diff --git a/CODEOWNERS b/CODEOWNERS index fffaf64564e559bbf9ca4ffd5d5a65e228b26e00..8110a344a6207d0b267e0bd7fd948fb22de01227 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -330,7 +330,7 @@ zh-cn/application-dev/reference/apis/js-apis-prompt.md @HelloCrease @niulihua @t zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @blackstone-oh zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids -zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984 +zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @hanruofei @murphy1984 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 @@ -365,7 +365,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-notification.md @jayleehw @R zh-cn/application-dev/reference/apis/js-apis-system-package.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @HelloCrease @niulihua @tomatodevboy -zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 +zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @ningningW @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-router.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-system-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 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/file-management/photoAccessHelper-notify-guidelines.md b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md index 12e1f2c5beb2db4a666ad0cb7ec1b8b2989a071f..c216c76b8587b1d5e899c624de247f04ae25f511 100644 --- a/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md @@ -81,7 +81,7 @@ import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, 'albumName'); let fetchOptions: dataSharePredicates.FetchOptions = { fetchColumns: [], diff --git a/en/application-dev/file-management/photoAccessHelper-overview.md b/en/application-dev/file-management/photoAccessHelper-overview.md index e8317f562e6ea8f8b0948606cb2d42f1e164480c..719da5ea9e1851316038dc0e92095154e715c7e6 100644 --- a/en/application-dev/file-management/photoAccessHelper-overview.md +++ b/en/application-dev/file-management/photoAccessHelper-overview.md @@ -108,7 +108,7 @@ The required permissions must be authorized by the user (user_grant). After addi onWindowStageCreate(windowStage) { let list : Array = ['ohos.permission.READ_IMAGEVIDEO', 'ohos.permission.WRITE_IMAGEVIDEO']; let permissionRequestResult; - let atManager = abilityAccessCtrl.createAtManager(); + let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(this.context, list, (err, result) => { if (err) { console.error('requestPermissionsFromUserError: ' + JSON.stringify(err)); diff --git a/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md b/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md index a517b4fb4cb1b6b2cd7711fdb68277292b7c6f7f..1d9a2406ea9416ec02e52dcb9f699807546ed72f 100644 --- a/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md @@ -99,8 +99,8 @@ import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // The value of the start time is the number of seconds elapsed since the Epoch time. -let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time. +let startTime: Number = Date.parse(new Date('2022-06-01').toString()) / 1000; // The value of the start time is the number of seconds elapsed since the Epoch time. +let endTime: Number = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time. let date_added: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.DATE_ADDED; predicates.between(date_added, startTime, endTime); predicates.orderByDesc(date_added); // Sort the obtained records in descending order. @@ -152,9 +152,10 @@ Example: Obtain the thumbnail of 720 x 720 of an image. ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; +import image from '@ohos.multimedia.image'; let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: dataSharePredicates.FetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -163,9 +164,9 @@ try { let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - let size = { width: 720, height: 720 }; - let pixelMap = await fileAsset.getThumbnail(size); - let imageInfo = await pixelMap.getImageInfo() + let size: image.Size = { width: 720, height: 720 }; + let pixelMap: image.PixelMap = await fileAsset.getThumbnail(size); + let imageInfo: image.ImageInfo = await pixelMap.getImageInfo() console.info('getThumbnail successful, pixelMap ImageInfo size: ' + JSON.stringify(imageInfo.size)); fetchResult.close(); } catch (err) { @@ -195,12 +196,12 @@ Example: Create an image asset. import photoAccessHelper from '@ohos.file.photoAccessHelper'; try { - let displayName = 'testPhoto' + Date.now() + '.jpg'; + let displayName: string = 'testPhoto' + Date.now() + '.jpg'; let createOption: photoAccessHelper.CreateOptions = { subType: photoAccessHelper.PhotoSubtype.DEFAULT }; - let fileAsset = await phAccessHelper.createAsset(displayName, createOption); + let fileAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(displayName, createOption); console.info('createAsset successfully, file displayName: ' + fileAsset.displayName); } catch (err) { console.error('createAsset failed, message = ', err); @@ -235,7 +236,7 @@ import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: dataSharePredicates.FetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: ['title'], predicates: predicates }; @@ -280,7 +281,7 @@ import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: dataSharePredicates.FetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; diff --git a/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md index 19c3434cca92143b5ff3fc104a81762c934b9e9b..b6b7b75d098724db75545a560bdda061096e04af 100644 --- a/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md @@ -62,16 +62,16 @@ Example: Favorite an image. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions: dataSharePredicates.FetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); let favoriteState = true; await fileAsset.setFavorite(favoriteState); @@ -102,8 +102,8 @@ Example: Obtain an image from **Favorites**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: dataSharePredicates.FetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -113,8 +113,8 @@ try { let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - let photoFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); photoFetchResult.close(); albumFetchResult.close(); @@ -145,8 +145,8 @@ Example: Unfavorite an image. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: dataSharePredicates.FetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -156,8 +156,8 @@ try { let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - let photoFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); let favoriteState = false; await fileAsset.setFavorite(favoriteState); @@ -221,8 +221,8 @@ Example: Obtain a video in **Videos**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: dataSharePredicates.FetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -232,8 +232,8 @@ try { let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get video Album successfully, albumUri: ' + album.albumUri); - let videoFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await videoFetchResult.getFirstObject(); + let videoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await videoFetchResult.getFirstObject(); console.info('video album getAssets successfully, albumName: ' + fileAsset.displayName); videoFetchResult.close(); albumFetchResult.close(); @@ -295,8 +295,8 @@ Example: Obtain a media asset from **Screenshots**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions: dataSharePredicates.FetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -306,8 +306,8 @@ try { let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get screenshot album successfully, albumUri: ' + album.albumUri); - let screenshotFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await screenshotFetchResult.getFirstObject(); + let screenshotFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await screenshotFetchResult.getFirstObject(); console.info('screenshot album getAssets successfully, albumName: ' + fileAsset.displayName); screenshotFetchResult.close(); albumFetchResult.close(); diff --git a/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md index db6c3a8058cef3e921b6ce15c5df09bac0cb6b5f..60d59a4448371c313bec743319910d9b0a3ebf04 100644 --- a/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md @@ -37,8 +37,8 @@ Example: Create a user album. import photoAccessHelper from '@ohos.file.photoAccessHelper'; try { - let albumName: photoAccessHelper.AlbumName = 'albumName'; - let album: photoAccessHelper.Album = await phAccessHelper.createAlbum(albumName); + let albumName = 'albumName'; + let album = await phAccessHelper.createAlbum(albumName); console.info('createAlbum successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); } catch (err) { console.error('createAlbum failed with err: ' + err); @@ -66,10 +66,10 @@ Example: Obtain the user album named **albumName**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, 'albumName'); -let fetchOptions: dataSharePredicates.FetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -111,10 +111,10 @@ Example: Rename an album named **albumName**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper..AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, 'albumName'); -let fetchOptions: dataSharePredicates.FetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -156,16 +156,16 @@ Example: Add an image to the album **albumName**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let albumPredicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; +let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper..AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; albumPredicates.equalTo(albumName, 'albumName'); let albumFetchOptions: dataSharePredicates.FetchOptions = { fetchColumns: [], predicates: albumPredicates }; -let photoPredicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: dataSharePredicates.FetchOptions = { +let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: photoPredicates }; @@ -174,8 +174,8 @@ try { let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult = await phAccessHelper.getAssets(photoFetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(photoFetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('getAssets successfully, albumName: ' + fileAsset.displayName); await album.addAssets([fileAsset]); albumFetchResult.close(); @@ -209,16 +209,16 @@ Example: Obtain an image in the user album **albumName**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let albumPredicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; +let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: dataSharePredicates.FetchOptions = { +let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: albumPredicates }; -let photoPredicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: dataSharePredicates.FetchOptions = { +let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: photoPredicates }; @@ -227,8 +227,8 @@ try { let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult = await album.getAssets(photoFetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(photoFetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); albumFetchResult.close(); photoFetchResult.close(); @@ -264,16 +264,16 @@ Example: Remove an image from the album named **albumName**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let albumPredicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; +let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions: dataSharePredicates.FetchOptions = { +let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: albumPredicates }; -let photoPredicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions: dataSharePredicates.FetchOptions = { +let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: photoPredicates }; @@ -282,8 +282,8 @@ try { let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); - let photoFetchResult = await album.getAssets(photoFetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(photoFetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('album getAssets successfully, albumName: ' + fileAsset.displayName); await album.removeAssets([fileAsset]); albumFetchResult.close(); @@ -315,10 +315,10 @@ Example: Delete a user album named **albumName**. import dataSharePredicates from '@ohos.data.dataSharePredicates'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates: dataSharePredicates = new dataSharePredicates.DataSharePredicates(); -let albumName: photoAccessHelper.AlbumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, '%albumName%'); -let fetchOptions: dataSharePredicates.FetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; 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-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/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/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index e1f64b915980aa23b9c1154f435a500a34922938..2848929b4d30fbc206344134e3e8047d030815d5 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -206,6 +206,7 @@ - [@ohos.arkui.dragController (DragController)](js-apis-arkui-dragController.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.inspector (Layout Callback)](js-apis-arkui-inspector.md) + - [@ohos.arkui.performanceMonitor (Performance Monitor)](js-apis-arkui-performancemonitor.md) - [@ohos.arkui.UIContext (UIContext)](js-apis-arkui-UIContext.md) - [@ohos.curves (Interpolation Calculation)](js-apis-curve.md) - [@ohos.font (Custom Font Registration)](js-apis-font.md) diff --git a/en/application-dev/reference/apis/js-apis-arkui-performancemonitor.md b/en/application-dev/reference/apis/js-apis-arkui-performancemonitor.md new file mode 100644 index 0000000000000000000000000000000000000000..b0722ac2aaf43f8a958ce53f0dbe2b02c41fc4c7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-arkui-performancemonitor.md @@ -0,0 +1,71 @@ +# @ohos.arkui.performanceMonitor (Performance Monitor) + +The **performanceMonitor** module provides APIs for performance monitoring indicators: response delay, completion delay, and frame loss rate. + +> **NOTE** +> +> The APIs of this module are supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + + +## Modules to Import + +```ts +import performanceMonitor from '@ohos.arkui.performanceMonitor'; +``` + + +## ActionType + +Enumerates types of actions that trigger user scenes. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Value| Description| +| -- | -- | -- | +| LAST_DOWN | 0 | Pressing against the screen. | +| LAST_UP | 1 | Lifting a finger off the screen.| +| FIRST_MOVE | 2 | First swiping on the screen.| + + +## performanceMonitor.begin + +begin(scene: string, startInputType: ActionType, note?: string): void + +Starts a user scene. + + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Description| +| -- | -- | -- | -- | +| scene | string | Yes| User scene ID.| +| startInputType | [ActionType](#actiontype)| Yes| Type of action that triggers the user scene.| +| note | string| No| Important information about the user scene.| + +**Example** + ```ts +performanceMonitor.begin("LAUNCHER_APP_LAUNCH_FROM_ICON", performanceMonitor.ActionType.LAST_UP, "APP_START_BEGIN"); + ``` + + +## performanceMonitor.end + +end(scene: string): void + +Ends a user scene. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -- | -- | -- | -- | +| scene | string | Yes| User scene ID, which corresponds to that in **begin**.| + +**Example** + ```ts +performanceMonitor.end("LAUNCHER_APP_LAUNCH_FROM_ICON"); + ``` 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-enterprise-bundleManager.md b/en/application-dev/reference/apis/js-apis-enterprise-bundleManager.md index 949307fcf0c0ac3211aa279c99412fe0d53551c4..470c211d35663aa83374f9dc1ef075c021fcba60 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-bundleManager.md @@ -1546,3 +1546,168 @@ bundleManager.uninstall(wantTemp, 'bundleName', 100, true).then(() => { console.error(`Failed to uninstall bundles. Code is ${err.code}, message is ${err.message}`); }); ``` + +## bundleManager.install + +install(admin: Want, hapFilePaths: Array\, callback: AsyncCallback\): void + +Installs applications through the specified device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_INSTALL_BUNDLE + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| hapFilePaths | Array\ | Yes | Applications to install.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | +| 9201002 | the application install failed. | + +**Example** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/testinstall/ExtensionTest.hap'] + +bundleManager.install(wantTemp, hapFilePaths, (err) => { + if (err) { + console.error(`Failed to install bundles. Code is ${err.code}, message is ${err.message}`); + } + console.info('Succeeded in installing bundles'); +}); +``` + +## bundleManager.install + +install(admin: Want, hapFilePaths: Array\, installParam: InstallParam, callback: AsyncCallback\): void + +Installs applications with specified parameters through the specified device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_INSTALL_BUNDLE + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| hapFilePaths | Array\ | Yes | Applications to install.| +| installParam | [InstallParam](#installparam) | Yes | Application installation parameters.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | +| 9201002 | the application install failed. | + +**Example** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/testinstall/ExtensionTest.hap'] +let installParam = { + userId: 100, + installFlag: 1, +}; + +bundleManager.install(wantTemp, hapFilePaths, installParam, (err) => { + if (err) { + console.error(`Failed to install bundles. Code is ${err.code}, message is ${err.message}`); + } + console.info('Succeeded in installing bundles'); +}); +``` + +## bundleManager.install + +install(admin: Want, hapFilePaths: Array\, installParam?: InstallParam): Promise\ + +Installs applications through the specified device administrator application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_INSTALL_BUNDLE + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| hapFilePaths | Array\ | Yes | Applications to install.| +| installParam | [InstallParam](#installparam) | No | Application installation parameters.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<void> | Promise that returns no value. If the operation fails, an error object will be thrown.| + +**Error codes** + +For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | +| 9201002 | the application install failed. | + +**Example** + +```js +let wantTemp = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', +}; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/testinstall/ExtensionTest.hap'] + +bundleManager.install(wantTemp, hapFilePaths).then(() => { + console.info('Succeeded in installing bundles'); +}).catch((err) => { + console.error(`Failed to install bundles. Code is ${err.code}, message is ${err.message}`); +}); +``` + +## InstallParam + +Defines the parameters specified for installing applications. + + **System capability**: SystemCapability.Customization.EnterpriseDeviceManager + + **System API**: This is a system API. + +| Name | Type | Mandatory | Description | +| ------------------------------ | ------------------------------ | ------------------ | ------------------ | +| userId | number | No | User ID, which must be greater than or equal to 0. The default value is the user ID of the caller. | +| installFlag | number | No | Installation flag.
- **0**: initial installation.
- **1**: overwrite installation.
- **2**: installation-free.
Default value: **0** | + diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 2acac025ffeffe32677f5af17b1e1cabfeb6655b..4fa35b6878ef99f3509af1444e38e89c2ab6f4fd 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -3,7 +3,7 @@ The **settings** module provides APIs for setting data items. > **NOTE** -> +> > The initial APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -24,8 +24,8 @@ Provides data items for setting the time and date formats. | ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | DATE_FORMAT | string | Yes | Yes | Date format.
The value can be **mm/dd/yyyy**, **dd/mm/yyyy**, or **yyyy/mm/dd**, where **mm** indicates the month, **dd** indicates the day, and **yyyy** indicates the year.| | TIME_FORMAT | string | Yes | Yes | Time format.
**12**: 12-hour format.
**24**: 24-hour format.| -| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
The value **true** means that the date, time, and time zone are automatically obtained from NITZ; and **false** means the opposite. | -| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.
The value **true** means that the time zone is automatically obtained from NITZ; and **false** means the opposite. | +| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
The value **true** means that the date, time, and time zone are automatically obtained from NITZ;
and **false** means the opposite.| +| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.
The value **true** means that the time zone is automatically obtained from NITZ;
and **false** means the opposite.| ## display @@ -39,7 +39,7 @@ Provides data items for setting the display effects. | ----------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | FONT_SCALE | string | Yes | Yes | Scale factor of the font. The value is a floating point number. | | SCREEN_BRIGHTNESS_STATUS | string | Yes | Yes | Screen brightness. The value ranges from 0 to 255. | -| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.
**AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.
**MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled. | +| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.
**AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.

**MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled.| | AUTO_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is enabled. | | MANUAL_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is disabled. | | SCREEN_OFF_TIMEOUT | string | Yes | Yes | Waiting time for the device to enter the sleep state when not in use (unit: ms). | @@ -47,7 +47,7 @@ Provides data items for setting the display effects. | ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration. This affects the start delay and duration of all such animations.
If the value is **0**, the animation ends immediately. The default value is **1**.| | TRANSITION_ANIMATION_SCALE | string | Yes | Yes | Scale factor for transition animations.
The value **0** indicates that the transition animations are disabled. | | WINDOW_ANIMATION_SCALE | string | Yes | Yes | Scale factor for normal window animations.
The value **0** indicates that window animations are disabled. | -| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.
**1**: Display color inversion is enabled.
**0**: Display color inversion is disabled.| +| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.
**1**: Display color inversion is enabled.

**0**: Display color inversion is disabled.| ## general @@ -186,57 +186,57 @@ Provides data items for setting wireless network information. | WIFI_WATCHDOG_STATUS | string | Yes | Yes | Whether Wi-Fi watchdog is available.
**true**: Wi-Fi watchdog is available.
**false**: Wi-Fi watchdog is unavailable.| -## settings.setValue +## settings.setValue10+ -setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object, callback: AsyncCallback\): void +setValue(context: Context, name: string, value: string, callback: AsyncCallback\): void -Sets the value for a data item. This API uses an asynchronous callback to return the result. +Sets the value for a data item. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.Applications.settings.Core +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | object | Yes | Value of the data item. The value range varies by service. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the operation is successful; returns **false** otherwise. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | string | Yes | Value of the data item. The value range varies by service. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the operation is successful; returns **false** otherwise. | **Example** ```js -import featureAbility from '@ohos.ability.featureAbility'; +import settings from '@ohos.settings'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) -let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); -let helper = featureAbility.acquireDataAbilityHelper(uri); -// @ts-ignore -// The value of the data item is a string. -settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => { - console.log('Callback return whether value is set.'); +settings.setValue(this.context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => { + console.log('Callback return whether value is set.'); }); ``` -## settings.setValue +## settings.setValue10+ -setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object): Promise\ +setValue(context: Context, name: string, value: string): Promise\ Sets the value for a data item. This API uses a promise to return the result. -**System API**: This is a system API. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.Applications.settings.Core +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | object | Yes | Value of the data item. The value range varies by service. | +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | string | Yes | Value of the data item. The value range varies by service. | **Return value** @@ -247,18 +247,149 @@ Sets the value for a data item. This API uses a promise to return the result. **Example** ```js -import featureAbility from '@ohos.ability.featureAbility'; +import settings from '@ohos.settings'; // Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) -let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); -let helper = featureAbility.acquireDataAbilityHelper(uri); -// @ts-ignore -// The value of the data item is a string. -settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => { - console.log('Callback return whether value is set.'); +settings.setValue(this.context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => { + console.log('Callback return whether value is set.'); +}); +``` + +## setting.getValue10+ + +getValue(context: Context, name: string, callback: AsyncCallback\): void + +Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | + +**Example** + +```js +import settings from '@ohos.settings'; + +settings.getValue(this.context, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, value) => { + if (err) { + console.error(`Failed to get the setting. ${err.message} `); + return; + } + console.log(`callback:value -> ${JSON.stringify(value)}`) }); ``` +## setting.getValue10+ + +getValue(context: Context, name: string): Promise\ + +Obtains the value of a data item in the database. This API uses a promise to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------- | +| Promise\ | Promise used to return the value of the data item.| + +**Example** + +```js +import settings from '@ohos.settings'; + +settings.getValue(this.context, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value) => { + console.log(`promise:value -> ${JSON.stringify(value)}`) +}); +``` + +## settings.getValueSync10+ + +getValueSync(context: Context, name: string, defValue: string): string; + +Obtains the value of a data item. Unlike **getValue**, this API returns the result synchronously. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.| + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| string | Value of the data item.| + +**Example** + +```js +import settings from '@ohos.settings'; + +// Obtain the value of SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database). +let value = settings.getValueSync(this.context, settings.display.SCREEN_BRIGHTNESS_STATUS, '10'); +``` + +## settings.setValueSync10+ + +setValueSync(context: Context, name: string, value: string): boolean + +Sets the value for a data item. Unlike **setValue**, this API returns the result synchronously. + +If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Applications.settings.Core + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | string | Yes | Value of the data item. The value range varies by service. | + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Result indicating whether the value is set successfully. Returns **true** if the value is set successfully; returns **false** otherwise.| + +**Example** + +```js +import settings from '@ohos.settings'; + +// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync API will update the value of the data item.) +let ret = settings.setValueSync(this.context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100'); +``` + ## settings.enableAirplaneMode enableAirplaneMode(enable: boolean, callback: AsyncCallback\): void @@ -390,7 +521,7 @@ Obtains the URI of a data item. ```js // Obtain the URI of a data item. -let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let uriVar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); ``` ## setting.getURI(deprecated) @@ -401,7 +532,7 @@ Obtains the URI of a data item. This API uses an asynchronous callback to return > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. No substitute API is provided. **System capability**: SystemCapability.Applications.settings.Core @@ -428,7 +559,7 @@ Obtains the URI of a data item. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. No substitute API is provided. **System capability**: SystemCapability.Applications.settings.Core @@ -452,6 +583,91 @@ settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS).then((uri) => { }) ``` +## settings.setValue(deprecated) + +setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object, callback: AsyncCallback\): void + +Sets the value for a data item. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setValue()](#settingssetvalue10) instead. + +**System API**: This is a system API. + +**Model restriction**: This API can be used only in the FA model. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | object | Yes | Value of the data item. The value range varies by service. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **true** if the operation is successful; returns **false** otherwise. | + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +//@ts-ignore +// The value of the data item is a string. +settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => { + console.log('Callback return whether value is set.'); +}); +``` + +## settings.setValue(deprecated) + +setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object): Promise\ + +Sets the value for a data item. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setValue()](#settingssetvalue10-1) instead. + +**System API**: This is a system API. + +**Model restriction**: This API can be used only in the FA model. + +**System capability**: SystemCapability.Applications.settings.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | object | Yes | Value of the data item. The value range varies by service. | + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------------------------- | +| Promise\ | Promise used to return the result. Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.) +let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS); +let helper = featureAbility.acquireDataAbilityHelper(uri); +//@ts-ignore +// The value of the data item is a string. +settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => { + console.log('Callback return whether value is set.'); +}); +``` + ## setting.getValue(deprecated) getValue(dataAbilityHelper: DataAbilityHelper, name: string, callback: AsyncCallback\): void @@ -460,7 +676,7 @@ Obtains the value of a data item in the database. This API uses an asynchronous > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getValue()](#settinggetvalue10) instead. **Model restriction**: This API can be used only in the FA model. @@ -468,11 +684,11 @@ Obtains the value of a data item in the database. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| callback | AsyncCallback\ | Yes | Callback used to return the value of the data item. | **Example** @@ -498,7 +714,7 @@ Obtains the value of a data item in the database. This API uses a promise to ret > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getValue()](#settinggetvalue10-1) instead. **Model restriction**: This API can be used only in the FA model. @@ -506,10 +722,10 @@ Obtains the value of a data item in the database. This API uses a promise to ret **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| **Return value** @@ -537,7 +753,7 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getValueSync()](#settingsgetvaluesync10) instead. **Model restriction**: This API can be used only in the FA model. @@ -545,11 +761,11 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.| +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.| **Return value** @@ -578,7 +794,7 @@ If the specified data item exists in the database, the **setValueSync** method u > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setValueSync()](#settingssetvaluesync10) instead. **Model restriction**: This API can be used only in the FA model. @@ -588,11 +804,11 @@ If the specified data item exists in the database, the **setValueSync** method u **Parameters** -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | -| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| -| value | string | Yes | Value of the data item. The value range varies by service. | +| name | string | Yes | Name of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items| +| value | string | Yes | Value of the data item. The value range varies by service. | **Return value** 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/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/ts-basic-components-progress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md index 060e00b1e3eca27a007342fe68ae309fe6e3d0b6..67923167b53a9bb450c157ed6e5eab46cefee56c 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**| +| enableSmoothEffect | 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,15 @@ 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**| +| enableSmoothEffect | 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**| +| strokeRadius | [PX](ts-types.md#px10) \| [VP](ts-types.md#vp10) \| [LPX](ts-types.md#lpx10) \| [Resource](ts-types.md#resource)| No | Rounded corner radius of the progress indicator.
Value range: [0, strokeWidth/2] Default value: **strokeWidth/2**| | enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**| +| enableSmoothEffect | 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,15 +107,18 @@ 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**| +| enableSmoothEffect | 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 | +| ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | +| enableSmoothEffect | 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 | | ----------------------- | ---------------- | -| LOADING10+ | Loading.| -| PROGRESSING10+ | The progress is being updated.| +| LOADING | Loading.| +| PROGRESSING | The progress is being updated.| ## Events @@ -249,3 +257,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/device-dev/porting/porting-smallchip-driver-oom.md b/en/device-dev/porting/porting-smallchip-driver-oom.md index ea579c6746607029bc6d994f979d54fd18b137c7..9488e6dc7ae2e0ea44b5e3a960f791c77a1b42a2 100644 --- a/en/device-dev/porting/porting-smallchip-driver-oom.md +++ b/en/device-dev/porting/porting-smallchip-driver-oom.md @@ -1,386 +1,280 @@ -# Device Driver Porting +# Device Driver Porting This section describes how to port device drivers. -## LCD Driver Porting +## LCD Driver Porting To port an LCD driver, write the driver, create an instance of the corresponding model in the driver, and complete the registration. -The LCD drivers are stored in **//drivers/framework/model/display/driver/panel**. +The LCD drivers are stored in **//drivers/hdf_core/framework/model/display/driver/panel**. 1. Create a panel driver. - Create an HDF driver and call the **RegisterPanel** method to register a model instance during driver initialization. - - ``` - int32_t LCDxxEntryInit(struct HdfDeviceObject *object) - { - struct PanelData *panel = CreateYourPanel(); - // Register a model instance. - if (RegisterPanel(panel) != HDF_SUCCESS) { - HDF_LOGE("%s: RegisterPanel failed", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; - } - - struct HdfDriverEntry g_xxxxDevEntry = { - .moduleVersion = 1, - .moduleName = "LCD_XXXX", - .Init = LCDxxEntryInit, - }; - - HDF_INIT(g_xxxxDevEntry); - ``` + Create an HDF driver and call the **RegisterPanel** method to register a model instance during driver initialization. + + + ``` + int32_t LCDxxEntryInit(struct HdfDeviceObject *object) + { + struct PanelData *panel = CreateYourPanel(); + // Register a model instance. + if (RegisterPanel(panel) != HDF_SUCCESS) { + HDF_LOGE("%s: RegisterPanel failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + + struct HdfDriverEntry g_xxxxDevEntry = { + .moduleVersion = 1, + .moduleName = "LCD_XXXX", + .Init = LCDxxEntryInit, + }; + + HDF_INIT(g_xxxxDevEntry); + ``` 2. Configure and load the panel driver. - Modify the source code file **//vendor/vendor\_name/product\_name/config/device\_info/device\_info.hcs**. Add configurations for the device named **device\_lcd** for the display host. + Modify the source code file **//vendor/vendor_name/product_name/config/device_info/device_info.hcs**. Add configurations for the device named **device\_lcd** for the display host. - >![](../public_sys-resources/icon-caution.gif) **CAUTION:** - >Make sure the value of **moduleName** is the same as that of **moduleName** in the panel driver. + > ![icon-caution.gif](public_sys-resources/icon-caution.gif) **CAUTION** + > Make sure the value of **moduleName** is the same as that of **moduleName** in the panel driver. - ``` - root { - ... - display :: host { - device_lcd :: device { - deviceN :: deviceNode { - policy = 0; - priority = 100; - preload = 2; - moduleName = "LCD_XXXX"; - } - } - } - } - ``` + + ``` + root { + ... + display :: host { + device_lcd :: device { + deviceN :: deviceNode { + policy = 0; + priority = 100; + preload = 2; + moduleName = "LCD_XXXX"; + } + } + } + } + ``` -## Touchscreen Driver Porting +## Touchscreen Driver Porting -This section describes how to port a touchscreen driver. The touchscreen drivers are stored in the source code directory **//drivers/framework/model/input/driver/touchscreen**. To port a touchscreen driver, register a **ChipDevice** model instance with the system. +This section describes how to port a touchscreen driver. The touchscreen drivers are stored in the source code directory **//drivers/hdf_core/framework/model/input/driver/touchscreen**. To port a touchscreen driver, register a **ChipDevice** model instance with the system. For details about how to develop a touchscreen driver, see [Touchscreen Development Guidelines](../driver/driver-peripherals-touch-des.md). 1. Create a touchscreen driver. - Create the **touch\_ic\_name.c** file in the **touchscreen** directory. Write the following content: - - ``` - #include "hdf_touch.h" - - static int32_t HdfXXXXChipInit(struct HdfDeviceObject *device) - { - ChipDevice *tpImpl = CreateXXXXTpImpl(); - if(RegisterChipDevice(tpImpl) != HDF_SUCCESS) {// Register the ChipDevice model instance. - ReleaseXXXXTpImpl(tpImpl); - return HDF_FAILURE; - } - return HDF_SUCCESS; - } - - struct HdfDriverEntry g_touchXXXXChipEntry = { - .moduleVersion = 1, - .moduleName = "HDF_TOUCH_XXXX", // Make sure the value is the same as that in the subsequent configuration. - .Init = HdfXXXXChipInit, - }; + Create the **touch\_ic\_name.c** file in the **touchscreen** directory. Write the following content: + + + ``` + #include "hdf_touch.h" + + static int32_t HdfXXXXChipInit(struct HdfDeviceObject *device) + { + ChipDevice *tpImpl = CreateXXXXTpImpl(); + if(RegisterChipDevice(tpImpl) != HDF_SUCCESS) { // Register the ChipDevice model instance. + ReleaseXXXXTpImpl(tpImpl); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + + struct HdfDriverEntry g_touchXXXXChipEntry = { + .moduleVersion = 1, + .moduleName = "HDF_TOUCH_XXXX", // Make sure the value is the same as that in the subsequent configuration. + .Init = HdfXXXXChipInit, + }; + + HDF_INIT(g_touchXXXXChipEntry); + ``` + + The following methods need to be implemented in **ChipDevice**: - HDF_INIT(g_touchXXXXChipEntry); - ``` - - The following methods need to be implemented in **ChipDevice**: - - - - - - - - - - - - - - - - - - - - - - - - - -

Method

-

Description

-

int32_t (*Init)(ChipDevice *device)

-

Initializes the device.

-

int32_t (*Detect)(ChipDevice *device)

-

Detects the device.

-

int32_t (*Suspend)(ChipDevice *device)

-

Places the device in sleep mode.

-

int32_t (*Resume)(ChipDevice *device)

-

Wakes up the device.

-

int32_t (*DataHandle)(ChipDevice *device)

-

Reads data from the device and writes touch point data to device > driver > frameData.

-

int32_t (*UpdateFirmware)(ChipDevice *device)

-

Updates the firmware.

-
+ | Method | Description | + | -------- | -------- | + | int32_t (\*Init)(ChipDevice \*device) | Initializes the device. | + | int32_t (\*Detect)(ChipDevice \*device) | Detects the device. | + | int32_t (\*Suspend)(ChipDevice \*device) | Places the device in sleep mode. | + | int32_t (\*Resume)(ChipDevice \*device) | Wakes up the device. | + | int32_t (\*DataHandle)(ChipDevice \*device) | Reads data from the device and writes touch point data to device > driver > frameData. | + | int32_t (\*UpdateFirmware)(ChipDevice \*device) | Updates the firmware. | 2. Configure the product and load the driver. - All device information of the product is defined in the source code file **//vendor/vendor\_name/product\_name/config/device\_info/device\_info.hcs**. Modify the file and add configurations to the **device** named **device\_touch\_chip** in the **host** of the **input** command. + All device information of the product is defined in the source code file **//vendor/vendor_name/product_name/config/device_info/device_info.hcs**. Modify the file and add configurations to the **device** named **device\_touch\_chip** in the **host** of the **input** command. - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >Make sure the value of **moduleName** is the same as that of **moduleName** in the touchscreen driver. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > Make sure the value of **moduleName** is the same as that of **moduleName** in the touchscreen driver. - ``` - deviceN :: deviceNode { - policy = 0; - priority = 130; - preload = 0; - permission = 0660; - moduleName = "HDF_TOUCH_XXXX"; - deviceMatchAttr = "touch_XXXX_configs"; - } - ``` + ``` + deviceN :: deviceNode { + policy = 0; + priority = 130; + preload = 0; + permission = 0660; + moduleName = "HDF_TOUCH_XXXX"; + deviceMatchAttr = "touch_XXXX_configs"; + } + ``` -## WLAN Driver Porting + +## WLAN Driver Porting The WLAN driver is divided into two parts. One of the parts manages WLAN devices, and the other part manages WLAN traffic. -**Figure 1** OpenHarmony WLAN driver architecture - - -![](figures/hdf_wifi.png) - -As shown in [Figure 1](#fig155920160203), the part on the left manages WLAN devices, and the part on the right manages WLAN traffic. The HDF WLAN framework abstracts these two parts. The porting process of the driver can be considered as the implementation of the APIs required by the two parts. These APIs are described as follows: - - - - - - - - - - - - - - - - - - - - -

API

-

Header File

-

API Description

-

HdfChipDriverFactory

-

drivers\framework\include\wifi\hdf_wlan_chipdriver_manager.h

-

Factory of the ChipDriver, which is used to support multiple WLAN interfaces of a chip.

-

HdfChipDriver

-

drivers\framework\include\wifi\wifi_module.h

-

Manages a specific WLAN interface.

-

NetDeviceInterFace

-

drivers\framework\include\wifi\net_device.h

-

Communicates with the protocol stack, such as sending data and setting the status of network interfaces.

-
- ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->For details about the API development, see [WLAN Development Guidelines](../driver/driver-peripherals-external-des.md). +**Figure 1** OpenHarmony WLAN driver architecture + + ![hdf_wifi](figures/hdf_wifi.png) + +As shown in Figure 1, the part on the left manages WLAN devices, and the part on the right manages WLAN traffic. The HDF WLAN framework abstracts these two parts. The porting process of the driver can be considered as the implementation of the APIs required by the two parts. These APIs are described as follows: + +| API | Header File | Description | +| -------- | -------- | -------- | +| HdfChipDriverFactory | drivers\hdf_core\framework\include\wifi\hdf_wlan_chipdriver_manager.h | Factory of the ChipDriver, which is used to support multiple WLAN interfaces of a chip. | +| HdfChipDriver | drivers\hdf_core\framework\include\wifi\wifi_module.h | Manages a specific WLAN interface. | +| NetDeviceInterFace | drivers\hdf_core\framework\include\wifi\net_device.h | Communicates with the protocol stack, such as sending data and setting the status of network interfaces. | + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> For details about the API development, see [WLAN Development Guidelines](../driver/driver-peripherals-external-des.md). The porting procedure is as follows: 1. Create a WLAN chip driver. - Create the **hdf\_wlan\_chip\_name.c** file in **/device/vendor\_name/peripheral/wifi/chip\_name/**. The sample code is as follows: - - ``` - static int32_t HdfWlanHisiChipDriverInit(struct HdfDeviceObject *device) { - static struct HdfChipDriverFactory factory = CreateChipDriverFactory(); // Implement the method. - struct HdfChipDriverManager *driverMgr = HdfWlanGetChipDriverMgr(); - if (driverMgr->RegChipDriver(&factory) != HDF_SUCCESS) {// Register the driver factory. - HDF_LOGE("%s fail: driverMgr is NULL!", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; - } - - struct HdfDriverEntry g_hdfXXXChipEntry = { - .moduleVersion = 1, - .Init = HdfWlanXXXChipDriverInit, - .Release = HdfWlanXXXChipRelease, - .moduleName = "HDF_WIFI_CHIP_XXX" // Make sure the name is the same as the configured one. - }; + Create the **hdf_wlan_chip_name.c** file in **/device/vendor_name/peripheral/wifi/chip_name/**. The sample code is as follows: + + ``` + static int32_t HdfWlanXXXChipDriverInit(struct HdfDeviceObject *device) { + static struct HdfChipDriverFactory factory = CreateChipDriverFactory(); // Implement the method. + struct HdfChipDriverManager *driverMgr = HdfWlanGetChipDriverMgr(); + if (driverMgr->RegChipDriver(&factory) != HDF_SUCCESS) { // Register the driver factory. + HDF_LOGE("%s fail: driverMgr is NULL!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + + struct HdfDriverEntry g_hdfXXXChipEntry = { + .moduleVersion = 1, + .Init = HdfWlanXXXChipDriverInit, + .Release = HdfWlanXXXChipRelease, + .moduleName = "HDF_WIFI_CHIP_XXX" // Make sure the name is the same as the configured one. + }; + + HDF_INIT(g_hdfXXXChipEntry); + ``` + + In the **CreateChipDriverFactory** method, create an object of the **HdfChipDriverFactory** type. This object provides the following methods: - HDF_INIT(g_hdfXXXChipEntry); - ``` - - In the **CreateChipDriverFactory** method, create an object of the **HdfChipDriverFactory** type. This object provides the following methods: - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Method

-

Description

-

const char *driverName

-

Indicates the driver name.

-

int32_t (*InitChip)(struct HdfWlanDevice *device)

-

Initializes the chip.

-

int32_t (*DeinitChip)(struct HdfWlanDevice *device)

-

Deinitializes the chip.

-

void (*ReleaseFactory)(struct HdfChipDriverFactory *factory)

-

Releases the HdfChipDriverFactory object.

-

struct HdfChipDriver *(*Build)(struct HdfWlanDevice *device, uint8_t ifIndex)

-

Creates an HdfChipDriver. In the input parameters, device indicates the device information, and ifIndex indicates the sequence number of this interface in the chip.

-

void (*Release)(struct HdfChipDriver *chipDriver)

-

Releases the chip driver.

-

uint8_t (*GetMaxIFCount)(struct HdfChipDriverFactory *factory)

-

Obtains the maximum number of interfaces supported by the current chip.

-
- - The **Build** method creates an **HdfChipDriver** object that manages the specified network interface. This object needs to provide the following methods: - - - - - - - - - - - - - - - - - - - - - - -

Method

-

Description

-

int32_t (*init)(struct HdfChipDriver *chipDriver, NetDevice *netDev)

-

Initializes the current network interface. The NetDeviceInterFace needs to be provided for the netDev.

-

int32_t (*deinit)(struct HdfChipDriver *chipDriver, NetDevice *netDev)

-

Deinitializes the current network interface.

-

struct HdfMac80211BaseOps *ops

-

Provides the WLAN basic capability interface set.

-

struct HdfMac80211STAOps *staOps

-

Provides the interface set required for supporting the STA mode.

-

struct HdfMac80211APOps *apOps

-

Provides the interface set required for supporting the AP mode.

-
+ | Method | Description | + | -------- | -------- | + | const char \*driverName | Indicates the driver name. | + | int32_t (\*InitChip)(struct HdfWlanDevice \*device) | Initializes the chip. | + | int32_t (\*DeinitChip)(struct HdfWlanDevice \*device) | Deinitializes the chip. | + | void (\*ReleaseFactory)(struct HdfChipDriverFactory \*factory) | Releases the **HdfChipDriverFactory** object. | + | struct HdfChipDriver \*(\*Build)(struct HdfWlanDevice \*device, uint8_t ifIndex) | Creates an **HdfChipDriver**. In the input parameters, **device** indicates the device information, and **ifIndex** indicates the sequence number of this interface in the chip. | + | void (\*Release)(struct HdfChipDriver \*chipDriver) | Releases the chip driver. | + | uint8_t (\*GetMaxIFCount)(struct HdfChipDriverFactory \*factory) | Obtains the maximum number of interfaces supported by the current chip. | + + The **Build** method creates an **HdfChipDriver** object that manages the specified network interface. This object needs to provide the following methods: + + | Method | Description | + | -------- | -------- | + | int32_t (\*init)(struct HdfChipDriver \*chipDriver, NetDevice \*netDev) | Initializes the current network interface. The **NetDeviceInterFace** needs to be provided for the **netDev**. | + | int32_t (\*deinit)(struct HdfChipDriver \*chipDriver, NetDevice \*netDev) | Deinitializes the current network interface. | + | struct HdfMac80211BaseOps \*ops | Provides the WLAN basic capability interface set. | + | struct HdfMac80211STAOps \*staOps | Provides the interface set required for supporting the STA mode. | + | struct HdfMac80211APOps \*apOps | Provides the interface set required for supporting the AP mode. | 2. Create a configuration file to describe the chips supported by the driver. - Create a chip configuration file in the product configuration directory and save it to the source code path **//vendor/vendor\_name/product\_name/config/wifi/wlan\_chip\_chip\_name.hcs**. - - The sample code is as follows: - - ``` - root { - wlan_config { - chip_name :& chipList { - chip_name :: chipInst { - match_attr = "hdf_wlan_chips_chip_name"; /* Indicates the configuration matching attribute, which is used to provide the configuration root of the driver.*/ - driverName = "driverName"; /* Indicates the driver name, which must be the same as that of driverName in HdfChipDriverFactory.*/ - sdio { - vendorId = 0xXXXX; /* your vendor id */ - deviceId = [0xXXXX]; /*your supported devices */ - } - } - } - } - } - ``` - - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >Replace the values of **vendor\_name**, **product\_name**, and **chip\_name** in the path and file with the actual names. - >Set **vendorId** and **deviceId** to the actual vendor ID and chip ID, respectively. + Create a chip configuration file in the product configuration directory and save it to the source code path **//vendor/vendor\_name/product\_name/config/wifi/wlan\_chip\_chip\_name.hcs**. + + + + + ``` + root { + wlan_config { + chip_name :& chipList { + chip_name :: chipInst { + match_attr = "hdf_wlan_chips_chip_name"; /* Indicates the configuration matching attribute, which is used to provide the configuration root of the driver. */ + driverName = "driverName"; /* Indicates the driver name, which must be the same as that of driverName in HdfChipDriverFactory.*/ + sdio { + vendorId = 0xXXXX; /* your vendor id */ + deviceId = [0xXXXX]; /*your supported devices */ + } + } + } + } + } + ``` + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > Replace the values of **vendor\_name**, **product\_name**, and **chip\_name** in the path and file with the actual names. + > + > Set **vendorId** and **deviceId** to the actual vendor ID and chip ID, respectively. 3. Edit the configuration file and load the driver. - All device information of the product is defined in the source code file **//vendor/vendor\_name/product\_name/config/device\_info/device\_info.hcs**. Modify the file and add configurations to the **device** named **device\_wlan\_chips** in the **host** of the **network** command. The sample code is as follows: + All device information of the product is defined in the source code file **//vendor/vendor\_name/product\_name/config/device\_info/device\_info.hcs**. Modify the file and add configurations to the **device** named **device\_wlan\_chips** in the **host** of the **network** command. The sample code is as follows: + - ``` - deviceN :: deviceNode { - policy = 0; - preload = 2; - moduleName = "HDF_WLAN_CHIPS"; - deviceMatchAttr = "hdf_wlan_chips_chip_name"; - serviceName = "driverName"; - } - ``` + ``` + deviceN :: deviceNode { + policy = 0; + preload = 2; + moduleName = "HDF_WLAN_CHIPS"; + deviceMatchAttr = "hdf_wlan_chips_chip_name"; + serviceName = "driverName"; + } + ``` - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >Make sure the value of **moduleName** is the same as that of **moduleName** in the WLAN driver. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > Make sure the value of **moduleName** is the same as that of **moduleName** in the WLAN driver. -4. Modify the **Kconfig** file to make the ported WLAN driver appear in the kernel configuration. +4. Modify the **Kconfig** file to make the ported WLAN driver appear in the kernel configuration. - Add configurations to **device/vendor\_name/drivers/Kconfig**. The sample code is as follows: + Add configurations to **device/vendor\_name/drivers/Kconfig**. The sample code is as follows: - ``` - config DRIVERS_HDF_WIFI_chip_name - bool "Enable chip_name Host driver" - default n - depends on DRIVERS_HDF_WLAN help - Answer Y to enable chip_name Host driver. - ``` - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >Replace **chip\_name** with the actual chip name. + ``` + config DRIVERS_HDF_WIFI_chip_name + bool "Enable chip_name Host driver" + default n + depends on DRIVERS_HDF_WLAN help + Answer Y to enable chip_name Host driver. + ``` + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > Replace **chip\_name** with the actual chip name. 5. Modify the build script to enable the driver to participate in the kernel build. - Add the following content to the end of the source code file **//device/vendor\_name/drivers/lite.mk**: + Add the following content to the end of the source code file **//device/vendor\_name/drivers/lite.mk**: + - ``` - ifeq ($(LOSCFG_DRIVERS_HDF_WIFI_chip_name), y) - # After the build is complete, an object named hdf_wlan_chipdriver_chip_name needs to be linked. You are advised to use this name to prevent conflicts. - LITEOS_BASELIB += -lhdf_wlan_chipdriver_chip_name - # Add the build directory gpio. - LIB_SUBDIRS += ../peripheral/wifi/chip_name - endif - ``` + ``` + ifeq ($(LOSCFG_DRIVERS_HDF_WIFI_chip_name), y) + # After the build is complete, an object named hdf_wlan_chipdriver_chip_name needs to be linked. You are advised to use this name to prevent conflicts. + LITEOS_BASELIB += -lhdf_wlan_chipdriver_chip_name + # Add the build directory gpio. + LIB_SUBDIRS += ../peripheral/wifi/chip_name + endif + ``` - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >Replace **chip\_name** with the actual chip name. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > + > Replace **chip_name** with the actual chip name. diff --git a/en/device-dev/porting/porting-smallchip-kernel-linux.md b/en/device-dev/porting/porting-smallchip-kernel-linux.md index 5b9e57546e2b61296728c2ffb33806cf86181aca..c6de151328130e3191374cf67b32b743287dee5f 100644 --- a/en/device-dev/porting/porting-smallchip-kernel-linux.md +++ b/en/device-dev/porting/porting-smallchip-kernel-linux.md @@ -19,6 +19,7 @@ You can use the Bootloader provided by the chipset vendor or open-source U-Boot ## Adaptation, Building, Burning, and Startup 1. Prepare the kernel configuration files, especially the chipset-related configuration files. + Source code directory of the configuration files: **kernel/linux/config/** Create a **<*YOUR_CHIP*>_small_defconfig** file, such as **hi3516dv300_small_defconfig**, in the **linux-4.19/arch/arm/configs/** directory. The configuration file can be created by combining the general-purpose **small_common_defconfig** file and chipset-specific configurations. @@ -48,7 +49,7 @@ You can use the Bootloader provided by the chipset vendor or open-source U-Boot The burning mode varies according to the development board of the chipset. Pay attention to the size of each burnt image and the configuration of the boot parameters. Below is the U-Boot parameter settings of Hi3516D V300: - + ``` setenv bootargs 'mem=128M console=ttyAMA0,115200 root=/dev/mmcblk0p3 ro rootfstype=ext4 rootwait blkdevparts=mmcblk0:1M(boot),9M(kernel),50M(rootfs),50M(userfs)' ``` @@ -65,16 +66,23 @@ Debug the **init** process, start shell, and run a simple program in the user sp Based on the preceding process, the recommended verification procedure is as follows: 1. Create a root file system image. - + Create a root file system image **rootfs.img** by following instructions in [Building Procedures](../subsystems/subsys-build-all.md). As shown in the preceding figure, the startup process is closely related to the product configuration. You need to complete the following configuration when creating **rootfs.img**: - Component configuration + In the product component configuration file ***vendor*/{*company*}/{*product*}/config.json**, configure the **init** component of the startup subsystem and the **linux_4_1_9** component of the kernel subsystem. + - System service configuration + Modify the system service configuration file ***vendor*/{*company*}/{*product*}/init_configs/init_xxx.cfg** to start the shell service. + - File system configuration + In the file system configuration file ***vendor*/{*company*}/{*product*}/fs.yml**, create the **/bin/sh -> mksh** and **/lib/ld-musl-arm.so.1 -> libc.so** soft links. These two files are the shell executable program and the c library on which the executable program depends, respectively. + - Startup configuration + In the ***vendor*/{*company*}/{*product*}/init_configs/etc** directory, configure startup settings, including the **fstab**, **rsS**, and **S*xxx*** files. Configure the startup settings as needed. After the build is complete, check the **rootfs** content in the product compilation output directory to determine whether the generated **rootfs.img** file meets the expectation. diff --git a/en/device-dev/porting/porting-smallchip-prepare-building.md b/en/device-dev/porting/porting-smallchip-prepare-building.md index a894946516034af688f6f4fe00c4ddf685eca061..9dd844b40758eb57a30546115864878ac4249e3f 100644 --- a/en/device-dev/porting/porting-smallchip-prepare-building.md +++ b/en/device-dev/porting/porting-smallchip-prepare-building.md @@ -24,38 +24,38 @@ After learning the compilation framework and setting up the compilation environm The directory structure is as follows: device/{*chipset solution vendor*}/{*development board*}. For example, if you are using the hispark_taurus development board from HiSilicon, create the following directory in the root directory of the code: - ``` - mkdir -p device/hisilicon/hispark_taurus - ``` - + ``` + mkdir -p device/hisilicon/hispark_taurus + ``` + The chipset solution directory tree is as follows: + - - ``` - device - └── company # Chipset solution vendor - └── board # Name of the development board - ├── BUILD.gn # Build script - ├── hals # OS device API adaptation - ├── linux # (Optional) Linux kernel version - │ └── config.gni # Linux build configuration - └── liteos_a # (Optional) LiteOS kernel version - └── config.gni # LiteOS_A build configuration - ``` - + ``` + device + └── company # Chipset solution vendor + └── board # Name of the development board + ├── BUILD.gn # Build script + ├── hals # OS device API adaptation + ├── linux # (Optional) Linux kernel version + │ └── config.gni # Linux build configuration + └── liteos_a # (Optional) LiteOS kernel version + └── config.gni # LiteOS_A build configuration + ``` + For example, if you are porting the Linux kernel to the hispark_taurus development board, the directory tree is as follows: - ``` - device - └── hisilicon - └── hispark_taurus - ├── BUILD.gn - ├── hals - ├── ...... - └── linux - └── config.gni - ``` + ``` + device + └── hisilicon + └── hispark_taurus + ├── BUILD.gn + ├── hals + ├── ...... + └── linux + └── config.gni + ``` After the directory tree is created, store the source code related to the development board in the **hispark_taurus** directory. @@ -64,63 +64,63 @@ After learning the compilation framework and setting up the compilation environm You can configure the build options in the **config.gni** file described in step 1. The compilation and building framework will then compile all OS components in the user space based on your configuration. The **config.gni** file contains the following key fields: - ``` - kernel_type: Kernel used by the development board, for example, LiteOS_A, LiteOS_M, or Linux. - kernel_version: Kernel version used by the development board, for example, 4.19. - board_cpu: CPU of the development board, for example, Cortex-A7 or RISCV32. - board_arch: Chipset architecture of the development board, for example, armv7-a or rv32imac. - board_toolchain: Name of the customized build toolchain used by the development board, for example, gcc-arm-none-eabi. If this field is not specified, ohos-clang will be used. - board_toolchain_prefix: Prefix of the toolchain, for example, gcc-arm-none-eabi. - board_toolchain_type: Toolchain type. Currently, only GCC and clang are supported. - board_cflags: Build options of the .c file configured for the development board. - board_cxx_flags: Build options of the .cpp file configured for the development board. - board_ld_flags: Linking options configured for the development board. - ``` - - For HiSilicon's hispark_taurus development board, the content in **device/hisilicon/hispark_taurus/config.gni** is as follows: - - ``` - # Board CPU type, e.g. "cortex-a7", "riscv32". - board_cpu = "cortex-a7" - - # Name of the toolchain used for system building - # E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf. - # Note: The "ohos-clang" toolchain is used by default. You can also customize the toolchain. - board_toolchain = "mips-linux-gnu-gcc" - - # Path where the toolchain is installed, which can be left blank if the installation path has been added to ~/.bashrc. - board_toolchain_path = - rebase_path("//prebuilts/gcc/linux-x86/arm/arm-linux-ohoseabi-gcc/bin", - root_build_dir) - - # Prefix of the toolchain - board_toolchain_prefix = "arm-linux-ohoseabi-" - - # Type of the compiler, which can be gcc or clang - board_toolchain_type = "gcc" - - # Build options related to the development board - board_cflags = [ - ] - board_cxx_flags = [ - ] - board_ld_flags = [] - - # Board related headfiles search path. - board_include_dirs = [] - board_include_dirs += [ rebase_path( - "//prebuilts/gcc/linux-x86/arm/arm-linux-ohoseabi-gcc/target/usr/include", - root_build_dir) ] - - # Board adapter dir for OHOS components. - board_adapter_dir = "" - - # Sysroot path. - board_configed_sysroot = "" - - # Board storage type, it used for file system generation. - storage_type = "emmc" - ``` + ``` + kernel_type: Kernel used by the development board, for example, LiteOS_A, LiteOS_M, or Linux. + kernel_version: Kernel version used by the development board, for example, 4.19. + board_cpu: CPU of the development board, for example, Cortex-A7 or RISCV32. + board_arch: Chipset architecture of the development board, for example, armv7-a or rv32imac. + board_toolchain: Name of the customized build toolchain used by the development board, for example, gcc-arm-none-eabi. If this field is not specified, ohos-clang will be used. + board_toolchain_prefix: Prefix of the toolchain, for example, gcc-arm-none-eabi. + board_toolchain_type: Toolchain type. Currently, only GCC and clang are supported. + board_cflags: Build options of the .c file configured for the development board. + board_cxx_flags: Build options of the .cpp file configured for the development board. + board_ld_flags: Linking options configured for the development board. + ``` + + For HiSilicon's hispark_taurus development board, the content in **device/hisilicon/hispark_taurus/config.gni** is as follows: + + ``` + # Board CPU type, e.g. "cortex-a7", "riscv32". + board_cpu = "cortex-a7" + + # Name of the toolchain used for system building + # E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf. + # Note: The "ohos-clang" toolchain is used by default. You can also customize the toolchain. + board_toolchain = "mips-linux-gnu-gcc" + + # Path where the toolchain is installed, which can be left blank if the installation path has been added to ~/.bashrc. + board_toolchain_path = + rebase_path("//prebuilts/gcc/linux-x86/arm/arm-linux-ohoseabi-gcc/bin", + root_build_dir) + + # Prefix of the toolchain + board_toolchain_prefix = "arm-linux-ohoseabi-" + + # Type of the compiler, which can be gcc or clang + board_toolchain_type = "gcc" + + # Build options related to the development board + board_cflags = [ + ] + board_cxx_flags = [ + ] + board_ld_flags = [] + + # Board related headfiles search path. + board_include_dirs = [] + board_include_dirs += [ rebase_path( + "//prebuilts/gcc/linux-x86/arm/arm-linux-ohoseabi-gcc/target/usr/include", + root_build_dir) ] + + # Board adapter dir for OHOS components. + board_adapter_dir = "" + + # Sysroot path. + board_configed_sysroot = "" + + # Board storage type, it used for file system generation. + storage_type = "emmc" + ``` 3. Edit the build script of the development board. @@ -128,16 +128,16 @@ After learning the compilation framework and setting up the compilation environm For example, edit the **device/hisilicon/hispark_taurus/BUILD.gn** file as follows: - - ``` - # It is recommended that the group name be the same as the development board name. - group("hispark_taurus") { - deps = [ "//kernel/linux/patches:linux_kernel" ] # Start kernel compilation. - deps += [ - ...... # Other compilation units of the development board - ] - } - ``` + + ``` + # It is recommended that the group name be the same as the development board name. + group("hispark_taurus") { + deps = [ "//kernel/linux/patches:linux_kernel" ] # Start kernel compilation. + deps += [ + ...... # Other compilation units of the development board + ] + } + ``` 4. Start building and debugging. diff --git a/en/device-dev/porting/standard-system-porting-guide.md b/en/device-dev/porting/standard-system-porting-guide.md index 6deec486cb12d358d87800db6615f061f7ba24eb..71661c364e524815ff1262d393d6e917d1b7cd09 100644 --- a/en/device-dev/porting/standard-system-porting-guide.md +++ b/en/device-dev/porting/standard-system-porting-guide.md @@ -30,10 +30,10 @@ Create a file named **config.json** in the **//vendor/MyProductVendor/*{product_ { "subsystem": "ace", "components": [ - { "component": "ace_engine_lite", "features":[""] } + { "component": "ace_engine_lite", "features":[] } ] - }, - … + }, + ... ] } @@ -41,29 +41,20 @@ Create a file named **config.json** in the **//vendor/MyProductVendor/*{product_ ``` The main configurations are as follows: -**product_name**: product name. This parameter is required. - -**version**: version. This parameter is required. - -**type**: system level, such as **small** or **standard**. This parameter is required. - -**target_cpu**: CPU type of the device, such as **arm64**, **riscv**, or **x86**. This parameter is required. - -**ohos_version**: operating system version. This parameter is optional. - -**device_company**: device manufacturer name. This parameter is required. - -**board**: board name. This parameter is required. - -**enable_ramdisk**: whether to enable the RAM disk. This parameter is required. - -**kernel_type**: kernel type. This parameter is optional. - -**kernel_version**: kernel version. This parameter is optional. Both **kernel_type** and **kernel_version** are fixed. - -**subsystems**: subsystem to enable. A subsystem can be treated as an independently built functional block. This parameter is required. - -**product_company**: device manufacturer name. It is not set in the configuration, but in the directory name, next to the vendor name. It can be accessed from **build.gn script**. +| Item| Description| +|-------|----------| +|product_name |(Mandatory) Product name.| +|version|(Mandatory) Version.| +|type|(Mandatory) System level, such as **small** and **standard**.| +|target_cpu |(Mandatory) CPU type of the device, such as **arm64**, **riscv**, or **x86**.| +|ohos_version|(Optional) Operating system version.| +|device_company|(Mandatory) Device manufacturer name.| +|board|(Mandatory) Development board name.| +|enable_ramdisk|(Mandatory) Whether to start the RAM disk.| +|kernel_type|(Optional) Kernel type.| +|kernel_version|(Optional) Kernel version. The values of both **kernel_type** and **kernel_version** are fixed in the standard system.| +|subsystems|(Mandatory) Subsystem to enable. A subsystem can be treated as an independently built functional block.| +|product_company|Device manufacturer name. It is not set in the configuration, but in the directory name, next to the vendor name. It can be accessed from **build.gn script**.| You can find predefined subsystems in **//build/subsystem_config.json**. You can also customize subsystems. @@ -89,7 +80,7 @@ Now, you need to port the Linux kernel to enable it to run successfully. ### Adding a Kernel-built Subsystem to the SoC -Add the following subsystem configuration to the **//build/subsystem_config.json** file: +Modify the **//build/subsystem_config.json** file to add a subsystem. For example, if **product_name** is **MyProduct**, configure the **//vendor/MyProductVendor/MyProduct/config.json** file as follows: ``` @@ -126,10 +117,10 @@ The **BUILD.gn** file is the only entry for building the subsystem. The expected build result described in the table below. -| File| Description| +| File| Description| | -------- | -------- | -| $root_build_dir/packages/phone/images/uImage | Kernel image.| -| $root_build_dir/packages/phone/images/uboot | Bootloader image.| +| $root_build_dir/packages/phone/images/uImage | Kernel image.| +| $root_build_dir/packages/phone/images/uboot | Bootloader image.| ### Verifying the Porting @@ -140,17 +131,18 @@ Now start build, and check whether the kernel image is generated as expected. 1. Overview of user-mode boot process -![user-mode boot](figures/user-mode boot.png) + ![user-mode boot](figures/user-mode boot.png) + When the system is powered on, the kernel loads and starts services and applications as follows: -1. The kernel loads the init process, which is specified by **cmdline** of the kernel when the bootloader starts the kernel, for example, **init=/init root/dev/xxx**. -2. After the init process is started, **tmpfs** and **procfs** are mounted and basic **dev** nodes are created to establish a basic root file system. -3. The init process starts the ueventd process to listen for device hot-swap events in the kernel and creates **dev** nodes for related devices as well as partitions for the block device. -4. After mounting partitions (**system** and **vendor**) of the block device, the init process scans for the init startup script of each system service and launches the respective service ability (SA). -5. Each SA registers with the samgr process, which serves as the service registration center. The samgr process assigns each SA with an ID, which will be used by an application to access the desired SA. -6. The foundation process implements application lifecycle management. It is a special SA service process that provides the user program management framework and basic services. -7. The appspawn process directly spawns the application process, eliminating the need for the application to load the JS runtime environment. This reduces the application startup time. + 1. The kernel loads the init process, which is specified by **cmdline** of the kernel when the bootloader starts the kernel, for example, **init=/init root/dev/xxx**. + 2. After the init process is started, **tmpfs** and **procfs** are mounted and basic **dev** nodes are created to establish a basic root file system. + 3. The init process starts the ueventd process to listen for device hot-swap events in the kernel and creates **dev** nodes for related devices as well as partitions for the block device. + 4. After mounting partitions (**system** and **vendor**) of the block device, the init process scans for the init startup script of each system service and launches the respective service ability (SA). + 5. Each SA registers with the samgr process, which serves as the service registration center. The samgr process assigns each SA with an ID, which will be used by an application to access the desired SA. + 6. The foundation process implements application lifecycle management. It is a special SA service process that provides the user program management framework and basic services. + 7. The appspawn process directly spawns the application process, eliminating the need for the application to load the JS runtime environment. This reduces the application startup time. 2. init module @@ -158,7 +150,7 @@ Now start build, and check whether the kernel image is generated as expected. When porting a new chip platform, you need to add the **/vendor/etc/init/init.{hardware}.cfg** file that contains the platform-level initialization configuration. This file is used to implement platform-level initialization, for example, installing the ko driver and configuring information on the related **/proc** nodes. - The code of the init process is stored in the **//base/startup/init** directory. This process is the first process in the system and does not depend on other processes. + The code of the init process is stored in the **//base/startup/init_lite** directory. This process is the first process in the system and does not depend on other processes. For details about how to develop the initialization configuration file, see [Startup](../subsystems/subsys-boot-overview.md). @@ -170,180 +162,184 @@ Now start build, and check whether the kernel image is generated as expected. This section describes how to port a Liquid Crystal Display (LCD) driver. The hardware driver framework (HDF) designs a driver model for the LCD. To support an LCD, you must compile a driver, generate a model instance in the driver, and register the instance. -The LCD drivers are stored in the **//drivers/framework/model/display/driver/panel** directory. +The LCD drivers are stored in the **//drivers/hdf_core/framework/model/display/driver/panel** directory. -- Create a panel driver. +1. Create a panel driver. - In the **Init** method of the driver, call **RegisterPanel** to register the model instance. + In the **Init** method of the driver, call **RegisterPanel** to register the model instance. For example: -``` -int32_t XXXInit(struct HdfDeviceObject *object) -{ - struct PanelData *panel = CreateYourPanel(); - - // Registration - if (RegisterPanel(panel) != HDF_SUCCESS) { - HDF_LOGE("%s: RegisterPanel failed", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} + ``` + int32_t XXXInit(struct HdfDeviceObject *object) + { + struct PanelData *panel = CreateYourPanel(); -struct HdfDriverEntry g_xxxxDevEntry = { - .moduleVersion = 1, - .moduleName = "LCD_XXXX", - .Init = XXXInit, -}; + // Registration + if (RegisterPanel(panel) != HDF_SUCCESS) { + HDF_LOGE("%s: RegisterPanel failed", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } -HDF_INIT(g_xxxxDevEntry); -``` + struct HdfDriverEntry g_xxxxDevEntry = { + .moduleVersion = 1, + .moduleName = "LCD_XXXX", + .Init = XXXInit, + }; -- Configure and load the panel driver. All device information about the product is defined in the **//vendor/MyProductVendor/MyProduct/config/device_info/device_info.hcs** file. Modify the file by adding configurations for the device named **device_lcd** to the host named **display**. Note: The value of **moduleName** must be the same as that in the panel driver. + HDF_INIT(g_xxxxDevEntry); + ``` - -``` -root { - ... - display :: host { - device_lcd :: device { - deviceN :: deviceNode { - policy = 0; - priority = 100; - preload = 2; - moduleName = "LCD_XXXX"; - } - } - } -} -``` +2. Configure and load the panel driver. All device information about the product is defined in the **//vendor/MyProductVendor/MyProduct/config/device_info/device_info.hcs** file. Modify the file by adding configurations for the device named **device_lcd** to the host named **display**. + + Note: The value of **moduleName** must be the same as that in the panel driver. -For details about driver development, see [LCD](../driver/driver-peripherals-lcd-des.md). + ``` + root { + ... + display :: host { + device_lcd :: device { + deviceN :: deviceNode { + policy = 0; + priority = 100; + preload = 2; + moduleName = "LCD_XXXX"; + } + } + } + } + ``` + + For details about driver development, see [LCD](../driver/driver-peripherals-lcd-des.md). ### Touchscreen -This section describes how to port a touchscreen driver. The touchscreen driver is stored in the **//drivers/framework/model/input/driver/touchscreen** directory. To port a touchscreen driver, register a **ChipDevice** model instance. +This section describes how to port a touchscreen driver. The touchscreen driver is stored in the **//drivers/hdf_core/framework/model/input/driver/touchscreen** directory. To port a touchscreen driver, register a **ChipDevice** model instance. -- Create a touchscreen driver. +1. Create a touchscreen driver. - Create the **touch_ic_name.c** file in the directory. Replace **ic_name** with the name of your chip. The file template is as follows: + Create the **touch_ic_name.c** file in the directory. Replace **ic_name** with the name of your chip. The file template is as follows: -``` -#include "hdf_touch.h" + ``` + #include "hdf_touch.h" -static int32_t HdfXXXXChipInit(struct HdfDeviceObject *device) -{ - ChipDevice *tpImpl = CreateXXXXTpImpl(); - if(RegisterChipDevice(tpImpl) != HDF_SUCCESS) { - ReleaseXXXXTpImpl(tpImpl); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} + static int32_t HdfXXXXChipInit(struct HdfDeviceObject *device) + { + ChipDevice *tpImpl = CreateXXXXTpImpl(); + if(RegisterChipDevice(tpImpl) != HDF_SUCCESS) { + ReleaseXXXXTpImpl(tpImpl); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } -struct HdfDriverEntry g_touchXXXXChipEntry = { - .moduleVersion = 1, - .moduleName = "HDF_TOUCH_XXXX", - .Init = HdfXXXXChipInit, -}; + struct HdfDriverEntry g_touchXXXXChipEntry = { + .moduleVersion = 1, + .moduleName = "HDF_TOUCH_XXXX", + .Init = HdfXXXXChipInit, + }; -HDF_INIT(g_touchXXXXChipEntry); -``` + HDF_INIT(g_touchXXXXChipEntry); + ``` -Implement the following APIs in **ChipDevice**: + Implement the following interfaces in **ChipDevice**: -| API| Description| -| -------- | -------- | -| int32_t (\*Init)(ChipDevice \*device) | Initializes a touchscreen.| -| int32_t (\*Detect)(ChipDevice \*device) | Detects a touchscreen.| -| int32_t (\*Suspend)(ChipDevice \*device) | Suspends a touchscreen.| -| int32_t (\*Resume)(ChipDevice \*device) | Resumes a touchscreen.| -| int32_t (\*DataHandle)(ChipDevice \*device) | Reads data from a touchscreen and writes the touch point data to **device** > **driver** > **frameData**.| -| int32_t (\*UpdateFirmware)(ChipDevice \*device) | Upgrades the firmware.| - -- Configure the product and load the driver. + | API| Description| + | -------- | -------- | + | int32_t (\*Init)(ChipDevice \*device) | Initializes a touchscreen.| + | int32_t (\*Detect)(ChipDevice \*device) | Detects a touchscreen.| + | int32_t (\*Suspend)(ChipDevice \*device) | Suspends a touchscreen.| + | int32_t (\*Resume)(ChipDevice \*device) | Resumes a touchscreen.| + | int32_t (\*DataHandle)(ChipDevice \*device) | Reads data from a touchscreen and writes the touch point data to **device** > **driver** > **frameData**.| + | int32_t (\*UpdateFirmware)(ChipDevice \*device) | Upgrades the firmware.| + +2. Configure the product and load the driver. - All device information about the product is defined in the **//vendor/MyProductVendor/MyProduct/config/device_info/device_info.hcs** file. Modify the file by adding configurations for the device named **device_touch_chip** to the host named **input**. Note: The value of **moduleName** must be the same as that in the touchscreen driver. + All device information about the product is defined in the **//vendor/MyProductVendor/MyProduct/config/device_info/device_info.hcs** file. Modify the file by adding configurations for the device named **device_touch_chip** to the host named **input**. Note: The value of **moduleName** must be the same as that in the touchscreen driver. -``` - deviceN :: deviceNode { - policy = 0; - priority = 130; - preload = 0; - permission = 0660; - moduleName = "HDF_TOUCH_XXXX"; - deviceMatchAttr = "touch_XXXX_configs"; - } -``` + + ``` + deviceN :: deviceNode { + policy = 0; + priority = 130; + preload = 0; + permission = 0660; + moduleName = "HDF_TOUCH_XXXX"; + deviceMatchAttr = "touch_XXXX_configs"; + } + ``` -For details about driver development, see [Touchscreen](../driver/driver-peripherals-touch-des.md). + For details about driver development, see [Touchscreen](../driver/driver-peripherals-touch-des.md). ### WLAN The WLAN driver is divided into two parts. One of the parts manages WLAN devices, and the other part manages WLAN traffic. HDF WLAN provides abstraction for the two parts. Currently, only the WLAN with the SDIO interface is supported. -**Figure 1** WLAN chip + **Figure 1** WLAN chip -![hdf_wifi](figures/hdf_wifi.png) + ![hdf_wifi](figures/hdf_wifi.png) To support a chip, implement a **ChipDriver** for it. The major task is to implement the following interfaces provided by **HDF_WLAN_CORE** and **NetDevice**. | API| Header File| Description| | -------- | -------- | -------- | -| HdfChipDriverFactory | //drivers/framework/include/wifi/hdf_wlan_chipdriver_manager.h | Supports multiple WLAN interfaces of a chip.| -| HdfChipDriver | //drivers/framework/include/wifi/wifi_module.h | Manages a specific WLAN interface. Each WLAN interface corresponds to an **HdfChipDriver**.| -| NetDeviceInterFace | //drivers/framework/include/net/net_device.h | Communicates with the protocol stack, such as sending data and setting the status of network interfaces.| +| HdfChipDriverFactory | //drivers/hdf_core/framework/include/wifi/hdf_wlan_chipdriver_manager.h | Supports multiple WLAN interfaces of a chip.| +| HdfChipDriver | //drivers/hdf_core/framework/include/wifi/wifi_module.h | Manages a specific WLAN interface. Each WLAN interface corresponds to an **HdfChipDriver**.| +| NetDeviceInterFace | //drivers/hdf_core/framework/include/net/net_device.h | Communicates with the protocol stack, such as sending data and setting the status of network interfaces.| To port a WLAN driver, perform the following steps: 1. Create an HDF driver. You are advised to place the code file in the **//device/MySoCVendor/peripheral/wifi/chip_name/** directory. The file template is as follows: -``` -static int32_t HdfWlanHisiChipDriverInit(struct HdfDeviceObject *device) { - static struct HdfChipDriverFactory factory = CreateChipDriverFactory(); - struct HdfChipDriverManager *driverMgr = HdfWlanGetChipDriverMgr(); - if (driverMgr->RegChipDriver(&factory) != HDF_SUCCESS) { - HDF_LOGE("%s fail: driverMgr is NULL!", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} + ``` + static int32_t HdfWlanXXXChipDriverInit(struct HdfDeviceObject *device) { + static struct HdfChipDriverFactory factory = CreateChipDriverFactory(); + struct HdfChipDriverManager *driverMgr = HdfWlanGetChipDriverMgr(); + if (driverMgr->RegChipDriver(&factory) != HDF_SUCCESS) { + HDF_LOGE("%s fail: driverMgr is NULL!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } -struct HdfDriverEntry g_hdfXXXChipEntry = { - .moduleVersion = 1, - .Init = HdfWlanXXXChipDriverInit, - .Release = HdfWlanXXXChipRelease, - .moduleName = "HDF_WIFI_CHIP_XXX" -}; + struct HdfDriverEntry g_hdfXXXChipEntry = { + .moduleVersion = 1, + .Init = HdfWlanXXXChipDriverInit, + .Release = HdfWlanXXXChipRelease, + .moduleName = "HDF_WIFI_CHIP_XXX" + }; -HDF_INIT(g_hdfXXXChipEntry); -``` + HDF_INIT(g_hdfXXXChipEntry); + ``` -Create an **HdfChipDriverFactory** in the **CreateChipDriverFactory**. The APIs are as follows: + Create an **HdfChipDriverFactory** in the **CreateChipDriverFactory**. The APIs are as follows: -| API| Description| -| -------- | -------- | -| const char \*driverName | Indicates the driver name.| -| int32_t (\*InitChip)(struct HdfWlanDevice \*device) | Initializes a chip.| -| int32_t (\*DeinitChip)(struct HdfWlanDevice \*device) | Deinitializes a chip.| -| void (*ReleaseFactory)(struct HdfChipDriverFactory *factory) | Releases the **HdfChipDriverFactory** object.| -| struct HdfChipDriver *(_Build)(struct HdfWlanDevice \*device, uint8*t ifIndex) | Creates an **HdfChipDriver**. In the input parameters, **device** indicates the device information, and **ifIndex** indicates the sequence number of this interface in the chip.| -| void (*Release)(struct HdfChipDriver *chipDriver) | Releases the **HdfChipDriver**.| -| uint8_t (\*GetMaxIFCount)(struct HdfChipDriverFactory \*factory) | Obtains the maximum number of APIs supported by the current chip.| -Implement the following APIs in the **HdfChipDriver**. -| API| Description| -| -------- | -------- | -| int32_t (\*init)(struct HdfChipDriver \*chipDriver, NetDevice \*netDev) | Initializes the current network interface. The **NetDeviceInterFace** needs to be provided for the **netDev**.| -| int32_t (\*deinit)(struct HdfChipDriver \*chipDriver, NetDevice \*netDev) | Deinitializes the current network interface.| -| struct HdfMac80211BaseOps \*ops | Provides the WLAN basic capability interface set.| -| struct HdfMac80211STAOps \*staOps | Provides the interface set required for supporting the standalone (STA) mode.| -| struct HdfMac80211APOps \*apOps | Provides the interface set required for supporting the access point (AP) mode.| + | API| Description| + | -------- | -------- | + | const char \*driverName | Indicates the driver name.| + | int32_t (\*InitChip)(struct HdfWlanDevice \*device) | Initializes a chip.| + | int32_t (\*DeinitChip)(struct HdfWlanDevice \*device) | Deinitializes a chip.| + | void (_ReleaseFactory)(struct HdfChipDriverFactory _factory) | Releases the **HdfChipDriverFactory** object.| + | struct HdfChipDriver _(_Build)(struct HdfWlanDevice \*device, uint8_t ifIndex) | Creates an **HdfChipDriver**. In the input parameters, **device** indicates the device information, and **ifIndex** indicates the sequence number of this interface in the chip.| + | void (_Release)(struct HdfChipDriver _chipDriver) | Releases the **HdfChipDriver**.| + | uint8_t (\*GetMaxIFCount)(struct HdfChipDriverFactory \*factory) | Obtains the maximum number of APIs supported by the current chip.| + + Implement the following APIs in the **HdfChipDriver**. + + | API| Description| + | -------- | -------- | + | int32_t (\*init)(struct HdfChipDriver \*chipDriver, NetDevice \*netDev) | Initializes the current network interface. The **NetDeviceInterFace** needs to be provided for the **netDev**.| + | int32_t (\*deinit)(struct HdfChipDriver \*chipDriver, NetDevice \*netDev) | Deinitializes the current network interface.| + | struct HdfMac80211BaseOps \*ops | Provides the WLAN basic capability interface set.| + | struct HdfMac80211STAOps \*staOps | Provides the interface set required for supporting the standalone (STA) mode.| + | struct HdfMac80211APOps \*apOps | Provides the interface set required for supporting the access point (AP) mode.| 2. Compile the configuration file to describe the devices supported by the driver. @@ -353,65 +349,68 @@ Implement the following APIs in the **HdfChipDriver**. The sample code is as follows: - -``` -root { - wlan_config { - chip_name :& chipList { - chip_name :: chipInst { - match_attr = "hdf_wlan_chips_chip_name"; /* Configure the matching attribute, which is used to provide the configuration root of the driver.*/ - driverName = "driverName"; /* The value must be the same as that of driverName in HdfChipDriverFactory.*/ - sdio { - vendorId = 0x0296; - deviceId = [0x5347]; - } - } - } - } -} -``` + ``` + root { + wlan_config { + chip_name :& chipList { + chip_name :: chipInst { + match_attr = "hdf_wlan_chips_chip_name"; /* Configure the matching attribute, which is used to provide the configuration root of the driver.*/ + driverName = "driverName"; /* The value must be the same as that of driverName in HdfChipDriverFactory.*/ + sdio { + vendorId = 0x0296; + deviceId = [0x5347]; + } + } + } + } + } + ``` 3. Edit the configuration file and load the driver. - All device information about the product is defined in the **//vendor/MyProductVendor/MyProduct/config/device_info/device_info.hcs** file. Modify the file by adding configurations for the device named **device_wlan_chips** to the host named **network**. Note: The value of **moduleName** must be the same as that in the touchscreen driver. + All device information about the product is defined in the **//vendor/MyProductVendor/MyProduct/config/device_info/device_info.hcs** file. Modify the file by adding configurations for the device named **device_wlan_chips** to the host named **network**. + Note: The value of **moduleName** must be the same as that in the touchscreen driver. -``` - deviceN :: deviceNode { - policy = 0; - preload = 2; - moduleName = "HDF_WLAN_CHIPS"; - deviceMatchAttr = "hdf_wlan_chips_chip_name"; - serviceName = "driverName"; - } -``` + ``` + deviceN :: deviceNode { + policy = 0; + preload = 2; + moduleName = "HDF_WLAN_CHIPS"; + deviceMatchAttr = "hdf_wlan_chips_chip_name"; + serviceName = "driverName"; + } + ``` 4. Build the driver. -- Create a kernel configuration menu. Create a **Kconfig** file in the **//device/MySoCVendor/peripheral** directory. The file template is as follows: + - Create a kernel configuration menu. Create a **Kconfig** file in the **//device/MySoCVendor/peripheral** directory. The file template is as follows: + + ``` + config DRIVERS_WLAN_XXX + bool "Enable XXX WLAN Host driver" + default n + depends on DRIVERS_HDF_WIFI + help + Answer Y to enable XXX Host driver. Support chip xxx + ``` -``` -config DRIVERS_WLAN_XXX - bool "Enable XXX WLAN Host driver" - default n - depends on DRIVERS_HDF_WIFI - help - Answer Y to enable XXX Host driver. Support chip xxx -``` + Add the following configuration to the end of the **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi/Kconfig** file: -Add the following sample code to the end of the **//drivers/adapter/khdf/linux/model/network/wifi/Kconfig** file to add the configuration menu to the kernel: + ``` + source "../../../../../device/MySoCVendor/peripheral/Kconfig" + ``` -``` -source "../../../../../device/MySoCVendor/peripheral/Kconfig" -``` + - Create a build script. + + Add the following configuration to the end of the **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi/Makefile** file: -- Create a build script. -Add the following configuration to the end of the **//drivers/adapter/khdf/linux/model/network/wifi/Makefile** file: -``` -HDF_DEVICE_ROOT := $(HDF_DIR_PREFIX)/../device -obj-$(CONFIG_DRIVERS_WLAN_XXX) += $(HDF_DEVICE_ROOT)/MySoCVendor/peripheral/build/standard/ -``` + ``` + HDF_DEVICE_ROOT := $(HDF_DIR_PREFIX)/../device + obj-$(CONFIG_DRIVERS_WLAN_XXX) += $(HDF_DEVICE_ROOT)/MySoCVendor/peripheral/build/standard/ + ``` + + When **DRIVERS_WLAN_XXX** is enabled in the kernel, **makefile** in **//device/MySoCVendor/peripheral/build/standard/** is called. For details about the development, see [LED Peripheral Control](../guide/device-wlan-led-control.md). -When **DRIVERS_WLAN_XXX** is enabled in the kernel, **makefile** in **//device/MySoCVendor/peripheral/build/standard/** is called. For details about the development, see [LED Peripheral Control](../guide/device-wlan-led-control.md). 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..07eff504498ee7b37063a8267ed522cf990c9e5a 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 - ``` + + ![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/OpenHarmony_4.0.10.1/changelog-security_access_token.md b/en/release-notes/changelogs/OpenHarmony_4.0.10.1/changelog-security_access_token.md new file mode 100644 index 0000000000000000000000000000000000000000..e10090e9d1814ef8c0b0370146bec92864082dc4 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.10.1/changelog-security_access_token.md @@ -0,0 +1,24 @@ +# Application Access Control Subsystem Changelog + +## cl.sucurity_access_token.1 Changes in the Event Subscription and Cancellation APIs + +**Change Impact** + +The applications developed based on earlier versions are not affected. + +**Key API/Component Changes** + +Involved APIs: +interface/sdk-js/api/@ohos.abilityAccessCtrl.d.ts: + +atManager.on + +atManager.off + +From this version: + +Multiple callbacks can be registered if **tokenIDList** and **permissionList** are the same. + +The same callback cannot be registered if **tokenIDList** or **permissionList** are overlapped. + +If callback is not passed in **atManager.off**, all callbacks under **tokenIDList** and **permissionList** will be unregistered. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelog-security_privacy.md b/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelog-security_privacy.md new file mode 100644 index 0000000000000000000000000000000000000000..e4e10bb205da3d08343f229576a770989bbbdb46 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelog-security_privacy.md @@ -0,0 +1,24 @@ +# Application Access Control Subsystem Changelog + +## cl.sucurity_access_token.1 Changes in the Event Subscription and Cancellation APIs + +**Change Impact** + +The applications developed based on earlier versions are not affected. + +**Key API/Component Changes** + +Involved APIs: +interface/sdk-js/api/@ohos.privacyManager.d.ts: + +privacyManager.on + +privacyManager.off + +From this version: + +Multiple callbacks can be registered if **permissionList** is the same. + +The same callback cannot be registered if **tokenIDList** is overlapped. + +If callback is not passed in **privacyManager.off**, all callbacks under **permissionList** will be unregistered. 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/arkts-ui-widget-configuration.md b/zh-cn/application-dev/application-models/arkts-ui-widget-configuration.md index 183ac67bf051d5902269f08344160fffcd81f347..cc7be07c9b9ad495d56e4bf517fec683ae0ce7cd 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-configuration.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-configuration.md @@ -54,7 +54,7 @@ | formVisibleNotify | 标识是否允许卡片使用卡片可见性通知。 | 字符串 | 可缺省,缺省值为空。 | | metadata | 表示卡片的自定义信息,包含customizeData数组标签。 | 对象 | 可缺省,缺省值为空。 | | dataProxyEnabled | 表示卡片是否支持[卡片代理刷新](./arkts-ui-widget-update-by-proxy.md),取值范围:
- true:表示支持代理刷新。
- false:表示不支持代理刷新。
设置为true时,[定时刷新和下次刷新不生效,但不影响定点刷新](./arkts-ui-widget-update-by-time.md) | 布尔类型 | 可缺省,缺省值为false。 | - | isDynamic | 表示此卡片是否为动态卡片(仅针对ArkTS卡片生效)。
- true:为动态卡片。
- false:为静态卡片,当卡片添加成功后,将以静态图显示。 | 布尔类型 | 可缺省,缺省值为true。 | + | isDynamic | 表示此卡片是否为动态卡片(仅针对ArkTS卡片生效)。
- true:为动态卡片 。
- false:为静态卡片。
> **说明:**
 为了降低卡片不必要的内存资源开销,将卡片分为动态卡片和静态卡片。
-  动态卡片:支持onClick等事件机制,卡片内容可以根据用户的点击、滑动等动作有不同的反应和感知。
-  静态卡片:不支持onClick等事件机制,卡片内容以静态图显示,仅可以通过[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md)组件跳转到指定UIAbility。| 布尔类型 | 可缺省,缺省值为true。 | **表2** window对象的内部结构说明 diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.md index 0cb866cfd4b67db3e3091ad43355aca9484154c4..8a674be2aafc5ed44c8ac330b3cc366f7c470fa2 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-call.md @@ -4,6 +4,7 @@ 许多应用希望借助卡片的能力,实现和应用在前台时相同的功能。例如音乐卡片,卡片上提供播放、暂停等按钮,点击不同按钮将触发音乐应用的不同功能,进而提高用户的体验。在卡片中使用**postCardAction**接口的call能力,能够将卡片提供方应用的指定的UIAbility拉到后台。同时,call能力提供了调用应用指定方法、传递数据的功能,使应用在后台运行时可以通过卡片上的按钮执行不同的功能。 +说明:
本文主要介绍动态卡片的事件开发。对于静态卡片,请参见[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md)。
通常使用按钮控件来触发call事件,示例代码如下: diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md index 776b129a1fabf15885e43d19f5949878acf9be02..bea7df3809ced93e4da2ee081a92bd2e4f9ced8a 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-formextensionability.md @@ -1,6 +1,7 @@ # 通过message事件刷新卡片内容 +说明:
本文主要介绍动态卡片的事件开发。对于静态卡片,请参见[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md)。
在卡片页面中可以通过**postCardAction**接口触发message事件拉起FormExtensionAbility,然后由FormExtensionAbility刷新卡片内容,下面是这种刷新方式的简单示例。 diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-overview.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-overview.md index 5ee24405260ed7ace73a2d17b51fe22b0ced315f..70dd70c457d711e31988d8b3c9b4db8570ac2adc 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-overview.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-overview.md @@ -1,10 +1,11 @@ # 卡片事件能力说明 -ArkTS卡片中提供了postCardAction()接口用于卡片内部和提供方应用间的交互,当前支持router、message和call三种类型的事件,仅在卡片中可以调用。 -![WidgetPostCardAction](figures/WidgetPostCardAction.png) - +针对动态卡片,ArkTS卡片中提供了postCardAction()接口用于卡片内部和提供方应用间的交互,当前支持router、message和call三种类型的事件,仅在卡片中可以调用。 +
针对静态卡片,ArkTS卡片提供了[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md)用于卡片内部和提供方应用间的交互。 -接口定义:postCardAction(component: Object, action: Object): void +## 动态卡片事件能力说明 +![WidgetPostCardAction](figures/WidgetPostCardAction.png) +
接口定义:postCardAction(component: Object, action: Object): void 接口参数说明: @@ -63,5 +64,5 @@ Button('拉至后台') }) ``` - -以下介绍通过卡片事件实现的典型开发场景。 +## 静态卡片事件能力说明 +请参见[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md) diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md index e54036d3971d65b2a12cf45baec3640f079e6337..eaaf5cbb7b431a3b3dee53bc4a9696661dfa07c7 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-router.md @@ -5,7 +5,8 @@ ![WidgerCameraCard](figures/WidgerCameraCard.png) -通常使用按钮控件来实现页面拉起,示例代码如下: +说明:
本文主要介绍动态卡片的事件开发。对于静态卡片,请参见[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md)。
+通常使用按钮控件来实现页面拉起,示例代码如下: - 在卡片页面中布局两个按钮,点击其中一个按钮时调用postCardAction向指定UIAbility发送router事件,并在事件内定义需要传递的内容。 diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md b/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md index 73c9cc299d5c43b37a170c656c0df41d912a8168..d5e225db93f33277251bbb0e12ad94ccda219c80 100644 --- a/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md +++ b/zh-cn/application-dev/application-models/arkts-ui-widget-event-uiability.md @@ -5,6 +5,7 @@ ## 通过router事件刷新卡片内容 +说明:
本文主要介绍动态卡片的事件开发。对于静态卡片,请参见[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md)。
- 在卡片页面通过注册Button的onClick点击事件回调,并在回调中调用**postCardAction**接口触发router事件拉起UIAbility。 ```ts 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/arkts-utils/async-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md index b78e713853917e1ac23d11ebdde6d192cd6f2c4b..c0d45f2b7fbf7c189b138bbb39f4d7a6dc90ed11 100644 --- a/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/async-concurrency-overview.md @@ -17,16 +17,16 @@ Promise有三种状态:pending(进行中)、fulfilled(已完成)和rej ```js -const promise = new Promise((resolve, reject) => { - setTimeout(() => { - const randomNumber = Math.random(); - if (randomNumber > 0.5) { - resolve(randomNumber); - } else { - reject(new Error('Random number is too small')); - } - }, 1000); -}); +const promise: Promise = new Promise((resolve: Function, reject: Function) => { +setTimeout(() => { + const randomNumber: number = Math.random(); + if (randomNumber > 0.5) { + resolve(randomNumber); + } else { + reject(new Error('Random number is too small')); + } +}, 1000); +} ``` 上述代码中,setTimeout函数模拟了一个异步操作,并在1秒钟后随机生成一个数字。如果随机数大于0.5,则执行resolve回调函数并将随机数作为参数传递;否则执行reject回调函数并传递一个错误对象作为参数。 @@ -55,13 +55,13 @@ async函数是一个返回Promise对象的函数,用于表示一个异步操 ```js -async function myAsyncFunction() { - const result = await new Promise((resolve) => { +async function myAsyncFunction(): Promise { + const result: string = await new Promise((resolve: Function) => { setTimeout(() => { resolve('Hello, world!'); }, 3000); }); - console.info(String(result)); // 输出: Hello, world! + console.info(result); // 输出: Hello, world! } myAsyncFunction(); @@ -73,9 +73,9 @@ myAsyncFunction(); ```js -async function myAsyncFunction() { +async function myAsyncFunction(): Promise { try { - const result = await new Promise((resolve) => { + const result: string = await new Promise((resolve: Function) => { resolve('Hello, world!'); }); } catch (e) { diff --git a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md index 19b25b18b716cd8dca1eae4f71c9c3c2ad4c26c0..f2f4b93b648745f755689490510e5cca65620f54 100644 --- a/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/cpu-intensive-task-development.md @@ -24,19 +24,19 @@ CPU密集型任务是指需要占用系统资源处理大量计算能力的任 import taskpool from '@ohos.taskpool'; @Concurrent -function imageProcessing(dataSlice: ArrayBuffer) { +function imageProcessing(dataSlice: ArrayBuffer): ArrayBuffer { // 步骤1: 具体的图像处理操作及其他耗时操作 return dataSlice; } -function histogramStatistic(pixelBuffer: ArrayBuffer) { +function histogramStatistic(pixelBuffer: ArrayBuffer): void { // 步骤2: 分成三段并发调度 - let number = pixelBuffer.byteLength / 3; - let buffer1 = pixelBuffer.slice(0, number); - let buffer2 = pixelBuffer.slice(number, number * 2); - let buffer3 = pixelBuffer.slice(number * 2); + let number: number = pixelBuffer.byteLength / 3; + let buffer1: ArrayBuffer = pixelBuffer.slice(0, number); + let buffer2: ArrayBuffer = pixelBuffer.slice(number, number * 2); + let buffer3: ArrayBuffer = pixelBuffer.slice(number * 2); - let group = new taskpool.TaskGroup(); + let group: taskpool.TaskGroup = new taskpool.TaskGroup(); group.addTask(imageProcessing, buffer1); group.addTask(imageProcessing, buffer2); group.addTask(imageProcessing, buffer3); @@ -79,30 +79,28 @@ struct Index { ![newWorker](figures/newWorker.png) 2. 在主线程中通过调用ThreadWorker的[constructor()](../reference/apis/js-apis-worker.md#constructor9)方法创建Worker对象,当前线程为宿主线程。 - + ```js import worker from '@ohos.worker'; - - const workerInstance = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + + const workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); ``` 3. 在宿主线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9)方法接收Worker线程发送过来的消息,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9)方法向Worker线程发送消息。 例如向Worker线程发送训练和预测的消息,同时接收Worker线程发送回来的消息。 - + ```js // 接收Worker子线程的结果 workerInstance.onmessage = function(e) { - // data:主线程发送的信息 - let data = e.data; console.info('MyWorker.ts onmessage'); // 在Worker线程中进行耗时操作 } - + workerInstance.onerror = function (d) { // 接收Worker子线程的错误信息 } - + // 向Worker子线程发送训练消息 workerInstance.postMessage({ 'type': 0 }); // 向Worker子线程发送预测消息 @@ -110,40 +108,39 @@ struct Index { ``` 4. 在MyWorker.ts文件中绑定Worker对象,当前线程为Worker线程。 - + ```js import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; - + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; ``` 5. 在Worker线程中通过调用[onmessage()](../reference/apis/js-apis-worker.md#onmessage9-1)方法接收宿主线程发送的消息内容,并通过调用[postMessage()](../reference/apis/js-apis-worker.md#postmessage9-2)方法向宿主线程发送消息。 例如在Worker线程中定义预测模型及其训练过程,同时与主线程进行信息交互。 - + ```js import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; - + let workerPort: ThreadWorkerGlobalScope = worker.workerPort; - - // 定义训练模型及结果 + + // 定义训练模型及结果 let result; - + // 定义预测函数 function predict(x) { return result[x]; } - + // 定义优化器训练过程 function optimize() { result = {}; } - + // Worker线程的onmessage逻辑 - workerPort.onmessage = function (e: MessageEvents) { - let data = e.data + workerPort.onmessage = (e: MessageEvents): void => { // 根据传输的数据的type选择进行操作 - switch (data.type) { + switch (e.data.type) { case 0: // 进行训练 optimize(); @@ -152,7 +149,7 @@ struct Index { break; case 1: // 执行预测 - const output = predict(data.value); + const output = predict(e.data.value); // 发送主线程预测的结果 workerPort.postMessage({ type: 'predict', value: output }); break; @@ -166,7 +163,7 @@ struct Index { 6. 在Worker线程中完成任务之后,执行Worker线程销毁操作。销毁线程的方式主要有两种:根据需要可以在宿主线程中对Worker线程进行销毁;也可以在Worker线程中主动销毁Worker线程。 在宿主线程中通过调用[onexit()](../reference/apis/js-apis-worker.md#onexit9)方法定义Worker线程销毁后的处理逻辑。 - + ```js // Worker线程销毁后,执行onexit回调方法 workerInstance.onexit = function() { @@ -182,7 +179,7 @@ struct Index { ``` 方式二:在Worker线程中通过调用[close()](../reference/apis/js-apis-worker.md#close9)方法主动销毁Worker线程,并终止Worker接收消息。 - + ```js // 销毁线程 workerPort.close(); diff --git a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md index 6c4410e88b55a5148219b85521e4ffc1b61df4b7..1a29cc3e008f82e62df89809d981980a5d8c426f 100644 --- a/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md +++ b/zh-cn/application-dev/arkts-utils/io-intensive-task-development.md @@ -8,43 +8,45 @@ I/O密集型任务的性能重点通常不在于CPU的处理能力,而在于I/ 1. 定义并发函数,内部密集调用I/O能力。 - + ```ts - import fs from '@ohos.file.fs'; - - // 定义并发函数,内部密集调用I/O能力 - @Concurrent - async function concurrentTest(fileList: string[]) { - // 写入文件的实现 - async function write(data, filePath) { - let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); - await fs.write(file.fd, data); - fs.close(file); - } - // 循环写文件操作 - for (let i = 0; i < fileList.length; i++) { - write('Hello World!', fileList[i]).then(() => { - console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); - }).catch((err) => { - console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) - return false; - }) - } - return true; - } + import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; + + // 定义并发函数,内部密集调用I/O能力 + // 写入文件的实现 + async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + await fs.write(file.fd, data); + fs.close(file); + } + + @Concurrent + async function concurrentTest(fileList: string[]): Promise { + // 循环写文件操作 + for (let i: number = 0; i < fileList.length; i++) { + write('Hello World!', fileList[i]).then(() => { + console.info(`Succeeded in writing the file. FileList: ${fileList[i]}`); + }).catch((err: BusinessError) => { + console.error(`Failed to write the file. Code is ${err.code}, message is ${err.message}`) + return false; + }) + } + return true; + } ``` 2. 使用TaskPool执行包含密集I/O的并发函数:通过调用[execute()](../reference/apis/js-apis-taskpool.md#taskpoolexecute)方法执行任务,并在回调中进行调度结果处理。示例中的filePath1和filePath2的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - + ```ts import taskpool from '@ohos.taskpool'; - - let filePath1 = ...; // 应用文件路径 - let filePath2 = ...; - + + let filePath1: string = ...; // 应用文件路径 + let filePath2: string = ...; + // 使用TaskPool执行包含密集I/O的并发函数 // 数组较大时,I/O密集型任务任务分发也会抢占主线程,需要使用多线程能力 - taskpool.execute(concurrentTest, [filePath1, filePath2]).then((ret) => { + taskpool.execute(concurrentTest, [filePath1, filePath2]).then(() => { // 调度结果处理 console.info(`The result: ${ret}`); }) diff --git a/zh-cn/application-dev/arkts-utils/linear-container.md b/zh-cn/application-dev/arkts-utils/linear-container.md index 650feae053477ebbf8f643684c0f129ff2cabb15..088b6c7272ff42d1e2a5c345a1e6edb8d4f223a4 100644 --- a/zh-cn/application-dev/arkts-utils/linear-container.md +++ b/zh-cn/application-dev/arkts-utils/linear-container.md @@ -202,52 +202,59 @@ Stack进行增、删、改、查操作的常用API如下: // ArrayList import ArrayList from '@ohos.util.ArrayList'; // 导入ArrayList模块 -let arrayList = new ArrayList(); -arrayList.add('a'); -arrayList.add(1); // 增加元素 -console.info(`result: ${arrayList[0]}`); // 访问元素 -arrayList[0] = 'one'; // 修改元素 -console.info(`result: ${arrayList[0]}`); +let arrayList1: ArrayList = new ArrayList(); +arrayList1.add('a'); +let arrayList2: ArrayList = new ArrayList(); +arrayList2.add(1); // 增加元素 +console.info(`result: ${arrayList2[0]}`); // 访问元素 +arrayList1[0] = 'one'; // 修改元素 +console.info(`result: ${arrayList1[0]}`); // Vector import Vector from '@ohos.util.Vector'; // 导入Vector模块 -let vector = new Vector(); -vector.add('a'); +let vector1: Vector = new Vector(); +vector1.add('a'); +let vector2: Vector> = new Vector(); let b1 = [1, 2, 3]; -vector.add(b1); -vector.add(false); // 增加元素 -console.info(`result: ${vector[0]}`); // 访问元素 -console.info(`result: ${vector.getFirstElement()}`); // 访问元素 +vector2.add(b1); +let vector3: Vector = new Vector(); +vector3.add(false); // 增加元素 +console.info(`result: ${vector1[0]}`); // 访问元素 +console.info(`result: ${vector2.getFirstElement()}`); // 访问元素 // Deque import Deque from '@ohos.util.Deque'; // 导入Deque模块 -let deque = new Deque; -deque.insertFront('a'); -deque.insertFront(1); // 增加元素 -console.info(`result: ${deque[0]}`); // 访问元素 -deque[0] = 'one'; // 修改元素 -console.info(`result: ${deque[0]}`); +let deque1: Deque = new Deque; +deque1.insertFront('a'); +let deque2: Deque = new Deque; +deque2.insertFront(1); // 增加元素 +console.info(`result: ${deque1[0]}`); // 访问元素 +deque1[0] = 'one'; // 修改元素 +console.info(`result: ${deque2[0]}`); // Stack -import Stack from '@ohos.util.Stack'; // 导入Stack模块 +import Stack from '@ohos.util.Stack'; // 导入Stack模块 -let stack = new Stack(); -stack.push('a'); -stack.push(1); // 增加元素 -console.info(`result: ${stack[0]}`); // 访问元素 -stack.pop(); // 弹出元素 -console.info(`result: ${stack.length}`); +let stack1: Stack = new Stack(); +stack1.push('a'); +let stack2: Stack = new Stack(); +stack2.push(1); // 增加元素 +console.info(`result: ${stack1[0]}`); // 访问元素 +stack2.pop(); // 弹出元素 +console.info(`result: ${stack2.length}`); // List import List from '@ohos.util.List'; // 导入List模块 -let list = new List; -list.add('a'); -list.add(1); +let list1: List = new List; +list1.add('a'); +let list2: List = new List; +list2.add(1); +let list3: List> = new List; let b2 = [1, 2, 3]; -list.add(b2); // 增加元素 -console.info(`result: ${list[0]}`); // 访问元素 -console.info(`result: ${list.get(0)}`); // 访问元素 +list3.add(b2); // 增加元素 +console.info(`result: ${list1[0]}`); // 访问元素 +console.info(`result: ${list3.get(0)}`); // 访问元素 ``` diff --git a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md index cc0cee7c6f33d320895480f01505ad816226fad4..31271ee693b9b8314bb15612c09953dfb14a6123 100644 --- a/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md +++ b/zh-cn/application-dev/arkts-utils/multi-thread-concurrency-overview.md @@ -29,7 +29,7 @@ Actor并发模型作为基于消息通信并发模型的典型代表,不需要 ```js // 定义可转移对象 -let buffer = new ArrayBuffer(100); +let buffer: ArrayBuffer = new ArrayBuffer(100); ``` @@ -44,7 +44,7 @@ SharedArrayBuffer对象存储的数据在同时被修改时,需要通过原子 ```js // 定义可共享对象,可以使用Atomics进行操作 -let sharedBuffer = new SharedArrayBuffer(1024); +let sharedBuffer: SharedArrayBuffer = new SharedArrayBuffer(1024); ``` ### Native绑定对象 diff --git a/zh-cn/application-dev/arkts-utils/nonlinear-container.md b/zh-cn/application-dev/arkts-utils/nonlinear-container.md index 39cd522af930c12ef36db9ab673e18c912fa52aa..0b35b767bfc04b89746bfb32bb1057f4b93844d3 100644 --- a/zh-cn/application-dev/arkts-utils/nonlinear-container.md +++ b/zh-cn/application-dev/arkts-utils/nonlinear-container.md @@ -216,16 +216,17 @@ PlainArray进行增、删、改、查操作的常用API如下: // HashMap import HashMap from '@ohos.util.HashMap'; // 导入HashMap模块 -let hashMap = new HashMap(); -hashMap.set('a', 123); -hashMap.set(4, 123); // 增加元素 -console.info(`result: ${hashMap.hasKey(4)}`); // 判断是否含有某元素 -console.info(`result: ${hashMap.get('a')}`); // 访问元素 +let hashMap1: HashMap = new HashMap(); +hashMap1.set('a', 123); +let hashMap2: HashMap = new HashMap(); +hashMap2.set(4, 123); // 增加元素 +console.info(`result: ${hashMap2.hasKey(4)}`); // 判断是否含有某元素 +console.info(`result: ${hashMap1.get('a')}`); // 访问元素 // TreeMap import TreeMap from '@ohos.util.TreeMap'; // 导入TreeMap模块 -let treeMap = new TreeMap(); +let treeMap: TreeMap = new TreeMap(); treeMap.set('a', 123); treeMap.set('6', 356); // 增加元素 console.info(`result: ${treeMap.get('a')}`); // 访问元素 @@ -235,7 +236,7 @@ console.info(`result: ${treeMap.getLastKey()}`); // 访问尾元素 // LightWeightMap import LightWeightMap from '@ohos.util.LightWeightMap'; // 导入LightWeightMap模块 -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set('x', 123); lightWeightMap.set('8', 356); // 增加元素 console.info(`result: ${lightWeightMap.get('a')}`); // 访问元素 @@ -245,7 +246,7 @@ console.info(`result: ${lightWeightMap.getIndexOfKey('8')}`); // 访问元素 // PlainArray import PlainArray from '@ohos.util.PlainArray' // 导入PlainArray模块 -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, 'sdd'); plainArray.add(2, 'sff'); // 增加元素 console.info(`result: ${plainArray.get(1)}`); // 访问元素 diff --git a/zh-cn/application-dev/arkts-utils/single-io-development.md b/zh-cn/application-dev/arkts-utils/single-io-development.md index 432f674d04adac17663158f0add18dd549d887a5..6b551373ead8957fd162150b6e28be6a185feee7 100644 --- a/zh-cn/application-dev/arkts-utils/single-io-development.md +++ b/zh-cn/application-dev/arkts-utils/single-io-development.md @@ -5,24 +5,25 @@ Promise和async/await提供异步并发能力,适用于单次I/O任务的场 1. 实现单次I/O任务逻辑。 - + ```js import fs from '@ohos.file.fs'; - - async function write(data: string, filePath: string) { - let file = await fs.open(filePath, fs.OpenMode.READ_WRITE); - fs.write(file.fd, data).then((writeLen) => { + import { BusinessError } from '@ohos.base'; + + async function write(data: string, filePath: string): Promise { + let file: fs.File = await fs.open(filePath, fs.OpenMode.READ_WRITE); + fs.write(file.fd, data).then((writeLen: number) => { fs.close(file); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Failed to write data. Code is ${err.code}, message is ${err.message}`); }) } ``` 2. 采用异步能力调用单次I/O任务。示例中的filePath的获取方式请参见[获取应用文件路径](../application-models/application-context-stage.md#获取应用文件路径)。 - + ```js - let filePath = ...; // 应用文件路径 + let filePath: string = ...; // 应用文件路径 write('Hello World!', filePath).then(() => { console.info('Succeeded in writing data.'); }) diff --git a/zh-cn/application-dev/arkts-utils/sync-task-development.md b/zh-cn/application-dev/arkts-utils/sync-task-development.md index 8fb185d44af9042f80053dc6e06b6ede61ce64ce..6fbb549708694a312d6b349c80051a8dfc9a04f6 100644 --- a/zh-cn/application-dev/arkts-utils/sync-task-development.md +++ b/zh-cn/application-dev/arkts-utils/sync-task-development.md @@ -25,18 +25,16 @@ ```ts // Handle.ts 代码 export default class Handle { - static getInstance() { + static getInstance(): void { // 返回单例对象 } - static syncGet() { + static syncGet(): void { // 同步Get方法 - return; } - static syncSet(num: number) { + static syncSet(num: number): void { // 同步Set方法 - return; } } ``` @@ -51,7 +49,7 @@ import Handle from './Handle'; // 返回静态句柄 // 步骤1: 定义并发函数,内部调用同步方法 @Concurrent -function func(num: number) { +function func(num: number): boolean { // 调用静态类对象中实现的同步等待调用 Handle.syncSet(num); // 或者调用单例对象中实现的同步等待调用 @@ -60,13 +58,11 @@ function func(num: number) { } // 步骤2: 创建任务并执行 -async function asyncGet() { +async function asyncGet(): Promise { // 创建task并传入函数func - let task = new taskpool.Task(func, 1); - // 执行task任务,获取结果res - let res = await taskpool.execute(task); - // 对同步逻辑后的结果进行操作 - console.info(String(res)); + let task: taskpool.Task = new taskpool.Task(func, 1); + // 执行task任务并对同步逻辑后的结果进行操作 + console.info(String(await taskpool.execute(task))); } @Entry @@ -98,15 +94,15 @@ struct Index { 当一系列同步任务需要使用同一个句柄调度,或者需要依赖某个类对象调度,无法在不同任务池之间共享时,需要使用Worker。 1. 在主线程中创建Worker对象,同时接收Worker线程发送回来的消息。 - + ```js import worker from '@ohos.worker'; - + @Entry @Component struct Index { @State message: string = 'Hello World'; - + build() { Row() { Column() { @@ -114,7 +110,7 @@ struct Index { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - let w = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); + let w: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts'); w.onmessage = function (d) { // 接收Worker子线程的结果 } @@ -137,28 +133,28 @@ struct Index { ``` 2. 在Worker线程中绑定Worker对象,同时处理同步任务逻辑。 - + ```js // handle.ts代码 export default class Handle { syncGet() { return; } - + syncSet(num: number) { return; } } - + // Worker.ts代码 import worker, { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; import Handle from './handle.ts' // 返回句柄 - + var workerPort : ThreadWorkerGlobalScope = worker.workerPort; - + // 无法传输的句柄,所有操作依赖此句柄 var handler = new Handle() - + // Worker线程的onmessage逻辑 workerPort.onmessage = function(e : MessageEvents) { switch (e.data.type) { diff --git a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md index 35f70d0f4ec6f937de4c79fb88d17d856c84dfe2..a4f0cd4d8dcdfb711dfda59dcdd9a814a4ef5abd 100644 --- a/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md +++ b/zh-cn/application-dev/arkts-utils/taskpool-vs-worker.md @@ -102,9 +102,9 @@ TaskPool支持开发者在主线程封装任务抛给任务队列,系统选择 ```js // API 9及之后版本使用: -const worker1 = new worker.ThreadWorker(scriptURL); +const worker1: worker.ThreadWorker = new worker.ThreadWorker(scriptURL); // API 8及之前版本使用: -const worker1 = new worker.Worker(scriptURL); +const worker1: worker.ThreadWorker = new worker.Worker(scriptURL); ``` 构造函数需要传入Worker的路径(scriptURL),Worker文件存放位置默认路径为Worker文件所在目录与pages目录属于同级。 @@ -119,15 +119,15 @@ const worker1 = new worker.Worker(scriptURL); ```js // 写法一 // Stage模型-目录同级(entry模块下,workers目录与pages目录同级) -const worker1 = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); +const worker1: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/MyWorker.ts', {name:"first worker in Stage model"}); // Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录) -const worker2 = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts'); +const worker2: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/pages/workers/MyWorker.ts'); // 写法二 // Stage模型-目录同级(entry模块下,workers目录与pages目录同级),假设bundlename是com.example.workerdemo -const worker3 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); +const worker3: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/workers/worker'); // Stage模型-目录不同级(entry模块下,workers目录是pages目录的子目录),假设bundlename是com.example.workerdemo -const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); +const worker4: worker.ThreadWorker = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/ets/pages/workers/worker'); ``` @@ -151,9 +151,9 @@ const worker4 = new worker.ThreadWorker('@bundle:com.example.workerdemo/entry/et ```js // FA模型-目录同级(entry模块下,workers目录与pages目录同级) -const worker1 = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); +const worker1: worker.ThreadWorker = new worker.ThreadWorker('workers/worker.js', {name:'first worker in FA model'}); // FA模型-目录不同级(entry模块下,workers目录与pages目录的父目录同级) -const worker2 = new worker.ThreadWorker('../workers/worker.js'); +const worker2: worker.ThreadWorker = new worker.ThreadWorker('../workers/worker.js'); ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-conversion.md b/zh-cn/application-dev/arkts-utils/xml-conversion.md index a47c733357337a7d2d52714df8d8c2bf160fa186..100d5112be1a49659fd1a0ca85633922100637f7 100644 --- a/zh-cn/application-dev/arkts-utils/xml-conversion.md +++ b/zh-cn/application-dev/arkts-utils/xml-conversion.md @@ -17,22 +17,22 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 此处以XML转为JavaScript对象后获取其标签值为例,说明转换效果。 1. 引入模块。 - + ```js import convertxml from '@ohos.convertxml'; ``` 2. 输入待转换的XML,设置转换选项。 - + ```js - let xml = - '' + - '' + - ' Happy' + - ' Work' + - ' Play' + - ''; - let options = { + let xml: string = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + let options: convertxml.ConvertOptions = { // trim: false 转换后是否删除文本前后的空格,否 // declarationKey: "_declaration" 转换后文件声明使用_declaration来标识 // instructionKey: "_instruction" 转换后指令使用_instruction标识 @@ -51,7 +51,7 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 attributesKey: "_attributes", textKey: "_text", cdataKey: "_cdata", - docTypeKey: "_doctype", + doctypeKey: "_doctype", commentKey: "_comment", parentKey: "_parent", typeKey: "_type", @@ -61,24 +61,17 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 ``` 3. 调用转换函数,打印结果。 - + ```js - let conv = new convertxml.ConvertXML(); - let result = conv.convertToJSObject(xml, options); - let strRes = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出 + let conv: convertxml.ConvertXML = new convertxml.ConvertXML(); + let result: object = conv.convertToJSObject(xml, options); + let strRes: string = JSON.stringify(result); // 将js对象转换为json字符串,用于显式输出 console.info(strRes); - // 也可以直接处理转换后的JS对象,获取标签值 - let title = result['_elements'][0]['_elements'][0]['_elements'][0]['_text']; // 解析标签对应的值 - let todo = result['_elements'][0]['_elements'][1]['_elements'][0]['_text']; // 解析<todo>标签对应的值 - let todo2 = result['_elements'][0]['_elements'][2]['_elements'][0]['_text']; // 解析<todo>标签对应的值 - console.info(title); // Happy - console.info(todo); // Work - console.info(todo2); // Play ``` 输出结果如下所示: - + ```js strRes: {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note", @@ -86,7 +79,4 @@ XML解析及转换需要确保传入的XML数据符合标准格式。 "_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo", "_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo", "_elements":[{"_type":"text","_text":"Play"}]}]}]} - title:Happy - todo:Work - todo2:Play ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-generation.md b/zh-cn/application-dev/arkts-utils/xml-generation.md index 2e3013f0fc517dc61bedd9f05db164387ad4bd03..60edf5c6d3681f09547c7676bb526349c13b1488 100644 --- a/zh-cn/application-dev/arkts-utils/xml-generation.md +++ b/zh-cn/application-dev/arkts-utils/xml-generation.md @@ -23,27 +23,27 @@ XML模块提供XmlSerializer类来生成XML文件,输入为固定长度的Arra XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md)的详细描述,按需求调用对应函数可以生成一份完整的XML文件。 1. 引入模块。 - + ```js - import xml from '@ohos.xml'; + import xml from '@ohos.xml'; import util from '@ohos.util'; ``` 2. 创建缓冲区,构造XmlSerializer对象(可以基于Arraybuffer构造XmlSerializer对象, 也可以基于DataView构造XmlSerializer对象)。 - + ```js // 1.基于Arraybuffer构造XmlSerializer对象 - let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 - let thatSer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象 - + let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 + let thatSer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // 基于Arraybuffer构造XmlSerializer对象 + // 2.基于DataView构造XmlSerializer对象 - let arrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 - let dataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象 - let thatSer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象 + let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // 创建一个2048字节的缓冲区 + let dataView: DataView = new DataView(arrayBuffer); // 使用DataView对象操作ArrayBuffer对象 + let thatSer: xml.XmlSerializer = new xml.XmlSerializer(dataView); // 基于DataView构造XmlSerializer对象 ``` 3. 调用XML元素生成函数。 - + ```js thatSer.setDeclaration(); // 写入xml的声明 thatSer.startElement('bookstore'); // 写入元素开始标记 @@ -64,17 +64,17 @@ XML模块的API接口可以参考[@ohos.xml](../reference/apis/js-apis-xml.md) ``` 4. 使用Uint8Array操作Arraybuffer,调用TextDecoder对Uint8Array解码后输出。 - + ```js - let view = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据 - let textDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类 - let res = textDecoder.decodeWithStream(view); // 对view解码 + let view: Uint8Array = new Uint8Array(arrayBuffer); // 使用Uint8Array读取arrayBuffer的数据 + let textDecoder: util.TextDecoder = util.TextDecoder.create(); // 调用util模块的TextDecoder类 + let res: string = textDecoder.decodeWithStream(view); // 对view解码 console.info(res); ``` 输出结果如下: - + ```js <?xml version=\"1.0\" encoding=\"utf-8\"?><bookstore>\r\n <book category=\"COOKING\">\r\n <title lang=\"en\">Everyday\r\n Giada\r\n 2005\r\n \r\n ``` diff --git a/zh-cn/application-dev/arkts-utils/xml-parsing.md b/zh-cn/application-dev/arkts-utils/xml-parsing.md index e53a2d830d742d1c3cb287bbad29582071ce114c..5df577246c928a0896f3062d961c46330e3d7945 100644 --- a/zh-cn/application-dev/arkts-utils/xml-parsing.md +++ b/zh-cn/application-dev/arkts-utils/xml-parsing.md @@ -28,7 +28,7 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ## 解析XML标签和标签值 1. 引入模块。 - + ```js import xml from '@ohos.xml'; import util from '@ohos.util'; // 需要使用util模块函数对文件编码 @@ -37,29 +37,29 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A 2. 对XML文件编码后调用XmlPullParser。 可以基于ArrayBuffer构造XmlPullParser对象, 也可以基于DataView构造XmlPullParser对象。 - + ```js - let strXml = - '' + - '' + - 'Play' + - 'Work' + - ''; - let textEncoder = new util.TextEncoder(); - let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - // 1.基于ArrayBuffer构造XmlPullParser对象 - let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); - - // 2.基于DataView构造XmlPullParser对象 - let dataView = new DataView(arrBuffer.buffer); - let that = new xml.XmlPullParser(dataView, 'UTF-8'); + let strXml: string = + '' + + '' + + 'Play' + + 'Work' + + ''; + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + // 1.基于ArrayBuffer构造XmlPullParser对象 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + + // 2.基于DataView构造XmlPullParser对象 + let dataView: DataView = new DataView(arrBuffer.buffer); + let that: xml.XmlPullParser = new xml.XmlPullParser(dataView, 'UTF-8'); ``` 3. 自定义回调函数,本例直接打印出标签及标签值。 - + ```js - let str = ''; - function func(name, value){ + let str: string = ''; + function func(name: string, value: string): boolean { str = name + value; console.info(str); return true; //true:继续解析 false:停止解析 @@ -67,15 +67,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ``` 4. 设置解析选项,调用parse函数。 - + ```js - let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func}; that.parse(options); ``` 输出结果如下所示: - + ```js note title @@ -91,48 +91,48 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ## 解析XML属性和属性值 1. 引入模块。 - + ```js import xml from '@ohos.xml'; import util from '@ohos.util'; // 需要使用util模块函数对文件编码 ``` 2. 对XML文件编码后调用XmlPullParser。 - + ```js - let strXml = + let strXml: string = '' + '' + ' Play' + ' Happy' + ' Work' + ''; - let textEncoder = new util.TextEncoder(); - let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); ``` 3. 自定义回调函数,本例直接打印出属性及属性值。 - + ```js - let str = ''; - function func(name, value){ + let str: string = ''; + function func(name: string, value: string): boolean { str += name + ' ' + value + ' '; return true; // true:继续解析 false:停止解析 } ``` 4. 设置解析选项,调用parse函数。 - + ```js - let options = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, attributeValueCallbackFunction:func}; that.parse(options); console.info(str); // 一次打印出所有的属性及其值 ``` 输出结果如下所示: - + ```js importance high logged true // note节点的属性及属性值 ``` @@ -141,30 +141,30 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ## 解析XML事件类型和元素深度 1. 引入模块。 - + ```js import xml from '@ohos.xml'; import util from '@ohos.util'; // 需要使用util模块函数对文件编码 ``` 2. 对XML文件编码后调用XmlPullParser。 - + ```js - let strXml = + let strXml: string = '' + '' + 'Play' + ''; - let textEncoder = new util.TextEncoder(); - let arrBuffer = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 - let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); + let textEncoder: util.TextEncoder = new util.TextEncoder(); + let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); // 对数据编码,防止包含中文字符乱码 + let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); ``` 3. 自定义回调函数,本例直接打印元素事件类型及元素深度。 - + ```js - let str = ''; - function func(name, value){ + let str: string = ''; + function func(name: string, value: xml.ParseInfo): boolean { str = name + ' ' + value.getDepth(); // getDepth 获取元素的当前深度 console.info(str) return true; //true:继续解析 false:停止解析 @@ -172,15 +172,15 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A ``` 4. 设置解析选项,调用parse函数。 - + ```js - let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; + let options: xml.ParseOptions = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func}; that.parse(options); ``` 输出结果如下所示: - + ```js 0 0 // 0: 对应事件类型START_DOCUMENT值为0 0:起始深度为0 2 1 // 2: 对应事件类型START_TAG值为2 1:深度为1 @@ -201,36 +201,36 @@ XML模块提供XmlPullParser类对XML文件解析,输入为含有XML文本的A import xml from '@ohos.xml'; import util from '@ohos.util'; -let strXml = +let strXml: string = '' + '' + 'Everyday' + 'Giada' + ''; -let textEncoder = new util.TextEncoder(); -let arrBuffer = textEncoder.encodeInto(strXml); -let that = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); -let str = ''; +let textEncoder: util.TextEncoder = new util.TextEncoder(); +let arrBuffer: Uint8Array = textEncoder.encodeInto(strXml); +let that: xml.XmlPullParser = new xml.XmlPullParser(arrBuffer.buffer, 'UTF-8'); +let str: string = ''; -function tagFunc(name, value) { +function tagFunc(name: string, value: string): boolean { str = name + value; console.info('tag-' + str); return true; } -function attFunc(name, value) { +function attFunc(name: string, value: string): boolean { str = name + ' ' + value; console.info('attri-' + str); return true; } -function tokenFunc(name, value) { +function tokenFunc(name: string, value: xml.ParseInfo): boolean { str = name + ' ' + value.getDepth(); console.info('token-' + str); return true; } -let options = { +let options: xml.ParseOptions = { supportDocType: true, ignoreNameSpace: true, tagValueCallbackFunction: tagFunc, 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/database/data-persistence-by-preferences.md b/zh-cn/application-dev/database/data-persistence-by-preferences.md index 8385bd06cfc8326bccb04c79e430018b2ff56730..c5a6f64a0c47e540aa14b3ca85f04d106db1ef7e 100644 --- a/zh-cn/application-dev/database/data-persistence-by-preferences.md +++ b/zh-cn/application-dev/database/data-persistence-by-preferences.md @@ -58,11 +58,13 @@ ```js import UIAbility from '@ohos.app.ability.UIAbility'; + import { BusinessError } from '@ohos.base'; + import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => { + dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => { if (err) { console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); return; @@ -82,12 +84,13 @@ ```js import featureAbility from '@ohos.ability.featureAbility'; + import { BusinessError } from '@ohos.base'; // 获取context let context = featureAbility.getContext(); try { - dataPreferences.getPreferences(context, 'mystore', (err, preferences) => { + dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => { if (err) { console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); return; @@ -157,7 +160,7 @@ ```js try { - preferences.flush((err) => { + preferences.flush((err: BusinessError) => { if (err) { console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); return; @@ -174,18 +177,20 @@ 应用订阅数据变更需要指定observer作为回调方法。订阅的Key值发生变更后,当执行flush()方法时,observer被触发回调。示例代码如下所示: ```js - let observer = function (key) { - console.info('The key' + key + 'changed.'); + interface observer { + key: string } - preferences.on('change', observer); + preferences.on('change', (key: observer) => { + console.info('The key' + key + 'changed.'); + }); // 数据产生变更,由'auto'变为'manual' - preferences.put('startup', 'manual', (err) => { + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`); return; } console.info("Succeeded in putting the value of 'startup'."); - preferences.flush((err) => { + preferences.flush((err: BusinessError) => { if (err) { console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); return; @@ -210,7 +215,7 @@ ```js try { - dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => { + dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { if (err) { console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`); return; diff --git a/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md b/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md index 4dd9be9bcc82e00fef53b5ad901e2582ccc18af7..8f3cca0be0fac2dc1ec8bb1e1d7738309c914d68 100644 --- a/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md +++ b/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md @@ -151,17 +151,26 @@ // 导入模块 import distributedDataObject from '@ohos.data.distributedDataObject'; import UIAbility from '@ohos.app.ability.UIAbility'; - + import { BusinessError } from '@ohos.base'; + import window from '@ohos.window'; + + interface sourceObject{ + name: string, + age: number, + isVis: boolean + parent: { [key: string]: string }, + list: { [key: string]: string }[] + } class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - let localObject = distributedDataObject.create(this.context, { + onWindowStageCreate(windowStage: window.WindowStage) { + let source: sourceObject = { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - }); + } + let localObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, source); } } ``` @@ -175,34 +184,43 @@ import featureAbility from '@ohos.ability.featureAbility'; // 获取context let context = featureAbility.getContext(); - // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - let localObject = distributedDataObject.create(context, { + interface sourceObject{ + name: string, + age: number, + isVis: boolean + parent: { [key: string]: string }, + list: { [key: string]: string }[] + } + let source: sourceObject = { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - }); + } + // 创建对象,该对象包含4个属性类型:string、number、boolean和Object + let localObject: distributedDataObject.DataObject = distributedDataObject.create(context, source); ``` 4. 加入同步组网。同步组网中的数据对象分为发起方和被拉起方。 ```js // 设备1加入sessionId - let sessionId = '123456'; + let sessionId: string = '123456'; localObject.setSessionId(sessionId); // 和设备1协同的设备2加入同一个session // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - let remoteObject = distributedDataObject.create(this.context, { + let remoteSource: sourceObject = { name: undefined, age: undefined, // undefined表示数据来自对端 isVis: true, parent: undefined, list: undefined - }); + } + let remoteObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, remoteSource); // 收到status上线后remoteObject同步数据,即name变成jack,age是18 remoteObject.setSessionId(sessionId); ``` @@ -210,18 +228,19 @@ 5. 监听对象数据变更。可监听对端数据的变更,以callback作为变更回调实例。 ```js - function changeCallback(sessionId, changeData) { - console.info(`change: ${sessionId}`); - - if (changeData !== null && changeData !== undefined) { - changeData.forEach(element => { - console.info(`The element ${localObject[element]} changed.`); - }); - } + interface ChangeCallback { + sessionId: string, + fields: Array } - // 发起方要在changeCallback里刷新界面,则需要将正确的this绑定给changeCallback - localObject.on("change", this.changeCallback.bind(this)); + localObject.on("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info(`The element ${localObject[changeData.fields[index]]} changed.`); + } + } + }); ``` 6. 修改对象属性,对象属性支持基本类型(数字类型、布尔类型、字符串类型)以及复杂类型(数组、基本类型嵌套等)。 @@ -256,7 +275,14 @@ ```js // 删除变更回调changeCallback - localObject.off('change', this.changeCallback); + localObject.off('change',(changeData: ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } + }); // 删除所有的变更回调 localObject.off('change'); ``` @@ -264,27 +290,32 @@ 9. 监听分布式数据对象的上下线。可以监听对端分布式数据对象的上下线。 ```js - function statusCallback(sessionId, networkId, status) { - // 业务处理 + interface onStatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' } - localObject.on('status', this.statusCallback); + localObject.on('status', (statusCallback: onStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); + // 业务处理 + }); ``` 10. 保存和撤回已保存的数据对象。 ```js // 保存数据对象,如果应用退出后组网内设备需要恢复对象数据时调用 - localObject.save('local').then((result) => { + localObject.save("local").then((result: distributedDataObject.SaveSuccessResponse) => { console.info(`Succeeded in saving. SessionId:${result.sessionId},version:${result.version},deviceId:${result.deviceId}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Failed to save. Code:${err.code},message:${err.message}`); }); // 撤回保存的数据对象 - localObject.revokeSave().then((result) => { + localObject.revokeSave().then((result: distributedDataObject.RevokeSaveSuccessResponse) => { console.info(`Succeeded in revokeSaving. Session:${result.sessionId}`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Failed to revokeSave. Code:${err.code},message:${err.message}`); }); ``` @@ -292,8 +323,16 @@ 11. 删除监听分布式数据对象的上下线。可以指定删除监听的上下线回调;也可以不指定,这将会删除该分布式数据对象的所有上下线回调。 ```js + interface offStatusCallback { + sessionId: string, + deviceId: string, + status: 'online' | 'offline' + } // 删除上下线回调statusCallback - localObject.off('status', this.statusCallback); + localObject.off('status', (statusCallback: offStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId); + // 业务处理 + }); // 删除所有的上下线回调 localObject.off('status'); ``` @@ -302,7 +341,7 @@ ```js localObject.setSessionId(() => { - console.info('leave all lession.'); + console.info('leave all session.'); }); ``` diff --git a/zh-cn/application-dev/file-management/app-file-access.md b/zh-cn/application-dev/file-management/app-file-access.md index e7924858d1033f6231df862bade0a22de13c673a..eb3e5e4cdb3bc679242fef8f6fa0805cc9a9315a 100644 --- a/zh-cn/application-dev/file-management/app-file-access.md +++ b/zh-cn/application-dev/file-management/app-file-access.md @@ -46,8 +46,9 @@ // pages/xxx.ets import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; +import buffer from '@ohos.buffer'; -function createFile() { +createFile() { // 获取应用文件路径 let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; @@ -58,9 +59,10 @@ function createFile() { let writeLen = fs.writeSync(file.fd, "Try to write str."); console.info("The length of str is: " + writeLen); // 从文件读取一段内容 - let buf = new ArrayBuffer(1024); - let readLen = fs.readSync(file.fd, buf, { offset: 0 }); - console.info("the content of file: " + String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))); + let arrayBuffer = new ArrayBuffer(1024); + let readLen = fs.readSync(file.fd, arrayBuffer, { offset: 0 }); + let buf = buffer.from(arrayBuffer, 0, readLen); + console.info("the content of file: " + buf.toString()); // 关闭文件 fs.closeSync(file); } @@ -75,7 +77,7 @@ function createFile() { import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; -function readWriteFile() { +readWriteFile() { // 获取应用文件路径 let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; @@ -112,7 +114,7 @@ function readWriteFile() { import fs from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; -async function readWriteFileWithStream() { +async readWriteFileWithStream() { // 获取应用文件路径 let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; @@ -147,7 +149,7 @@ async function readWriteFileWithStream() { ```ts // 查看文件列表 -import fs from '@ohos.file.fs'; +import fs, { Filter } from '@ohos.file.fs'; import common from '@ohos.app.ability.common'; // 获取应用文件路径 @@ -155,18 +157,20 @@ let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; // 查看文件列表 -let options = { - recursion: false, - listNum: 0, - filter: { +getListFile() { + let filter: Filter = { suffix: ['.png', '.jpg', '.txt'], // 匹配文件后缀名为'.png','.jpg','.txt' displayName: ['test%'], // 匹配文件全名以'test'开头 fileSizeOver: 0, // 匹配文件大小大于等于0 lastModifiedAfter: new Date(0).getTime(), // 匹配文件最近修改时间在1970年1月1日之后 - }, -} -let files = fs.listFileSync(filesDir, options); -for (let i = 0; i < files.length; i++) { - console.info(`The name of file: ${files[i]}`); + } + let files = fs.listFileSync(filesDir, { + recursion: false, + listNum: 0, + filter: filter + }); + for (let i = 0; i < files.length; i++) { + console.info(`The name of file: ${files[i]}`); + } } ``` diff --git a/zh-cn/application-dev/file-management/app-file-backup.md b/zh-cn/application-dev/file-management/app-file-backup.md index 7b8eb451978a70db57e4905d9a93da92e9d11ad0..1928f6c4366748687bfa46702876d96b91ec5d29 100644 --- a/zh-cn/application-dev/file-management/app-file-backup.md +++ b/zh-cn/application-dev/file-management/app-file-backup.md @@ -32,7 +32,7 @@ 调用`backup.getLocalCapabilities()`获取能力文件。 - ```js + ```ts import fs from '@ohos.file.fs'; async function getLocalCapabilities() { try { @@ -89,16 +89,21 @@ ```ts import fs from '@ohos.file.fs'; + import common from '@ohos.app.ability.common'; + import { BusinessError } from '@ohos.base'; + + let context = getContext(this) as common.UIAbilityContext; + let filesDir = context.filesDir; // 创建SessionBackup类的实例用于备份数据 - let g_session; - function createSessionBackup() { + let g_session: backup.SessionBackup; + createSessionBackup() { let sessionBackup = new backup.SessionBackup({ - onFileReady: async (err, file) => { + onFileReady: (err: BusinessError, file: backup.File) => { if (err) { console.info('onFileReady err: ' + err); } try { - let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName; + let bundlePath = filesDir + '/' + file.bundleName; if (!fs.accessSync(bundlePath)) { fs.mkdirSync(bundlePath); } @@ -109,21 +114,21 @@ console.error('onFileReady failed with err: ' + e); } }, - onBundleBegin: (err, bundleName) => { + onBundleBegin: (err: BusinessError, bundleName: string) => { if (err) { console.info('onBundleBegin err: ' + err); } else { console.info('onBundleBegin bundleName: ' + bundleName); } }, - onBundleEnd: (err, bundleName) => { + onBundleEnd: (err: BusinessError, bundleName: string) => { if (err) { console.info('onBundleEnd err: ' + err); } else { console.info('onBundleEnd bundleName: ' + bundleName); } }, - onAllBundlesEnd: (err) => { + onAllBundlesEnd: (err: BusinessError) => { if (err) { console.info('onAllBundlesEnd err: ' + err); } else { @@ -137,12 +142,11 @@ return sessionBackup; } - async function sessionBackup () - { + async sessionBackup () { g_session = createSessionBackup(); // 此处可根据backup.getLocalCapabilities()提供的能力文件,选择需要备份的应用 // 也可直接根据应用包名称进行备份 - const backupApps = [ + const backupApps: string[] = [ "com.example.hiworld", ] await g_session.appendBundles(backupApps); @@ -163,22 +167,21 @@ ```ts import fs from '@ohos.file.fs'; // 创建SessionRestore类的实例用于恢复数据 - let g_session; - async function publishFile(file) - { + let g_session: backup.SessionRestore; + async publishFile(file: backup.File) { await g_session.publishFile({ bundleName: file.bundleName, uri: file.uri }); } - function createSessionRestore() { + createSessionRestore() { let sessionRestore = new backup.SessionRestore({ - onFileReady: (err, file) => { + onFileReady: (err: BusinessError, file: backup.File) => { if (err) { console.info('onFileReady err: ' + err); } // 此处开发者请根据实际场景待恢复文件存放位置进行调整 bundlePath - let bundlePath; + let bundlePath: string; if (!fs.accessSync(bundlePath)) { console.info('onFileReady bundlePath err : ' + bundlePath); } @@ -188,19 +191,19 @@ publishFile(file); console.info('onFileReady success'); }, - onBundleBegin: (err, bundleName) => { + onBundleBegin: (err: BusinessError, bundleName: string) => { if (err) { console.error('onBundleBegin failed with err: ' + err); } console.info('onBundleBegin success'); }, - onBundleEnd: (err, bundleName) => { + onBundleEnd: (err: BusinessError, bundleName: string) => { if (err) { console.error('onBundleEnd failed with err: ' + err); } console.info('onBundleEnd success'); }, - onAllBundlesEnd: (err) => { + onAllBundlesEnd: (err: BusinessError) => { if (err) { console.error('onAllBundlesEnd failed with err: ' + err); } @@ -213,10 +216,9 @@ return sessionRestore; } - async function restore () - { + async restore01 () { g_session = createSessionRestore(); - const backupApps = [ + const backupApps: string[] = [ "com.example.hiworld", ] // 能力文件的获取方式可以根据开发者实际场景进行调整。此处仅为请求示例 @@ -251,21 +253,20 @@ ```ts import fs from '@ohos.file.fs'; // 创建SessionRestore类的实例用于恢复数据 - let g_session; - async function publishFile(file) - { + let g_session: backup.SessionRestore; + async publishFile(file) { await g_session.publishFile({ bundleName: file.bundleName, uri: file.uri }); } - function createSessionRestore() { + createSessionRestore() { let sessionRestore = new backup.SessionRestore({ - onFileReady: (err, file) => { + onFileReady: (err: BusinessError, file: backup.File) => { if (err) { console.info('onFileReady err: ' + err); } - let bundlePath; + let bundlePath: string; if( file.uri == "/data/storage/el2/restore/bundle.hap" ) { // 此处开发者请根据实际场景安装包的存放位置进行调整 @@ -281,19 +282,19 @@ publishFile(file); console.info('onFileReady success'); }, - onBundleBegin: (err, bundleName) => { + onBundleBegin: (err: BusinessError, bundleName: string) => { if (err) { console.error('onBundleBegin failed with err: ' + err); } console.info('onBundleBegin success'); }, - onBundleEnd: (err, bundleName) => { + onBundleEnd: (err: BusinessError, bundleName: string) => { if (err) { console.error('onBundleEnd failed with err: ' + err); } console.info('onBundleEnd success'); }, - onAllBundlesEnd: (err) => { + onAllBundlesEnd: (err: BusinessError) => { if (err) { console.error('onAllBundlesEnd failed with err: ' + err); } @@ -306,10 +307,9 @@ return sessionRestore; } - async function restore () - { + async restore02 () { g_session = createSessionRestore(); - const backupApps = [ + const backupApps: string[] = [ "com.example.hiworld", ] let fpath = await globalThis.context.filesDir + '/localCapabilities.json'; diff --git a/zh-cn/application-dev/file-management/app-file-upload-download.md b/zh-cn/application-dev/file-management/app-file-upload-download.md index a4c8e623bfaa943a9043fcc1b9bbc458dfe42243..bde07c15debc054dcf3b70ea7307d28c9990d40b 100644 --- a/zh-cn/application-dev/file-management/app-file-upload-download.md +++ b/zh-cn/application-dev/file-management/app-file-upload-download.md @@ -19,6 +19,7 @@ import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; import request from '@ohos.request'; +import { BusinessError } from '@ohos.base'; // 获取应用文件路径 let context = getContext(this) as common.UIAbilityContext; @@ -30,29 +31,29 @@ fs.writeSync(file.fd, 'upload file test'); fs.closeSync(file); // 上传任务配置项 -let uploadConfig = { +let files: Array = [ + { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } +] +let data: request.RequestData = { name: 'name', value: 'value' }; +let uploadConfig: request.UploadConfig = { url: 'https://xxx', header: { key1: 'value1', key2: 'value2' }, method: 'POST', - files: [ - { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' } - ], - data: [ - { name: 'name', value: 'value' } - ] + files: files, + data: [ data ] } // 将本地应用文件上传至网络服务器 try { request.uploadFile(context, uploadConfig) - .then((uploadTask) => { - uploadTask.on('complete', (taskStates) => { + .then((uploadTask: request.UploadTask) => { + uploadTask.on('complete', (taskStates: Array) => { for (let i = 0; i < taskStates.length; i++) { console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`); } }); }) - .catch((err) => { + .catch((err: BusinessError) => { console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`); }) } catch (err) { @@ -78,6 +79,7 @@ try { import common from '@ohos.app.ability.common'; import fs from '@ohos.file.fs'; import request from '@ohos.request'; +import { BusinessError } from '@ohos.base'; // 获取应用文件路径 let context = getContext(this) as common.UIAbilityContext; @@ -87,16 +89,17 @@ try { request.downloadFile(context, { url: 'https://xxxx/xxxx.txt', filePath: filesDir + '/xxxx.txt' - }).then((downloadTask) => { + }).then((downloadTask: request.DownloadTask) => { downloadTask.on('complete', () => { console.info('download complete'); let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE); - let buf = new ArrayBuffer(1024); - let readLen = fs.readSync(file.fd, buf); - console.info(`The content of file: ${String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)))}`); + let arrayBuffer = new ArrayBuffer(1024); + let readLen = fs.readSync(file.fd, arrayBuffer); + let buf = buffer.from(arrayBuffer, 0, readLen); + console.info(`The content of file: ${buf.toString()}`); fs.closeSync(file); }) - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`); }); } catch (err) { diff --git a/zh-cn/application-dev/file-management/app-fs-space-statistics.md b/zh-cn/application-dev/file-management/app-fs-space-statistics.md index a3d585ff4010b55373980ea22f88a755e036dfb5..210759129a7f4e54f17a32f0016624962279cc9c 100644 --- a/zh-cn/application-dev/file-management/app-fs-space-statistics.md +++ b/zh-cn/application-dev/file-management/app-fs-space-statistics.md @@ -28,9 +28,10 @@ API的详细介绍请参见[ohos.file.statvfs](../reference/apis/js-apis-file-st ```ts import statvfs from '@ohos.file.statvfs'; + import { BusinessError } from '@ohos.base'; let path = "/data"; - statvfs.getFreeSize(path, (err, number) => { + statvfs.getFreeSize(path, (err: BusinessError, number: number) => { if (err) { console.error(`Invoke getFreeSize failed, code is ${err.code}, message is ${err.message}`); } else { @@ -43,8 +44,9 @@ API的详细介绍请参见[ohos.file.statvfs](../reference/apis/js-apis-file-st ```ts import storageStatistics from "@ohos.file.storageStatistics"; + import { BusinessError } from '@ohos.base'; - storageStatistics.getCurrentBundleStats((err, bundleStats) => { + storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => { if (err) { console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`); } else { diff --git a/zh-cn/application-dev/file-management/dev-user-file-manager.md b/zh-cn/application-dev/file-management/dev-user-file-manager.md index 8aef15fe41151238f88c7d18781d6e9322f8ae26..4ee4838b0fe7a136887d5ad926dc15cef127c4b9 100644 --- a/zh-cn/application-dev/file-management/dev-user-file-manager.md +++ b/zh-cn/application-dev/file-management/dev-user-file-manager.md @@ -22,6 +22,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ```ts import fileAccess from '@ohos.file.fileAccess'; import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; + import { Filter } from '@ohos.file.fs'; ``` 其中fileAccess提供了文件基础操作的API,fileExtensionInfo提供了应用开发的关键结构体。 @@ -33,7 +34,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ```ts // 创建连接系统内所有文件管理服务端的helper对象 - let fileAccessHelperAllServer = null; + let fileAccessHelperAllServer: fileAccess.FileAccessHelper; createFileAccessHelper() { try { // this.context是EntryAbility传过来的Context fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context); @@ -44,23 +45,23 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); } } - async getRoots() { - let rootIterator = null; - let rootInfos = []; - let isDone = false; + async getRoots() { + let rootIterator: fileAccess.RootIterator; + let rootInfos: fileAccess.RootInfo[] = []; + let isDone: boolean = false; try { rootIterator = await fileAccessHelperAllServer.getRoots(); if (!rootIterator) { console.error("getRoots interface returns an undefined object"); - return; - } + return; + } while (!isDone) { let result = rootIterator.next(); console.info("next result = " + JSON.stringify(result)); isDone = result.done; if (!isDone) - rootinfos.push(result.value); - } + rootInfos.push(result.value); + } } catch (error) { console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); } @@ -74,10 +75,10 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 ```ts // 从根目录开始 - let rootInfo = rootinfos[0]; - let fileInfos = []; - let isDone = false; - let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 + let rootInfo = rootInfos[0]; + let fileInfos: fileAccess.FileInfo[] = []; + let isDone: boolean = false; + let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 try { let fileIterator = rootInfo.listFile(); // 遍历设备rootinfos[0]的根目录,返回迭代器对象 // let fileIterator = rootInfo.scanFile(filter); // 过滤设备rootinfos[0]满足指定条件的文件信息,返回迭代对象 @@ -98,9 +99,9 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 // 从指定的目录开始 let fileInfoDir = fileInfos[0]; // fileInfoDir 表示某个目录信息 - let subFileInfos = []; - let isDone = false; - let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 + let subFileInfos: fileAccess.FileInfo[] = []; + let isDone: boolean = false; + let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // 设定过滤条件 try { let fileIterator = fileInfoDir.listFile(); // 遍历特定的目录fileinfo,返回迭代器对象 // let fileIterator = rootInfo.scanFile(filter); // 过滤特定的目录fileinfo,返回迭代器对象 @@ -113,7 +114,7 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 console.info("next result = " + JSON.stringify(result)); isDone = result.done; if (!isDone) - subfileInfos.push(result.value); + subFileInfos.push(result.value); } } catch (error) { console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); @@ -128,9 +129,9 @@ OpenHarmony预置了FileManager文件管理器。系统应用开发者也可以 // 创建文件 // 示例代码sourceUri是Download目录的fileinfo中的URI // 开发者应根据自己实际获取fileinfo的URI进行开发 - let sourceUri = "file://docs/storage/Users/currentUser/Download"; - let displayName = "file1"; - let fileUri = null; + let sourceUri: string = "file://docs/storage/Users/currentUser/Download"; + let displayName: string = "file1"; + let fileUri: string; try { // fileAccessHelper 参考 fileAccess.createFileAccessHelper 示例代码获取 fileUri = await fileAccessHelper.createFile(sourceUri, displayName); diff --git a/zh-cn/application-dev/file-management/file-access-across-devices.md b/zh-cn/application-dev/file-management/file-access-across-devices.md index 2e0443f9b0817c73cd082413e5bf40ea0931505c..b113f565d4c7aa881dccec74c11185d9ae69a551 100644 --- a/zh-cn/application-dev/file-management/file-access-across-devices.md +++ b/zh-cn/application-dev/file-management/file-access-across-devices.md @@ -14,11 +14,12 @@ ```ts import fs from '@ohos.file.fs'; - - let context = ...; // 获取设备A的UIAbilityContext信息 - let pathDir = context.distributedFilesDir; + import common from '@ohos.app.ability.common'; + + let context = getContext(this) as common.UIAbilityContext; // 获取设备A的UIAbilityContext信息 + let pathDir: string = context.distributedFilesDir; // 获取分布式目录的文件路径 - let filePath = pathDir + '/test.txt'; + let filePath: string = pathDir + '/test.txt'; try { // 在分布式目录下创建文件 @@ -37,23 +38,26 @@ ```ts import fs from '@ohos.file.fs'; + import common from '@ohos.app.ability.common'; + import buffer from '@ohos.buffer'; - let context = ...; // 获取设备B的UIAbilityContext信息 - let pathDir = context.distributedFilesDir; + let context = getContext(this) as common.UIAbilityContext; // 获取设备B的UIAbilityContext信息 + let pathDir: string = context.distributedFilesDir; // 获取分布式目录的文件路径 - let filePath = pathDir + '/test.txt'; + let filePath: string = pathDir + '/test.txt'; try { // 打开分布式目录下的文件 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); // 定义接收读取数据的缓存 - let buffer = new ArrayBuffer(4096); + let arrayBuffer = new ArrayBuffer(4096); // 读取文件的内容,返回值是读取到的字节个数 - let num = fs.readSync(file.fd, buffer, { + let num = fs.readSync(file.fd, arrayBuffer, { offset: 0 }); // 打印读取到的文件数据 - console.info('read result: ' + String.fromCharCode.apply(null, new Uint8Array(buffer.slice(0, num)))); + let buf = buffer.from(arrayBuffer, 0, num); + console.info('read result: ' + buf.toString()); } catch (err) { console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`); } diff --git a/zh-cn/application-dev/file-management/manage-external-storage.md b/zh-cn/application-dev/file-management/manage-external-storage.md index 3605bb615958975d445536bc24ff97399575171c..8ed79dbc3678d448b5614aea9d0280fd42f9c241 100644 --- a/zh-cn/application-dev/file-management/manage-external-storage.md +++ b/zh-cn/application-dev/file-management/manage-external-storage.md @@ -55,8 +55,9 @@ ```ts import CommonEvent from '@ohos.commonEventManager'; import volumeManager from '@ohos.file.volumeManager'; - - const subscribeInfo = { + import { BusinessError } from '@ohos.base'; + + const subscribeInfo: CommonEvent.CommonEventSubscribeInfo = { events: [ "usual.event.data.VOLUME_REMOVED", "usual.event.data.VOLUME_UNMOUNTED", @@ -71,11 +72,11 @@ 3. 收到广播通知后获取卷设备信息。 ```ts - CommonEvent.subscribe(subscriber, function (err, data) { + CommonEvent.subscribe(subscriber, (err: BusinessError, data: CommonEvent.CommonEventData) => { if (data.event === 'usual.event.data.VOLUME_MOUNTED') { // 开发者可以通过广播传递的卷设备信息来管理卷设备 - let volId = data.parameters.id; - volumeManager.getVolumeById(volId, function(error, vol) { + let volId: string = data.parameters.id; + volumeManager.getVolumeById(volId, (error: BusinessError, vol: volumeManager.Volume) => { if (error) { console.error('volumeManager getVolumeById failed'); } else { diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md index 9e4e15b41f6b00a9f2b5715a2b362efcfcad44a2..a6568e442d847946af56ba3a189f0010c391569c 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-notify-guidelines.md @@ -33,20 +33,21 @@ photoAccessHelper提供监听媒体资源变更的接口,供开发者对指定 ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - let onCallback = (changeData) => { + let onCallback = (changeData:dataSharePredicates.ChangeData) => { console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); } phAccessHelper.registerChange(fileAsset.uri, false, onCallback); @@ -77,21 +78,22 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper.AlbumKeys = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, 'albumName'); -let fetchOptions = { +let fetchOptions: dataSharePredicates.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('getAlbums successfullyfully, albumName: ' + album.albumUri); - let onCallback = (changeData) => { + let onCallback = (changeData: photoAccessHelper.ChangeData) => { console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); } phAccessHelper.registerChange(album.albumUri, false, onCallback); @@ -127,21 +129,22 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let onCallback = (changeData) => { +let onCallback = (changeData: dataSharePredicates.ChangeData) => { console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); } phAccessHelper.registerChange(photoAccessHelper.DefaultChangeUri.DEFAULT_PHOTO_URI, true, onCallback); -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.uri : ' + fileAsset.uri); await fileAsset.favorite(true); fetchResult.close(); @@ -169,23 +172,24 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.uri : ' + fileAsset.uri); - let onCallback1 = (changeData) => { + let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { console.info('onCallback1, changData: ' + JSON.stringify(changeData)); } - let onCallback2 = (changeData) => { + let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { console.info('onCallback2, changData: ' + JSON.stringify(changeData)); } phAccessHelper.registerChange(fileAsset.uri, false, onCallback1); diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-overview.md b/zh-cn/application-dev/file-management/photoAccessHelper-overview.md index 6b7f718a3c71276d0fde87f145b9aa4979badc03..9ac3deb5f0c76597d9e78415669c40e7d0168bb1 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-overview.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-overview.md @@ -49,7 +49,7 @@ import photoAccessHelper from '@ohos.file.photoAccessHelper'; // 此处获取的phAccessHelper实例为全局对象,后续文档中使用到的地方默认为使用此处获取的对象,如未添加此段代码报未定义的错误请自行添加。 const context = getContext(this); -let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); +let phAccessHelper: photoAccessHelper.PhotoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); ``` ## 申请相册管理模块功能相关权限 @@ -108,7 +108,7 @@ let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); onWindowStageCreate(windowStage) { let list : Array = ['ohos.permission.READ_IMAGEVIDEO', 'ohos.permission.WRITE_IMAGEVIDEO']; let permissionRequestResult; - let atManager = abilityAccessCtrl.createAtManager(); + let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(this.context, list, (err, result) => { if (err) { console.error('requestPermissionsFromUserError: ' + JSON.stringify(err)); diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md index edc9d8695da6154a9ba8136f98ba87cb8bf5cb3d..a728ea8e283eebd21343551c0030731692ec5069 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-resource-guidelines.md @@ -33,10 +33,11 @@ ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, 'test.jpg'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -45,9 +46,11 @@ let fetchOptions = { 调用PhotoAccessHelper.getAssets接口获取图片资源。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); fetchResult.close(); } catch (err) { @@ -61,10 +64,11 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo(photoAccessHelper.PhotoKeys.URI, 'file://media/Photo/1'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -73,9 +77,11 @@ let fetchOptions = { 调用PhotoAccessHelper.getAssets接口获取图片资源。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.uri : ' + fileAsset.uri); fetchResult.close(); } catch (err) { @@ -90,15 +96,16 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // 查询起始时间距1970年1月1日的秒数值。 -let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // 查询结束时间距1970年1月1日的秒数值。 -let date_added = photoAccessHelper.PhotoKeys.DATE_ADDED; +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let startTime: Number = Date.parse(new Date('2022-06-01').toString()) / 1000; // The value of the start time is the number of seconds elapsed since the Epoch time. +let endTime: Number = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time. +let date_added: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.DATE_ADDED; predicates.between(date_added, startTime, endTime); -predicates.orderByDesc(date_added); // 查询结果按照降序排序。 -let fetchOptions = { - fetchColumns: [date_added], // date_added属性不属于默认查询列,需要自行添加。 +predicates.orderByDesc(date_added); // Sort the obtained records in descending order. +let fetchOptions: photoAccessHelper.FetchOptions = { + fetchColumns: [date_added], // The date_added attribute is not a default option and needs to be added. predicates: predicates }; ``` @@ -106,10 +113,12 @@ let fetchOptions = { 调用PhotoAccessHelper.getAssets接口获取图片资源。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); console.info('getAssets count: ' + fetchResult.getCount()); - let fileAsset = await fetchResult.getFirstObject(); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); fetchResult.close(); } catch (err) { @@ -142,20 +151,22 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; +import image from '@ohos.multimedia.image'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); - let size = { width: 720, height: 720 }; - let pixelMap = await fileAsset.getThumbnail(size); - let imageInfo = await pixelMap.getImageInfo() + let size: image.Size = { width: 720, height: 720 }; + let pixelMap: image.PixelMap = await fileAsset.getThumbnail(size); + let imageInfo: image.ImageInfo = await pixelMap.getImageInfo() console.info('getThumbnail successful, pixelMap ImageInfo size: ' + JSON.stringify(imageInfo.size)); fetchResult.close(); } catch (err) { @@ -182,13 +193,15 @@ try { 2. 调用createAsset接口创建图片资源。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let displayName = 'testPhoto' + Date.now() + '.jpg'; - let createOption = { + let displayName: string = 'testPhoto' + Date.now() + '.jpg'; + let createOption: photoAccessHelper.CreateOptions = { subType: photoAccessHelper.PhotoSubtype.DEFAULT }; - let fileAsset = await phAccessHelper.createAsset(displayName, createOption); + let fileAsset: photoAccessHelper.photoAsset = await phAccessHelper.createAsset(displayName, createOption); console.info('createAsset successfully, file displayName: ' + fileAsset.displayName); } catch (err) { console.error('createAsset failed, message = ', err); @@ -220,19 +233,20 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: ['title'], predicates: predicates }; let newTitle = 'newTestPhoto'; try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); - let title = photoAccessHelper.PhotoKeys.TITLE; - let fileAssetTitle = fileAsset.get(title); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE; + let fileAssetTitle: photoAccessHelper.MemberType = fileAsset.get(title); console.info('getAssets fileAsset.title : ' + fileAssetTitle); fileAsset.set(title, newTitle); await fileAsset.commitModify(); @@ -264,16 +278,17 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('getAssets fileAsset.uri : ' + fileAsset.uri); await phAccessHelper.deleteAssets([fileAsset.uri]); fetchResult.close(); diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md index c28fa585240c448563b44c15f4e91093731fe4c5..11fdee073158b8bddb39d5c8736ef63cad4e37a1 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md @@ -29,9 +29,11 @@ photoAccessHelper仅提供开发者对收藏夹、视频相册、截屏和录屏 2. 调用getAlbums接口获取收藏夹对象。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('get favorite Album successfully, albumUri: ' + album.albumUri); fetchResult.close(); } catch (err) { @@ -58,17 +60,18 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo(photoAccessHelper.ImageVideoKey.DISPLAY_NAME, 'test.jpg'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let photoFetchResult = await phAccessHelper.getAssets(fetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('getAssets fileAsset.displayName : ' + fileAsset.displayName); let favoriteState = true; await fileAsset.setFavorite(favoriteState); @@ -97,20 +100,21 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - let photoFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); photoFetchResult.close(); albumFetchResult.close(); @@ -139,20 +143,21 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get favorite Album successfully, albumUri: ' + album.albumUri); - let photoFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await photoFetchResult.getFirstObject(); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getFirstObject(); console.info('favorite album getAssets successfully, albumName: ' + fileAsset.displayName); let favoriteState = false; await fileAsset.setFavorite(favoriteState); @@ -182,9 +187,11 @@ try { 2. 调用getAlbums接口获取视频相册。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); - let album = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('get video Album successfully, albumUri: ' + album.albumUri); fetchResult.close(); } catch (err) { @@ -212,20 +219,21 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get video Album successfully, albumUri: ' + album.albumUri); - let videoFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await videoFetchResult.getFirstObject(); + let videoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await videoFetchResult.getFirstObject(); console.info('video album getAssets successfully, albumName: ' + fileAsset.displayName); videoFetchResult.close(); albumFetchResult.close(); @@ -253,9 +261,11 @@ try { 2. 调用getAlbums接口获取截屏和录屏相册。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); - let album = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('get screenshot Album successfully, albumUri: ' + album.albumUri); fetchResult.close(); } catch (err) { @@ -283,20 +293,21 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let fetchOptions = { +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.SCREENSHOT); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('get screenshot album successfully, albumUri: ' + album.albumUri); - let screenshotFetchResult = await album.getAssets(fetchOptions); - let fileAsset = await screenshotFetchResult.getFirstObject(); + let screenshotFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); + let fileAsset: photoAccessHelper.PhotoAsset = await screenshotFetchResult.getFirstObject(); console.info('screenshot album getAssets successfully, albumName: ' + fileAsset.displayName); screenshotFetchResult.close(); albumFetchResult.close(); diff --git a/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md b/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md index 475f76b615abc96cfe420f356c7d543c5a724ddf..1480b71b26ccde6e849a80f2f9fa8c952846e82b 100644 --- a/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md +++ b/zh-cn/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md @@ -34,9 +34,11 @@ photoAccessHelper提供用户相册相关的接口,供开发者创建、删除 2. 调用createAlbum接口创建相册。 ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { - let albumName = 'albumName'; - let album = await phAccessHelper.createAlbum(albumName); + let albumName: photoAccessHelper.AlbumName = 'albumName'; + let album: photoAccessHelper.Album = await phAccessHelper.createAlbum(albumName); console.info('createAlbum successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri); } catch (err) { console.error('createAlbum failed with err: ' + err); @@ -62,18 +64,19 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, 'albumName'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); fetchResult.close(); } catch (err) { @@ -108,18 +111,19 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); -let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, 'albumName'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); album.albumName = 'newAlbumName'; await album.commitModify(); @@ -152,24 +156,25 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let albumPredicates = new dataSharePredicates.DataSharePredicates(); -let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; +let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let albumName: photoAccessHelper = photoAccessHelper.AlbumKey.ALBUM_NAME; albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions = { +let albumFetchOptions: dataSharePredicates.FetchOptions = { fetchColumns: [], predicates: albumPredicates }; -let photoPredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions = { +let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: photoPredicates }; try { - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); let photoFetchResult = await phAccessHelper.getAssets(photoFetchOptions); let fileAsset = await photoFetchResult.getFirstObject(); @@ -204,24 +209,25 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let albumPredicates = new dataSharePredicates.DataSharePredicates(); +let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions = { +let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: albumPredicates }; -let photoPredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions = { +let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: photoPredicates }; try { - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); let photoFetchResult = await album.getAssets(photoFetchOptions); let fileAsset = await photoFetchResult.getFirstObject(); @@ -258,24 +264,25 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let albumPredicates = new dataSharePredicates.DataSharePredicates(); +let albumPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; albumPredicates.equalTo(albumName, 'albumName'); -let albumFetchOptions = { +let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: albumPredicates }; -let photoPredicates = new dataSharePredicates.DataSharePredicates(); -let photoFetchOptions = { +let photoPredicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); +let photoFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: photoPredicates }; try { - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); let photoFetchResult = await album.getAssets(photoFetchOptions); let fileAsset = await photoFetchResult.getFirstObject(); @@ -308,18 +315,19 @@ try { ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let predicates = new dataSharePredicates.DataSharePredicates(); +let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); let albumName = photoAccessHelper.AlbumKey.ALBUM_NAME; predicates.equalTo(albumName, '%albumName%'); -let fetchOptions = { +let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); - let album = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('getAlbums successfully, albumName: ' + album.albumName); phAccessHelper.deleteAlbums([album]); fetchResult.close(); diff --git a/zh-cn/application-dev/file-management/save-user-file.md b/zh-cn/application-dev/file-management/save-user-file.md index ff52752af54a91a429b72449d96abacd912a472c..15121f354a20290e5f08e1ac72ba7bfae1ff0c56 100644 --- a/zh-cn/application-dev/file-management/save-user-file.md +++ b/zh-cn/application-dev/file-management/save-user-file.md @@ -18,33 +18,36 @@ save接口会将文件保存在文件管理器,而不是图库。 import fs from '@ohos.file.fs'; import photoAccessHelper from '@ohos.file.photoAccessHelper'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; + import common from '@ohos.app.ability.common'; + import image from '@ohos.multimedia.image'; + import { BusinessError } from '@ohos.base'; ``` 2. 获取设备里第一张图片的缩略图。注意:在执行这一步之前,要先确保设备里至少有一张图片。 ```ts - const context = getContext(this); - let photoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); + let context = getContext(this) as common.UIAbilityContext; + let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); - let pixelmapArrayBuffer; + let pixelmapArrayBuffer: ArrayBuffer; async getPixelmap() { try { let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await photoAccessHelper.getAssets(fetchOption); + let fetchResult = await phAccessHelper.getAssets(fetchOption); console.info('[picker] getThumbnail fetchResult: ' + fetchResult); const asset = await fetchResult.getFirstObject(); console.info('[picker] getThumbnail asset displayName = ', asset.displayName); - asset.getThumbnail().then((pixelMap) => { + asset.getThumbnail().then((pixelMap: image.PixelMap) => { let pixelBytesNumber = pixelMap.getPixelBytesNumber(); const readBuffer = new ArrayBuffer(pixelBytesNumber); pixelMap.readPixelsToBuffer(readBuffer).then(() => { pixelmapArrayBuffer = readBuffer; }) - }).catch((err) => { + }).catch((err: BusinessError) => { console.error('[picker] getThumbnail failed with error: ' + err); }); } catch (error) { @@ -58,7 +61,7 @@ save接口会将文件保存在文件管理器,而不是图库。 save返回的uri权限是读写权限,可以根据结果集里面的uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uris = null; + let uris: string; async photoViewPickerSave() { try { const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例 @@ -85,7 +88,7 @@ save接口会将文件保存在文件管理器,而不是图库。 然后,通过fd使用[fs.write](../reference/apis/js-apis-file-fs.md#fswrite)接口对这个文件进行编辑修改,编辑修改完成后关闭fd。 ```ts - async writeOnly(uri) { + async writeOnly(uri: string) { try { let file = fs.openSync(uri, fs.OpenMode.WRITE_ONLY); let writeLen = await fs.write(file.fd, pixelmapArrayBuffer); @@ -104,6 +107,7 @@ save接口会将文件保存在文件管理器,而不是图库。 ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. 创建文档保存选项实例。 @@ -119,12 +123,12 @@ save接口会将文件保存在文件管理器,而不是图库。
save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uris = null; + let uris: Array; const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 - documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => { + documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array) => { uris = documentSaveResult; console.info('documentViewPicker.save to file succeed and uris are:' + uris); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -151,6 +155,7 @@ save接口会将文件保存在文件管理器,而不是图库。 ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. 创建音频保存选项实例。 @@ -165,12 +170,12 @@ save接口会将文件保存在文件管理器,而不是图库。
save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uri = null; + let uri: string; const audioViewPicker = new picker.AudioViewPicker(); - audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => { + audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array) => { uri = audioSelectResult[0]; console.info('audioViewPicker.save to file succeed and uri is:' + uri); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) ``` diff --git a/zh-cn/application-dev/file-management/select-user-file.md b/zh-cn/application-dev/file-management/select-user-file.md index 8d8689edb49c72746e21c68b04d1970a244f46a2..1bd67b591f9209176452b2ef484d517f90a49acd 100644 --- a/zh-cn/application-dev/file-management/select-user-file.md +++ b/zh-cn/application-dev/file-management/select-user-file.md @@ -17,6 +17,7 @@ ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. 创建图库选择选项实例。 @@ -38,12 +39,12 @@
select返回的uri权限是只读权限,可以根据结果集中uri进行读取文件数据操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。 ```ts - let uris = null; + let uris: Array; const photoViewPicker = new picker.PhotoViewPicker(); - photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => { + photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => { uris = photoSelectResult.photoUris; console.info('photoViewPicker.select to file succeed and uris are:' + uris); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -71,6 +72,8 @@ ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import Want from '@ohos.app.ability.Want'; + import { BusinessError } from '@ohos.base'; ``` 2. 创建文档选择选项实例。 @@ -89,12 +92,12 @@
例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据uri获取部分文件属性信息,比如文件大小、访问时间、修改时间等。如有获取文件名称需求,请暂时使用[startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md)获取。 ```ts - let uris = null; + let uris: Array; const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例 - documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { + documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array) => { uris = documentSelectResult; console.info('documentViewPicker.select to file succeed and uris are:' + uris); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -104,7 +107,7 @@ > 目前DocumentSelectOptions功能不完整, 如需获取文件名称,请使用startAbilityForResult接口。 ```ts - let config = { + let config: Want = { action: 'ohos.want.action.OPEN_FILE', parameters: { startMode: 'choose', @@ -149,6 +152,7 @@ ```ts import picker from '@ohos.file.picker'; import fs from '@ohos.file.fs'; + import { BusinessError } from '@ohos.base'; ``` 2. 创建音频选择选项实例。 @@ -168,12 +172,12 @@ > 目前AudioSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。 ```ts - let uri = null; + let uri: string; const audioViewPicker = new picker.AudioViewPicker(); - audioViewPicker.select(audioSelectOptions).then(audioSelectResult => { + audioViewPicker.select(audioSelectOptions).then((audioSelectResult: Array) => { uri = audioSelectResult[0]; console.info('audioViewPicker.select to file succeed and uri is:' + uri); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) ``` diff --git a/zh-cn/application-dev/file-management/set-security-label.md b/zh-cn/application-dev/file-management/set-security-label.md index a936e10442733389fc2c764b0a947aea57b496c7..97a5a07a9435a407004452c4511f6a9a226137f4 100644 --- a/zh-cn/application-dev/file-management/set-security-label.md +++ b/zh-cn/application-dev/file-management/set-security-label.md @@ -26,16 +26,18 @@ API详细介绍请参见[ohos.file.securityLabel](../reference/apis/js-apis-file ```ts import securityLabel from '@ohos.file.securityLabel'; +import { BusinessError } from '@ohos.base'; +import common from '@ohos.app.ability.common'; // 获取需要设备数据等级的文件沙箱路径 -let context = ...; // 获取UIAbilityContext信息 +let context = getContext(this) as common.UIAbilityContext; // 获取UIAbilityContext信息 let pathDir = context.filesDir; let filePath = pathDir + '/test.txt'; // 设置文件的数据等级为s0 securityLabel.setSecurityLabel(filePath, 's0').then(() => { console.info('Succeeded in setSecurityLabeling.'); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`); }); ``` diff --git a/zh-cn/application-dev/file-management/share-app-file.md b/zh-cn/application-dev/file-management/share-app-file.md index 2d93e836d3387cbcbe2f1f18ce7741ad4bdc4aab..9186dcad5112cc97bafec468a27a27d064a0a796 100644 --- a/zh-cn/application-dev/file-management/share-app-file.md +++ b/zh-cn/application-dev/file-management/share-app-file.md @@ -54,6 +54,8 @@ import window from '@ohos.window'; import wantConstant from '@ohos.app.ability.wantConstant'; import UIAbility from '@ohos.app.ability.UIAbility'; + import Want from '@ohos.app.ability.Want'; + import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { @@ -61,7 +63,7 @@ let filePath = this.context.filesDir + '/test.txt'; // 将沙箱路径转换为uri let uri = fileuri.getUriFromPath(filePath); - let want = { + let want: Want = { // 配置被分享文件的读写权限,例如对被分享应用进行读写授权 flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, // 配置分享应用的隐式拉起规则 @@ -73,7 +75,7 @@ .then(() => { console.info('Invoke getCurrentBundleStats succeeded.'); }) - .catch((err) => { + .catch((err: BusinessError) => { console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); }); } @@ -120,10 +122,11 @@ ```ts // xxx.ets import fs from '@ohos.file.fs'; +import Want from '@ohos.app.ability.Want'; function getShareFile() { try { - let want = ...; // 获取分享方传递过来的want信息 + let want: Want = ...; // 获取分享方传递过来的want信息 // 从want信息中获取uri字段 let uri = want.uri; 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/typical-layout-scenario.md b/zh-cn/application-dev/key-features/multi-device-app-dev/typical-layout-scenario.md index 7f03669d97747365761699c1c9c65b818ff587fd..b67ec12b4420b93425932f64cfc1f3079584ffe1 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/media/audio-recording-overview.md b/zh-cn/application-dev/media/audio-recording-overview.md index df4067839d3434c1e5c9c4d60f8442074bdd953d..2b6564509ee522291e2b43c64502dd2de6e2db82 100644 --- a/zh-cn/application-dev/media/audio-recording-overview.md +++ b/zh-cn/application-dev/media/audio-recording-overview.md @@ -10,7 +10,7 @@ - [OpenSL ES](using-opensl-es-for-recording.md):一套跨平台标准化的音频Native API,同样提供音频输入原子能力,仅支持PCM格式,适用于从其他嵌入式平台移植,或依赖在Native层实现音频输入功能的录音应用使用。 -- [OHAudio](using-ohaudio-for-playback.md):用于音频输入的Native API,此API在设计上实现归一,同时支持普通音频通路和低时延通路。适用于依赖Native层实现音频输入功能的场景。 +- [OHAudio](using-ohaudio-for-recording.md):用于音频输入的Native API,此API在设计上实现归一,同时支持普通音频通路和低时延通路。适用于依赖Native层实现音频输入功能的场景。 ## 开发音频录制应用须知 diff --git a/zh-cn/application-dev/media/camera-device-input.md b/zh-cn/application-dev/media/camera-device-input.md index b3ceea2db9ad0456ec9c44847f5ff3ef561c2642..a2eefd8eb9953812c5397b9f7e5c5098f22d4177 100644 --- a/zh-cn/application-dev/media/camera-device-input.md +++ b/zh-cn/application-dev/media/camera-device-input.md @@ -15,9 +15,9 @@ 2. 通过getCameraManager()方法,获取cameraManager对象。 ```ts - let cameraManager; - let context: any = getContext(this); - cameraManager = camera.getCameraManager(context) + let cameraManager: camera.CameraManager; + let context: Context = getContext(this); // [各类Context的获取方式](../application-models/application-context-stage.md) + 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,24 @@ ```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); + console.error('Failed to createCameraInput errorCode = ' + error.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 +75,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..30515f6286b36dd4de5e45e80a5b23b6f319ca8e 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); + console.info(error.code); } ``` @@ -25,9 +25,9 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 ```ts metadataOutput.start().then(() => { - console.info('Callback returned with metadataOutput started.'); + console.info('Callback returned with metadataOutput started.'); }).catch((err) => { - console.info('Failed to metadataOutput start '+ err.code); + console.info('Failed to metadataOutput start '+ err.code); }); ``` @@ -35,9 +35,9 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 ```ts metadataOutput.stop().then(() => { - console.info('Callback returned with metadataOutput stopped.'); + console.info('Callback returned with metadataOutput stopped.'); }).catch((err) => { - console.info('Failed to metadataOutput stop '+ err.code); + 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 index 5bd22a536e87e5f9976508407bb17cb51d22153e..ca4caadf7d4f771dc7064fcf8008ad339f54d344 100644 --- a/zh-cn/application-dev/media/camera-mode.md +++ b/zh-cn/application-dev/media/camera-mode.md @@ -11,248 +11,247 @@ ## 完整示例 ```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); // [各类Context的获取方式](../application-models/application-context-stage.md) +let cameraManager: camera.CameraManager = camera.getCameraManager(context); if (!cameraManager) { - console.error("camera.getCameraManager error") - return; + console.error("camera.getCameraManager error"); + return; } // 创建ModeManager对象 -context: any = getContext(this) -let modeManager = camera.getModeManager(this.context) +let modeManager: camera.ModeManager = camera.getModeManager(context); if (!cameraManager) { - console.error("camera.getModeManager error") - return; + console.error("camera.getModeManager 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 cameraModeArray = modeManager.getSupportedModes(cameraArray[0]); +let cameraModeArray: Array = modeManager.getSupportedModes(cameraArray[0]); if (cameraModeArray.length <= 0) { - console.error("modeManager.getSupportedModes error") - return; + console.error("modeManager.getSupportedModes error"); + return; } // 创建相机输入流 -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.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 = modeManager.getSupportedOutputCapability(cameraArray[0], cameraModeArray[0]); +let cameraOutputCap: camera.CameraOutputCapability = modeManager.getSupportedOutputCapability(cameraArray[0], cameraModeArray[0]); if (!cameraOutputCap) { - console.error("modeManager.getSupportedOutputCapability error") - return; + console.error("modeManager.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.") + console.error("Failed to create the PreviewOutput instance."); } // 监听预览输出错误信息 -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 = await 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); + console.error('Failed to createPhotoOutput errorCode = ' + error.code); } //创建portrait会话 -let portraitSession +let portraitSession: camera.CaptureSession; try { - portraitSession = modeManager.createCaptureSession(cameraModeArray[0]) + portraitSession = modeManager.createCaptureSession(cameraModeArray[0]); } catch (error) { - console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); + console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); } // 监听portraitSession错误信息 -portraitSession.on('error', (error) => { - console.info(`Capture session error code: ${error.code}`); -}) +portraitSession.on('error', (error: BusinessError) => { + console.info(`Capture session error code: ${error.code}`); +}); // 开始配置会话 try { - portraitSession.beginConfig() + portraitSession.beginConfig(); } catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); + console.error('Failed to beginConfig. errorCode = ' + error.code); } // 向会话中添加相机输入流 try { - portraitSession.addInput(cameraInput) + portraitSession.addInput(cameraInput); } catch (error) { - console.error('Failed to addInput. errorCode = ' + error.code); + console.error('Failed to addInput. errorCode = ' + error.code); } // 向会话中添加预览输出流 try { - portraitSession.addOutput(previewOutput) + portraitSession.addOutput(previewOutput); } catch (error) { - console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); + console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); } // 向会话中添加拍照输出流 try { - portraitSession.addOutput(photoOutput) + portraitSession.addOutput(photoOutput); } catch (error) { - console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); + console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); } // 提交会话配置 -await portraitSession.commitConfig() +await portraitSession.commitConfig(); // 启动会话 await portraitSession.start().then(() => { - console.info('Promise returned to indicate the session start success.'); + console.info('Promise returned to indicate the session start success.'); }) // 获取支持的美颜类型 -let beautyTypes +let beautyTypes: Array; try { - beautyTypes = portraitSession.getSupportedBeautyTypes() + beautyTypes = portraitSession.getSupportedBeautyTypes(); } catch (error) { - console.error('Failed to get the beauty types. errorCode = ' + error.code); + console.error('Failed to get the beauty types. errorCode = ' + error.code); } // 获取支持的美颜类型对应的美颜强度范围 -let beautyRanges +let beautyRanges: Array; try { - beautyRanges = portraitSession.getSupportedBeautyRanges(beautyTypes[0]) + beautyRanges = portraitSession.getSupportedBeautyRanges(beautyTypes[0]); } catch (error) { - console.error('Failed to get the beauty types ranges. errorCode = ' + error.code); + console.error('Failed to get the beauty types ranges. errorCode = ' + error.code); } // 设置美颜类型及对应的美颜强度 try { - portraitSession.setBeauty(beautyTypes[0], beautyRanges[0]) + portraitSession.setBeauty(beautyTypes[0], beautyRanges[0]); } catch (error) { - console.error('Failed to set the beauty type value. errorCode = ' + error.code); + console.error('Failed to set the beauty type value. errorCode = ' + error.code); } // 获取已经设置的美颜类型对应的美颜强度 -let beautyLevel +let beautyLevel: number; try { - beautyLevel = portraitSession.getBeauty(beautyTypes[0]) + beautyLevel = portraitSession.getBeauty(beautyTypes[0]); } catch (error) { - console.error('Failed to get the beauty type value. errorCode = ' + error.code); + console.error('Failed to get the beauty type value. errorCode = ' + error.code); } // 获取支持的滤镜类型 -let filterTypes +let filterTypes: Array; try { - filterTypes = portraitSession.getSupportedFilters() + filterTypes = portraitSession.getSupportedFilters(); } catch (error) { - console.error('Failed to get the filter types. errorCode = ' + error.code); + console.error('Failed to get the filter types. errorCode = ' + error.code); } // 设置滤镜类型 try { - portraitSession.setFilter(filterTypes[0]) + portraitSession.setFilter(filterTypes[0]); } catch (error) { - console.error('Failed to set the filter type value. errorCode = ' + error.code); + console.error('Failed to set the filter type value. errorCode = ' + error.code); } // 获取已经设置的滤镜类型 -let filter +let filter: number; try { - filter = portraitSession.getFilter() + filter = portraitSession.getFilter(); } catch (error) { - console.error('Failed to get the filter type value. errorCode = ' + error.code); + console.error('Failed to get the filter type value. errorCode = ' + error.code); } // 获取支持的虚化类型 -let portraitTypes +let portraitTypes: Array; try { - portraitTypes = portraitSession.getSupportedPortraitEffects() + portraitTypes = portraitSession.getSupportedPortraitEffects(); } catch (error) { - console.error('Failed to get the portrait effects types. errorCode = ' + error.code); + console.error('Failed to get the portrait effects types. errorCode = ' + error.code); } // 设置虚化类型 try { - portraitSession.setPortraitEffect(portraitTypes[0]) + portraitSession.setPortraitEffect(portraitTypes[0]); } catch (error) { - console.error('Failed to set the portrait effects value. errorCode = ' + error.code); + console.error('Failed to set the portrait effects value. errorCode = ' + error.code); } // 获取已经设置的虚化类型 -let effect +let effect: camera.PortraitEffect; try { - effect = portraitSession.getPortraitEffect() + effect = portraitSession.getPortraitEffect(); } catch (error) { - console.error('Failed to get the portrait effects value. errorCode = ' + error.code); + console.error('Failed to get the portrait effects value. errorCode = ' + error.code); } // 使用当前拍照设置进行拍照 -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.'); }); // 停止当前会话 -portraitSession.stop() +portraitSession.stop(); // 释放相机输入流 -cameraInput.close() +cameraInput.close(); // 释放预览输出流 -previewOutput.release() +previewOutput.release(); // 释放拍照输出流 -photoOutput.release() +photoOutput.release(); // 释放会话 -portraitSession.release() +portraitSession.release(); // 会话置空 -portraitSession = null +portraitSession = null; ``` diff --git a/zh-cn/application-dev/media/camera-performance-improvement.md b/zh-cn/application-dev/media/camera-performance-improvement.md index dd8310024d9e350713d06aae072732083456c152..ccf0fa46bba91b31381c62e2dad8e708cd391d09 100644 --- a/zh-cn/application-dev/media/camera-performance-improvement.md +++ b/zh-cn/application-dev/media/camera-performance-improvement.md @@ -36,10 +36,10 @@ import camera from '@ohos.multimedia.camera'; function async preview(context: Context, cameraInfo: camera.Device, 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 = await 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(); + const session: camera.CaptureSession = await mCameraManager.createCaptureSession(); await session.beginConfig(); await session.addInput(cameraInput); await session.addOutput(previewOutput); @@ -80,32 +80,32 @@ function async preview(context: Context, cameraInfo: camera.Device, previewProfi ![](figures/quick-thumbnail-sequence-diagram.png) ```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); // [各类Context的获取方式](../application-models/application-context-stage.md) +let cameraManager: camera.CameraManager = camera.getCameraManager(context); +let cameras: Array = cameraManager.getSupportedCameras(); // 创建CaptureSession实例 -this.captureSession = await this.cameraManager.createCaptureSession() +let captureSession: camera.CaptureSession = await cameraManager.createCaptureSession(); // 开始配置会话 -await this.captureSession.beginConfig() +await 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 = await cameraManager.createCameraInput(cameras[0]); +await cameraInput.open(); +await 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 = await cameraManager.createPhotoOutput(photoProfile, surfaceId); +await 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); }) } ``` @@ -138,13 +138,13 @@ if (isSupported) { - **桌面应用** ```js - import camera from '@ohos.multimedia.camera' + import camera from '@ohos.multimedia.camera'; - this.cameraManager = camera.getCameraManager(globalThis.abilityContext); + let cameraManager: camera.CameraManager = camera.getCameraManager(globalThis.abilityContext); try { - this.cameraManager.prelaunch(); + cameraManager.prelaunch(); } catch (error) { - console.error(`catch error: Code: ${error.code}, message: ${error.message}`) + console.error(`catch error: Code: ${error.code}, message: ${error.message}`); } ``` @@ -155,15 +155,15 @@ if (isSupported) { 具体申请方式及校验方式,请参考[访问控制授权申请指导](../security/accesstoken-guidelines.md)。 ```js - import camera from '@ohos.multimedia.camera' + import camera from '@ohos.multimedia.camera'; - this.cameraManager = camera.getCameraManager(globalThis.abilityContext); - let cameras = this.cameraManager.getSupportedCameras() - if(this.cameraManager.isPrelaunchSupported(cameras[0])) { + cameraManager: camera.CameraManager = camera.getCameraManager(globalThis.abilityContext); + 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}`) + console.error(`catch error: Code: ${error.code}, message: ${error.message}`); } } ``` diff --git a/zh-cn/application-dev/media/camera-preview.md b/zh-cn/application-dev/media/camera-preview.md index 552ba4162d51f9ea53e74e1d7d6892b90051ade8..0711cf2ac2b660fa98c71e420624755ae69b2512 100644 --- a/zh-cn/application-dev/media/camera-preview.md +++ b/zh-cn/application-dev/media/camera-preview.md @@ -16,37 +16,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); + previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); } catch (error) { - console.error("Failed to create the PreviewOutput instance." + error); + console.error("Failed to create the PreviewOutput instance." + error); } ``` @@ -54,9 +53,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); }); ``` @@ -69,22 +68,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..ae37b4db5df4f2f69272eb217b497ee410e2469c 100644 --- a/zh-cn/application-dev/media/camera-recording-case.md +++ b/zh-cn/application-dev/media/camera-recording-case.md @@ -10,238 +10,238 @@ ## 完整示例 ```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); // [各类Context的获取方式](../application-models/application-context-stage.md) +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 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 -} + 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}`); - } + 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: media.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); + console.error('Failed to beginConfig. errorCode = ' + error.code); } // 获取相机列表 -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; } // 创建相机输入流 -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 4722aab102d018bb6d8de03de5917df5a656b794..ecce6b50e34a4a1cf6396ffdbd424068a3b76e1c 100644 --- a/zh-cn/application-dev/media/camera-recording.md +++ b/zh-cn/application-dev/media/camera-recording.md @@ -17,30 +17,30 @@ 系统提供的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可参考下一章节 - AVRecorder.prepare(AVRecorderConfig, (err) => { - if (err == null) { - console.log('prepare success'); - } else { - console.log('prepare failed and error is ' + err.message); - } - }) + avRecorder.prepare(AVRecorderConfig: media.AVRecorderConfig, (err: BusinessError) => { + 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; + let videoSurfaceId: string = null; + avRecorder.getInputSurface().then((surfaceId: string) => { + console.info('getInputSurface success'); + videoSurfaceId = surfaceId; }).catch((err) => { - console.info('getInputSurface failed and catch error is ' + err.message); + console.info('getInputSurface failed and catch error is ' + err.message); }); ``` @@ -51,43 +51,43 @@ **注**:预览流与录像输出流的分辨率的宽高比要保持一致,如示例代码中宽高比为640:480 = 4:3,则需要预览流中的分辨率的宽高比也为4:3,如分辨率选择640:480,或960:720,或1440:1080,以此类推 ```ts - let videoProfilesArray = cameraOutputCapability.videoProfiles; + let videoProfilesArray: Array = cameraOutputCapability.videoProfiles; if (!videoProfilesArray) { - console.error("createOutput videoProfilesArray == null || undefined"); + console.error("createOutput videoProfilesArray == null || undefined"); } // 创建视频录制的参数,预览流与录像输出流的分辨率的宽(videoFrameWidth)高(videoFrameHeight)比要保持一致 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); + console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); } ``` @@ -95,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'); }); ``` @@ -115,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.'); }); ``` @@ -136,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..1bddd3c805b880a9dc7ad56194b2c8739d955ab2 100644 --- a/zh-cn/application-dev/media/camera-session-management.md +++ b/zh-cn/application-dev/media/camera-session-management.md @@ -18,11 +18,11 @@ 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); + console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); } ``` @@ -30,9 +30,9 @@ ```ts try { - captureSession.beginConfig(); + captureSession.beginConfig(); } catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); + console.error('Failed to beginConfig. errorCode = ' + error.code); } ``` @@ -42,24 +42,24 @@ ```ts 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); } 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(photoOutput); + captureSession.addOutput(photoOutput); } catch (error) { - console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); + console.error('Failed to addOutput(photoOutput). errorCode = ' + error.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 +67,20 @@ ```ts await captureSession.stop(); try { - captureSession.beginConfig(); + captureSession.beginConfig(); } catch (error) { - console.error('Failed to beginConfig. errorCode = ' + error.code); + console.error('Failed to beginConfig. errorCode = ' + error.code); } // 从会话中移除拍照输出流 try { - captureSession.removeOutput(photoOutput); + captureSession.removeOutput(photoOutput); } catch (error) { - console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code); + console.error('Failed to removeOutput(photoOutput). 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); } ``` diff --git a/zh-cn/application-dev/media/camera-shooting-case.md b/zh-cn/application-dev/media/camera-shooting-case.md index c8f307cc352937643b72e9942730bae8db0c5a87..103921ac5fcd68f56c64d41f7b06046445dfa975 100644 --- a/zh-cn/application-dev/media/camera-shooting-case.md +++ b/zh-cn/application-dev/media/camera-shooting-case.md @@ -9,232 +9,232 @@ ## 完整示例 ```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); // [各类Context的获取方式](../application-models/application-context-stage.md) +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); + console.error('Failed to createCameraInput errorCode = ' + error.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.") + console.error("Failed to create the PreviewOutput instance."); } // 监听预览输出错误信息 -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 = await 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); + console.error('Failed to createPhotoOutput errorCode = ' + 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.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); + console.error('Failed to beginConfig. errorCode = ' + error.code); } // 向会话中添加相机输入流 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); } // 向会话中添加预览输出流 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(photoOutput) + captureSession.addOutput(photoOutput); } catch (error) { - console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); + console.error('Failed to addOutput(photoOutput). errorCode = ' + error.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); + console.error('Failed to hasFlash. errorCode = ' + error.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) { + console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.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); - } + console.error('Failed to set the flash mode. errorCode = ' + error.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); + console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.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) { + console.error('Failed to set the focus mode. errorCode = ' + error.code); + } } // 获取相机支持的可变焦距比范围 -let zoomRatioRange +let zoomRatioRange; try { - zoomRatioRange = captureSession.getZoomRatioRange() + zoomRatioRange: Array = captureSession.getZoomRatioRange(); } catch (error) { - console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); + console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); } // 设置可变焦距比 try { - captureSession.setZoomRatio(zoomRatioRange[0]) + captureSession.setZoomRatio(zoomRatioRange[0]); } catch (error) { - console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); + console.error('Failed to set the zoom ratio value. errorCode = ' + error.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..c63a4389db81f4a7e5f077dd59e41146ffaab799 100644 --- a/zh-cn/application-dev/media/camera-shooting.md +++ b/zh-cn/application-dev/media/camera-shooting.md @@ -18,15 +18,15 @@ ```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'); - } + 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 = receiver.getReceivingSurfaceId(); + console.info('ImageReceived id: ' + JSON.stringify(photoSurfaceId)); + } else { + console.info('ImageReceiver is not ok'); + } } ``` @@ -35,15 +35,15 @@ 通过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); + console.error('Failed to createPhotoOutput errorCode = ' + error.code); } ``` @@ -53,59 +53,59 @@ ```ts // 判断设备是否支持闪光灯 - let flashStatus; + let flashStatus: boolean; try { - flashStatus = captureSession.hasFlash(); + flashStatus = captureSession.hasFlash(); } catch (error) { - console.error('Failed to hasFlash. errorCode = ' + error.code); + console.error('Failed to hasFlash. errorCode = ' + error.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) { + console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.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); - } + console.error('Failed to set the flash mode. errorCode = ' + error.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); + console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.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) { + console.error('Failed to set the focus mode. errorCode = ' + error.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); + console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); } // 设置可变焦距比 try { - captureSession.setZoomRatio(zoomRatioRange[0]); + captureSession.setZoomRatio(zoomRatioRange[0]); } catch (error) { - console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); + console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); } ``` @@ -114,18 +114,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 +136,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/quick-start/arkts-page-custom-components-lifecycle.md b/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md index 4a2397a02a144d9965c9d6c1e452311412cd97c0..295da4cdec2847c751a0b9b469358b5ba55938ca 100644 --- a/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md +++ b/zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @@ -178,7 +178,7 @@ struct Child { - 点击“push to next page”,调用router.pushUrl接口,跳转到另外一个页面,当前Index页面隐藏,执行页面生命周期Index onPageHide。此处调用的是router.pushUrl接口,Index页面被隐藏,并没有销毁,所以只调用onPageHide。跳转到新页面后,执行初始化新页面的生命周期的流程。 -- 如果调用的是router.replaceUrl,则当前Index页面被销毁,执行的生命周期流程将变为:Index onPageHide --> MyComponent aboutToDisappear --> Child aboutToDisappear。上文已经提到,组件的销毁是从组件树上直接摘下子树,所以先调用父组件的aboutToDisappear,再调用子组件的aboutToDisAppear,然后执行初始化新页面的生命周期流程。 +- 如果调用的是router.replaceUrl,则当前Index页面被销毁,执行的生命周期流程将变为:Index onPageHide --> MyComponent aboutToDisappear --> Child aboutToDisappear。上文已经提到,组件的销毁是从组件树上直接摘下子树,所以先调用父组件的aboutToDisappear,再调用子组件的aboutToDisappear,然后执行初始化新页面的生命周期流程。 - 点击返回按钮,触发页面生命周期Index onBackPress,且触发返回一个页面后会导致当前Index页面被销毁。 diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 70d7057a1c254affec1f20df026656c185756e66..175fae498866130149583b19cad163edaf0529c5 100644 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -8,12 +8,14 @@ - [@ohos.app.ability.AbilityConstant (AbilityConstant)](js-apis-app-ability-abilityConstant.md) - [@ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback)](js-apis-app-ability-abilityLifecycleCallback.md) - [@ohos.app.ability.AbilityStage (AbilityStage)](js-apis-app-ability-abilityStage.md) + - [@ohos.app.ability.ActionExtensionAbility (自定义服务扩展能力)](js-apis-app-ability-actionExtensionAbility.md) - [@ohos.app.ability.ApplicationStateChangeCallback (ApplicationStateChangeCallback)](js-apis-app-ability-applicationStateChangeCallback.md) - [@ohos.app.ability.common (应用上下文Context)](js-apis-app-ability-common.md) - [@ohos.app.ability.contextConstant (ContextConstant)](js-apis-app-ability-contextConstant.md) - [@ohos.app.ability.EnvironmentCallback (EnvironmentCallback)](js-apis-app-ability-environmentCallback.md) - [@ohos.app.ability.ExtensionAbility (扩展能力基类)](js-apis-app-ability-extensionAbility.md) - [@ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility)](js-apis-app-ability-serviceExtensionAbility.md) + - [@ohos.app.ability.ShareExtensionAbility (分享模板服务扩展能力)](js-apis-app-ability-shareExtensionAbility.md) - [@ohos.app.ability.StartOptions (StartOptions)](js-apis-app-ability-startOptions.md) - [@ohos.app.ability.UIAbility (UIAbility)](js-apis-app-ability-uiAbility.md) - [@ohos.app.ability.UIExtensionAbility (带界面扩展能力基类)](js-apis-app-ability-uiExtensionAbility.md) @@ -206,7 +208,7 @@ - [@ohos.arkui.dragController (DragController)](js-apis-arkui-dragController.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.inspector (布局回调)](js-apis-arkui-inspector.md) - - [ @ohos.arkui.performanceMonitor (性能监测)](js-apis-arkui-performancemonitor.md) + - [@ohos.arkui.performanceMonitor (性能监测)](js-apis-arkui-performancemonitor.md) - [@ohos.arkui.UIContext (UIContext)](js-apis-arkui-UIContext.md) - [@ohos.curves (插值计算)](js-apis-curve.md) - [@ohos.font (注册自定义字体)](js-apis-font.md) @@ -280,7 +282,8 @@ - [@ohos.data.distributedKVStore (分布式键值数据库)](js-apis-distributedKVStore.md) - [@ohos.data.preferences (用户首选项)](js-apis-data-preferences.md) - [@ohos.data.relationalStore (关系型数据库)](js-apis-data-relationalStore.md) - - [@ohos.data.UDMF (统一数据管理框架)](js-apis-data-udmf.md) + - [@ohos.data.unifiedDataChannel (标准化数据通路)](js-apis-data-unifiedDataChannel.md) + - [@ohos.data.uniformTypeDescriptor (标准化数据定义与描述)](js-apis-data-uniformTypeDescriptor.md) - [@ohos.data.ValuesBucket (数据集)](js-apis-data-valuesBucket.md) - 文件管理 diff --git a/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index b7fff65f534301b064789b4e85e2a6dff604e38d..337f7f8bfb347f73f6def59e57323a61507665e0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -11,7 +11,8 @@ ## 导入模块 ```ts -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' +import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; +import workScheduler from '@ohos.resourceschedule.workScheduler'; ``` ## 属性 @@ -40,7 +41,7 @@ onWorkStart(work: workScheduler.WorkInfo): void ```ts export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { + onWorkStart(workInfo: workScheduler.WorkInfo) { console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); } } @@ -65,7 +66,7 @@ onWorkStop(work: workScheduler.WorkInfo): void ```ts export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStop(workInfo) { + onWorkStop(workInfo: workScheduler.WorkInfo) { console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); } } 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..78726882de928a2b1d00ede2b2eae923851c87a4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -430,6 +430,10 @@ on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionLi 订阅指定tokenId列表与权限列表的权限状态变更事件。 +允许指定tokenId列表与权限列表订阅多个callback。 + +不允许存在交集的tokenId列表与权限列表订阅相同callback。 + **系统接口:** 此接口为系统接口。 **需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS,仅系统应用可用。 @@ -482,6 +486,8 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionL 取消订阅指定tokenId列表与权限列表的权限状态变更事件,使用callback回调异步返回结果。 +取消订阅不传callback时,批量删除tokenIDList和permissionList下面的所有callback。 + **系统接口:** 此接口为系统接口。 **需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS,仅系统应用可用。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md index c447a0fa845477e443aed5651d3a54dc8422011a..8af52f018b44ff4242650ef74082bf9976f9af2b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -44,5 +44,7 @@ constructor(durationTime: number); **示例:** ```ts +import GesturePath from '@ohos.accessibility.GesturePath'; + let gesturePath = new GesturePath.GesturePath(20); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md index ceafa7ceb09a73285b91e751bb8f1353f0e9c8c5..0c4bf4e52f488045aa6bf7e7cce47269a1b2736d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -45,5 +45,7 @@ constructor(positionX: number, positionY: number); **示例:** ```ts +import GesturePoint from '@ohos.accessibility.GesturePoint'; + let gesturePoint = new GesturePoint.GesturePoint(1, 2); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md index 2b196175c3675f0b5c6191e247ac480e925dd607..20649e2a0c61b395b6205a256f82ee8a33cb2a1c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md @@ -68,12 +68,14 @@ enableAbility(name: string, capability: Array<accessibility.Capability>): ```ts import accessibility from '@ohos.accessibility'; -let name = 'com.ohos.example/axExtension'; +import config from '@ohos.accessibility.config'; + +let name: string = 'com.ohos.example/axExtension'; let capability : accessibility.Capability[] = ['retrieve']; try { config.enableAbility(name, capability).then(() => { console.info('enable ability succeed'); - }).catch((err) => { + }).catch((err: object) => { console.error('failed to enable ability, because ' + JSON.stringify(err)); }); } catch (exception) { @@ -110,10 +112,13 @@ enableAbility(name: string, capability: Array<accessibility.Capability>, c ```ts import accessibility from '@ohos.accessibility'; -let name = 'com.ohos.example/axExtension'; -let capability : accessibility.Capability[] = ['retrieve']; +import config from '@ohos.accessibility.config'; +import { BusinessError } from '@ohos.base'; + +let name: string = 'com.ohos.example/axExtension'; +let capability: accessibility.Capability[] = ['retrieve']; try { - config.enableAbility(name, capability, (err) => { + config.enableAbility(name, capability, (err: BusinessError) => { if (err) { console.error('failed to enable ability, because ' + JSON.stringify(err)); return; @@ -156,11 +161,14 @@ disableAbility(name: string): Promise<void>; **示例:** ```ts -let name = 'com.ohos.example/axExtension'; +import accessibility from '@ohos.accessibility'; +import config from '@ohos.accessibility.config'; + +let name: string = 'com.ohos.example/axExtension'; try { config.disableAbility(name).then(() => { console.info('disable ability succeed'); - }).catch((err) => { + }).catch((err: object) => { console.error('failed to disable ability, because ' + JSON.stringify(err)); }); } catch (exception) { @@ -194,9 +202,13 @@ disableAbility(name: string, callback: AsyncCallback<void>): void; **示例:** ```ts -let name = 'com.ohos.example/axExtension'; +import accessibility from '@ohos.accessibility'; +import config from '@ohos.accessibility.config'; +import { BusinessError } from '@ohos.base'; + +let name: string = 'com.ohos.example/axExtension'; try { - config.disableAbility(name, (err, data) => { + config.disableAbility(name, (err: BusinessError) => { if (err) { console.error('failed to enable ability, because ' + JSON.stringify(err)); return; @@ -226,6 +238,8 @@ on(type: 'enabledAccessibilityExtensionListChange', callback: Callback<void&g **示例:** ```ts +import config from '@ohos.accessibility.config'; + try { config.on('enabledAccessibilityExtensionListChange', () => { console.info('subscribe enabled accessibility extension list change state success'); @@ -254,6 +268,8 @@ off(type: 'enabledAccessibilityExtensionListChange', callback?: Callback<void **示例:** ```ts +import config from '@ohos.accessibility.config'; + try { config.off('enabledAccessibilityExtensionListChange', () => { console.info('Unsubscribe enabled accessibility extension list change state success'); @@ -291,11 +307,13 @@ set(value: T): Promise<void>; **示例:** ```ts -let value = true; +import config from '@ohos.accessibility.config'; + +let value: boolean = true; try { config.highContrastText.set(value).then(() => { console.info('set highContrastText succeed'); - }).catch((err) => { + }).catch((err: object) => { console.error('failed to set highContrastText, because ' + JSON.stringify(err)); }); } catch (exception) { @@ -321,9 +339,12 @@ set(value: T, callback: AsyncCallback<void>): void; **示例:** ```ts -let value = true; +import config from '@ohos.accessibility.config'; +import { BusinessError } from '@ohos.base'; + +let value: boolean = true; try { - config.highContrastText.set(value, (err, data) => { + config.highContrastText.set(value, (err: BusinessError) => { if (err) { console.error('failed to set highContrastText, because ' + JSON.stringify(err)); return; @@ -352,11 +373,14 @@ get(): Promise<T>; **示例:** ```ts -let value; -config.highContrastText.get().then((data) => { +import config from '@ohos.accessibility.config'; +import { BusinessError } from '@ohos.base'; + +let value: boolean; +config.highContrastText.get().then((data: boolean) => { value = data; console.info('get highContrastText success'); -}).catch((err) => { +}).catch((err: object) => { console.error('failed to get highContrastText, because ' + JSON.stringify(err)); }); ``` @@ -378,8 +402,11 @@ get(callback: AsyncCallback<T>): void; **示例:** ```ts -let value; -config.highContrastText.get((err, data) => { +import config from '@ohos.accessibility.config'; +import { BusinessError } from '@ohos.base'; + +let value: boolean; +config.highContrastText.get((err: BusinessError, data: boolean) => { if (err) { console.error('failed to get highContrastText, because ' + JSON.stringify(err)); return; @@ -406,8 +433,10 @@ on(callback: Callback<T>): void; **示例:** ```ts +import config from '@ohos.accessibility.config'; + try { - config.highContrastText.on((data) => { + config.highContrastText.on((data: boolean) => { console.info('subscribe highContrastText success, result: ' + JSON.stringify(data)); }); } catch (exception) { @@ -432,7 +461,9 @@ off(callback?: Callback<T>): void; **示例:** ```ts -config.highContrastText.off((data) => { +import config from '@ohos.accessibility.config'; + +config.highContrastText.off((data: boolean) => { console.info('Unsubscribe highContrastText success, result: ' + JSON.stringify(data)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md index ad762b7c34524c460aea7342f4b11d533fb4317e..12665fee0edbd6fa00dfeafb7d47a3fb7d8fc01f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md @@ -174,9 +174,11 @@ on(type: 'enableChange', callback: Callback<boolean>): void; **示例:** ```ts +import accessibility from '@ohos.accessibility'; + let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.on('enableChange', (data) => { + captionsManager.on('enableChange', (data: boolean) => { console.info('subscribe caption manager enable state change, result: ' + JSON.stringify(data)); }); } catch (exception) { @@ -202,10 +204,12 @@ on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; **示例:** ```ts -let captionStyle; +import accessibility from '@ohos.accessibility'; + +let captionStyle: accessibility.CaptionsStyle; let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.on('styleChange', (data) => { + captionsManager.on('styleChange', (data: accessibility.CaptionsStyle) => { captionStyle = data; console.info('subscribe caption manager style state change, result: ' + JSON.stringify(data)); }); @@ -232,9 +236,11 @@ off(type: 'enableChange', callback?: Callback<boolean>): void; **示例:** ```ts +import accessibility from '@ohos.accessibility'; + let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.off('enableChange', (data) => { + captionsManager.off('enableChange', (data: boolean) => { console.info('Unsubscribe caption manager enable state change, result: ' + JSON.stringify(data)); }); } catch (exception) { @@ -260,10 +266,12 @@ off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; **示例:** ```ts -let captionStyle; +import accessibility from '@ohos.accessibility'; + +let captionStyle: accessibility.CaptionsStyle; let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.off('styleChange', (data) => { + captionsManager.off('styleChange', (data: accessibility.CaptionsStyle) => { captionStyle = data; console.info('Unsubscribe caption manager style state change, result: ' + JSON.stringify(data)); }); @@ -314,10 +322,12 @@ constructor(jsonObject) **示例:** ```ts - let eventInfo = new accessibility.EventInfo({ - 'type':'click', - 'bundleName':'com.example.MyApplication', - 'triggerAction':'click' + import accessibility from '@ohos.accessibility'; + + let eventInfo: accessibility.EventInfo = ({ + type: 'click', + bundleName: 'com.example.MyApplication', + triggerAction: 'click' }); ``` @@ -398,24 +408,28 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<A **示例:** ```ts -let abilityType = 'spoken'; -let abilityState = 'enable'; -let abilityList: accessibility.AccessibilityInfo[]; +import accessibility from '@ohos.accessibility'; + +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let abilityList: accessibility.AccessibilityAbilityInfo[]; try { - accessibility.getAbilityLists(abilityType, abilityState).then((data) => { - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.bundleName); - extensionList.push(item); - } - console.info('get accessibility extension list success'); - }).catch((err) => { - console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + accessibility.getAbilityLists(abilityType, abilityState) + .then((data: accessibility.AccessibilityAbilityInfo[]) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + abilityList.push(item); + } + console.info('get accessibility extension list success'); + }) + .catch((err: object) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); }); } catch (exception) { - console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); } ``` @@ -443,11 +457,15 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: Asyn **示例:** ```ts -let abilityType = 'spoken'; -let abilityState = 'enable'; +import accessibility from '@ohos.accessibility'; +import { BusinessError } from '@ohos.base'; + +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; let abilityList: accessibility.AccessibilityInfo[]; try { - accessibility.getAbilityLists(abilityType, abilityState, (err, data) => { + accessibility.getAbilityLists(abilityType, abilityState, + (err: BusinessError, data: accessibility.AccessibilityAbilityInfo[]) => { if (err) { console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); return; @@ -460,9 +478,7 @@ try { abilityList.push(item); } console.info('get accessibility extension list success'); - }).catch((err) => { - console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); - }); + }) } catch (exception) { console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); } @@ -492,11 +508,14 @@ getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState) **示例:** ```ts +import accessibility from '@ohos.accessibility'; + let abilityType : accessibility.AbilityType = 'spoken'; let abilityState : accessibility.AbilityState = 'enable'; let extensionList: accessibility.AccessibilityAbilityInfo[] = []; try { - accessibility.getAccessibilityExtensionList(abilityType, abilityState).then((data) => { + accessibility.getAccessibilityExtensionList(abilityType, abilityState) + .then((data: accessibility.AccessibilityAbilityInfo[]) => { for (let item of data) { console.info(item.id); console.info(item.name); @@ -505,7 +524,8 @@ try { extensionList.push(item); } console.info('get accessibility extension list success'); - }).catch((err) => { + }) + .catch((err: object) => { console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); }); } catch (exception) { @@ -532,11 +552,15 @@ getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState, **示例:** ```ts +import accessibility from '@ohos.accessibility'; +import { BusinessError } from '@ohos.base'; + let abilityType : accessibility.AbilityType = 'spoken'; let abilityState : accessibility.AbilityState = 'enable'; let extensionList: accessibility.AccessibilityAbilityInfo[] = []; try { - accessibility.getAccessibilityExtensionList(abilityType, abilityState, (err, data) => { + accessibility.getAccessibilityExtensionList(abilityType, abilityState, + (err: BusinessError, data: accessibility.AccessibilityAbilityInfo[]) => { if (err) { console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); return; @@ -572,6 +596,8 @@ getCaptionsManager(): CaptionsManager **示例:** ```ts +import accessibility from '@ohos.accessibility'; + let captionsManager = accessibility.getCaptionsManager(); ``` @@ -593,8 +619,10 @@ on(type: 'accessibilityStateChange', callback: Callback<boolean>): void **示例:** ```ts +import accessibility from '@ohos.accessibility'; + try { - accessibility.on('accessibilityStateChange', (data) => { + accessibility.on('accessibilityStateChange', (data: boolean) => { console.info('subscribe accessibility state change, result: ' + JSON.stringify(data)); }); } catch (exception) { @@ -620,8 +648,10 @@ on(type: 'touchGuideStateChange', callback: Callback<boolean>): void **示例:** ```ts +import accessibility from '@ohos.accessibility'; + try { - accessibility.on('touchGuideStateChange', (data) => { + accessibility.on('touchGuideStateChange', (data: boolean) => { console.info('subscribe touch guide state change, result: ' + JSON.stringify(data)); }); } catch (exception) { @@ -647,8 +677,10 @@ off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void **示例:** ```ts +import accessibility from '@ohos.accessibility'; + try { - accessibility.off('accessibilityStateChange', (data) => { + accessibility.off('accessibilityStateChange', (data: boolean) => { console.info('Unsubscribe accessibility state change, result: ' + JSON.stringify(data)); }); } catch (exception) { @@ -674,8 +706,10 @@ off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void **示例:** ```ts +import accessibility from '@ohos.accessibility'; + try { - accessibility.off('touchGuideStateChange', (data) => { + accessibility.off('touchGuideStateChange', (data: boolean) => { console.info('Unsubscribe touch guide state change, result: ' + JSON.stringify(data)); }); } catch (exception) { @@ -700,9 +734,11 @@ isOpenAccessibility(): Promise<boolean> **示例:** ```ts -accessibility.isOpenAccessibility().then((data) => { +import accessibility from '@ohos.accessibility'; + +accessibility.isOpenAccessibility().then((data: boolean) => { console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) -}).catch((err) => { +}).catch((err: object) => { console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); }); ``` @@ -724,7 +760,10 @@ isOpenAccessibility(callback: AsyncCallback<boolean>): void **示例:** ```ts -accessibility.isOpenAccessibility((err, data) => { +import accessibility from '@ohos.accessibility'; +import { BusinessError } from '@ohos.base'; + +accessibility.isOpenAccessibility((err: BusinessError, data: boolean) => { if (err) { console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); return; @@ -750,9 +789,11 @@ isOpenTouchGuide(): Promise<boolean> **示例:** ```ts -accessibility.isOpenTouchGuide().then((data) => { +import accessibility from '@ohos.accessibility'; + +accessibility.isOpenTouchGuide().then((data: boolean) => { console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) -}).catch((err) => { +}).catch((err: object) => { console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); }); ``` @@ -774,7 +815,10 @@ isOpenTouchGuide(callback: AsyncCallback<boolean>): void **示例:** ```ts -accessibility.isOpenTouchGuide((err, data) => { +import accessibility from '@ohos.accessibility'; +import { BusinessError } from '@ohos.base'; + +accessibility.isOpenTouchGuide((err: BusinessError, data: boolean) => { if (err) { console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); return; @@ -811,14 +855,16 @@ sendEvent(event: EventInfo): Promise<void> **示例:** ```ts -let eventInfo = new accessibility.EventInfo({ - 'type':'click', - 'bundleName':'com.example.MyApplication', - 'triggerAction':'click' +import accessibility from '@ohos.accessibility'; + +let eventInfo: accessibility.EventInfo = ({ + type: 'click', + bundleName: 'com.example.MyApplication', + triggerAction: 'click' }); accessibility.sendEvent(eventInfo).then(() => { console.info('send event success'); -}).catch((err) => { +}).catch((err: object) => { console.error('failed to sendEvent because ' + JSON.stringify(err)); }); ``` @@ -846,12 +892,15 @@ sendEvent(event: EventInfo, callback: AsyncCallback<void>): void **示例:** ```ts -let eventInfo = new accessibility.EventInfo({ - 'type':'click', - 'bundleName':'com.example.MyApplication', - 'triggerAction':'click' +import accessibility from '@ohos.accessibility'; +import { BusinessError } from '@ohos.base'; + +let eventInfo: accessibility.EventInfo = ({ + type: 'click', + bundleName: 'com.example.MyApplication', + triggerAction: 'click' }); -accessibility.sendEvent(eventInfo, (err, data) => { +accessibility.sendEvent(eventInfo, (err: BusinessError) => { if (err) { console.error('failed to sendEvent because ' + JSON.stringify(err)); return; @@ -883,15 +932,17 @@ sendAccessibilityEvent(event: EventInfo): Promise<void> **示例:** ```ts -let eventInfo = new accessibility.EventInfo({ - 'type':'click', - 'bundleName':'com.example.MyApplication', - 'triggerAction':'click' +import accessibility from '@ohos.accessibility'; + +let eventInfo: accessibility.EventInfo = ({ + type: 'click', + bundleName: 'com.example.MyApplication', + triggerAction: 'click' }); try { accessibility.sendAccessibilityEvent(eventInfo).then(() => { console.info('send event success'); - }).catch((err) => { + }).catch((err: object) => { console.error('failed to send event because ' + JSON.stringify(err)); }); } catch (exception) { @@ -917,13 +968,16 @@ sendAccessibilityEvent(event: EventInfo, callback: AsyncCallback<void>): v **示例:** ```ts -let eventInfo = new accessibility.EventInfo({ - 'type':'click', - 'bundleName':'com.example.MyApplication', - 'triggerAction':'click' +import accessibility from '@ohos.accessibility'; +import { BusinessError } from '@ohos.base'; + +let eventInfo: accessibility.EventInfo = ({ + type: 'click', + bundleName: 'com.example.MyApplication', + triggerAction: 'click' }); try { - accessibility.sendEvent(eventInfo, (err, data) => { + accessibility.sendEvent(eventInfo, (err: BusinessError) => { if (err) { console.error('failed to send event because ' + JSON.stringify(err)); return; diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md index 64e8a9c391835497fb41c8850bc0ac0d3ab0849d..bc083f54cecdcdbf13cb790b4d0aaa6a8dde0d8a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -389,12 +389,16 @@ appManager.isSharedBundleRunning(bundleName, versionCode, (err, data) => { }); ``` -## appManager.on +## appManager.on(type: 'applicationState', observer: ApplicationStateObserver)(deprecated) on(type: 'applicationState', observer: ApplicationStateObserver): number; 注册全部应用程序的状态观测器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[appManager.on(type: 'applicationStateEvent', observer: ApplicationStateObserver)](#appmanagerontype-applicationstateevent-observer-applicationstateobserver10)。 + **需要权限**:ohos.permission.RUNNING_STATE_OBSERVER **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -452,12 +456,16 @@ try { } ``` -## appManager.on +## appManager.on(type: 'applicationState', observer: ApplicationStateObserver, bundleNameList: Array\)(deprecated) on(type: 'applicationState', observer: ApplicationStateObserver, bundleNameList: Array\): number; 注册指定应用程序的状态观测器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[appManager.on(type: 'applicationStateEvent', observer: ApplicationStateObserver, bundleNameList: Array\)](#appmanagerontype-applicationstateevent-observer-applicationstateobserver-bundlenamelist-arraystring10)。 + **需要权限**:ohos.permission.RUNNING_STATE_OBSERVER **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -517,12 +525,16 @@ try { } ``` -## appManager.off +## appManager.off(type: 'applicationState', observerId: number, callback: AsyncCallback\)(deprecated) off(type: 'applicationState', observerId: number, callback: AsyncCallback\): void; 取消注册应用程序状态观测器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[appManager.off(type: 'applicationStateEvent', observerId: number)](#appmanagerofftype-applicationstateevent-observerid-number10)。 + **需要权限**:ohos.permission.RUNNING_STATE_OBSERVER **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -593,12 +605,16 @@ try { } ``` -## appManager.off +## appManager.off(type: 'applicationState', observerId: number)(deprecated) off(type: 'applicationState', observerId: number): Promise\; 取消注册应用程序状态观测器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[appManager.off(type: 'applicationStateEvent', observerId: number)](#appmanagerofftype-applicationstateevent-observerid-number10)。 + **需要权限**:ohos.permission.RUNNING_STATE_OBSERVER **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -671,6 +687,203 @@ try { } ``` +## appManager.on(type: 'applicationStateEvent', observer: ApplicationStateObserver)10+ + +on(type: 'applicationStateEvent', observer: ApplicationStateObserver): number; + +注册全部应用程序的状态观测器。 + +**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**系统API**:该接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 调用接口类型,固定填'applicationStateEvent'字符串。 | +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | 是 | 应用状态观测器,用于观测应用的生命周期变化。 | + +**返回值:** + +| 类型 | 说明 | +| --- | --- | +| number | 已注册观测器的数字代码,可用于off接口取消注册观测器。| + +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + +**示例:** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + } +}; +try { + const observerId = appManager.on('applicationStateEvent', applicationStateObserver); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} +``` + +## appManager.on(type: 'applicationStateEvent', observer: ApplicationStateObserver, bundleNameList: Array\)10+ + +on(type: 'applicationStateEvent', observer: ApplicationStateObserver, bundleNameList: Array\): number; + +注册指定应用程序的状态观测器。 + +**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**系统API**:该接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 调用接口类型,固定填'applicationStateEvent'字符串。 | +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | 是 | 应用状态观测器,用于观测应用的生命周期变化。 | +| bundleNameList | `Array` | 是 | 表示需要注册监听的bundleName数组。最大值128。 | + +**返回值:** + +| 类型 | 说明 | +| --- | --- | +| number | 已注册观测器的数字代码,可用于off接口注销观测器。| + +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + +**示例:** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + } +}; +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + const observerId = appManager.on('applicationStateEvent', applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} +``` + +## appManager.off(type: 'applicationStateEvent', observerId: number)10+ + +off(type: 'applicationStateEvent', observerId: number): void; + +取消注册应用程序状态观测器。 + +**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**系统API**:该接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 调用接口类型,固定填'applicationStateEvent'字符串。 | +| observerId | number | 是 | 表示观测器的编号代码。 | +| callback | AsyncCallback\ | 是 | 以回调方式返回接口运行结果,可进行错误处理或其他自定义处理。 | + +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000050 | Internal error. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + +**示例:** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let observerId = 0; + +// 1.注册应用状态监听器 +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + } +}; +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + observerId = appManager.on('applicationStateEvent', applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} + +// 2.注销应用状态监听器 +try { + appManager.off('applicationStateEvent', observerId); +} catch (paramError) { + console.error(`error: ${paramError.code}, ${paramError.message}`); +} +``` + ## appManager.getForegroundApplications getForegroundApplications(callback: AsyncCallback\>): void; @@ -1356,3 +1569,4 @@ try { | STATE_ACTIVE | 3 | 当进程在获焦的时候处于的状态。 | | STATE_BACKGROUND | 4 | 当进程处于后台不可见时处于的状态。 | | STATE_DESTROY | 5 | 当进程在销毁的时候处于的状态。 | + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md index 640b08d8cd0ffe1a259e663a9df514bdc175a61b..ec3d1ad96f0f1c0362120a1600b1890a5d668576 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -11,12 +11,16 @@ ErrorManager模块提供对错误观察器的注册和注销的能力。使用 import errorManager from '@ohos.app.ability.errorManager'; ``` -## ErrorManager.on +## ErrorManager.on(type: 'error', observer: ErrorObserver)(deprecated) on(type: 'error', observer: ErrorObserver): number; 注册错误观测器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[ErrorManager.on(type: 'errorEvent', observer: ErrorObserver)](#errormanagerontype-errorevent-observer-errorobserver10)。 + **系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** @@ -59,16 +63,20 @@ let observerId = -1; try { observerId = errorManager.on('error', observer); } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); } ``` -## ErrorManager.off +## ErrorManager.off(type: 'error', observerId: number, callback: AsyncCallback\)(deprecated) off(type: 'error', observerId: number, callback: AsyncCallback\): void; 注销错误观测器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[ErrorManager.off(type: 'errorEvent', observerId: number)](#errormanagerofftype-errorevent-observerid-number10)。 + **系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** @@ -100,16 +108,20 @@ function unregisterErrorObserverCallback(err) { try { errorManager.off('error', observerId, unregisterErrorObserverCallback); } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); } ``` -## ErrorManager.off +## ErrorManager.off(type: 'error', observerId: number)(deprecated) off(type: 'error', observerId: number): Promise\; 注销错误观测器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[ErrorManager.off(type: 'errorEvent', observerId: number)](#errormanagerofftype-errorevent-observerid-number10)。 + **系统能力**:SystemCapability.Ability.AbilityRuntime.Core **参数:** @@ -146,7 +158,96 @@ try { console.error('----------- unregisterErrorObserver fail ----------', err); }); } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); +} + +``` + +## ErrorManager.on(type: 'errorEvent', observer: ErrorObserver)10+ + +on(type: 'errorEvent', observer: ErrorObserver): number; + +注册错误观测器。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 填写'errorEvent',表示错误观察器。 | +| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | 是 | 错误观察器。 | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | number | 观察器的index值,和观察器一一对应。 | + +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000003 | Id does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + +**示例:** + +```ts +let observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg); + }, + onException(errorObj) { + console.log('onException, name: ', errorObj.name); + console.log('onException, message: ', errorObj.message); + if (typeof(errorObj.stack) === 'string') { + console.log('onException, stack: ', errorObj.stack); + } + } +}; +let observerId = -1; +try { + observerId = errorManager.on('errorEvent', observer); +} catch (paramError) { + console.error(`error: ${paramError.code}, ${paramError.message}`); } +``` + +## ErrorManager.off(type: 'errorEvent', observerId: number)10+ + +off(type: 'errorEvent', observerId: number): void; + +注销错误观测器。 + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 填写'errorEvent',表示错误观察器。 | +| observerId | number | 是 | 由on方法返回的观察器的index值。 | +| callback | AsyncCallback\ | 是 | 表示指定的回调方法。 | + +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16000003 | Id does not exist. | +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + +**示例:** + +```ts +let observerId = 100; + +try { + errorManager.off('errorEvent', observerId); +} catch (paramError) { + console.error(`error: ${paramError.code}, ${paramError.message}`); +} ``` + \ No newline at end of file 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..8e7be84913dcb1aa398ce9d53938bfad542e2d67 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 @@ -16,12 +16,16 @@ import missionManager from '@ohos.app.ability.missionManager'; ohos.permission.MANAGE_MISSIONS -## missionManager.on +## missionManager.on(type:'mission', listener: MissionListener)(deprecated) on(type:'mission', listener: MissionListener): number; 注册系统任务状态监听器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[missionManager.on(type:'missionEvent', listener: MissionListener)](#missionmanagerontypemissionevent-listener-missionlistener10)。 + **需要权限**:ohos.permission.MANAGE_MISSIONS **系统能力**:SystemCapability.Ability.AbilityRuntime.Mission @@ -32,6 +36,7 @@ on(type:'mission', listener: MissionListener): number; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | type | string | 是 | 调用接口类型,固定填'mission'字符串。 | | listener | [MissionListener](js-apis-inner-application-missionListener.md) | 是 | 系统任务监听器。 | **返回值:** @@ -73,7 +78,7 @@ export default class EntryAbility extends UIAbility { }); } } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); } console.log('[Demo] EntryAbility onDestroy'); } @@ -84,15 +89,15 @@ export default class EntryAbility extends UIAbility { try { listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); } windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - console.error('Failed to load the content. Cause: ${JSON.stringify(err)}'); + console.error(`Failed to load the content. Cause: ${JSON.stringify(err)}`); return; } - console.info('Succeeded in loading the content. Data: ${JSON.stringify(data)}'); + console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`); }); if (globalThis.flag) { @@ -102,13 +107,16 @@ export default class EntryAbility extends UIAbility { }; ``` - -## missionManager.off +## missionManager.off(type: 'mission', listenerId: number, callback: AsyncCallback<void>)(deprecated) off(type: 'mission', listenerId: number, callback: AsyncCallback<void>): void; 解注册任务状态监听器。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[missionManager.off(type: 'missionEvent', listenerId: number)](#missionmanagerofftype-missionevent-listenerid-number10)。 + **需要权限**:ohos.permission.MANAGE_MISSIONS **系统能力**:SystemCapability.Ability.AbilityRuntime.Mission @@ -119,6 +127,7 @@ off(type: 'mission', listenerId: number, callback: AsyncCallback<void>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | type | string | 是 | 调用接口类型,固定填'mission'字符串。 | | listenerId | number | 是 | 系统任务状态监器法的index值,和监听器一一对应,由on方法返回。 | | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | @@ -163,7 +172,7 @@ export default class EntryAbility extends UIAbility { }); } } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); } console.log('[Demo] EntryAbility onDestroy'); } @@ -174,15 +183,15 @@ export default class EntryAbility extends UIAbility { try { listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); } windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - console.error('Failed to load the content. Cause: ${JSON.stringify(err)}'); + console.error(`Failed to load the content. Cause: ${JSON.stringify(err)}`); return; } - console.info('Succeeded in loading the content. Data: ${JSON.stringify(data)}'); + console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`); }); if (globalThis.flag) { @@ -192,13 +201,16 @@ export default class EntryAbility extends UIAbility { }; ``` - -## missionManager.off +## missionManager.off(type: 'mission', listenerId: number)(deprecated) off(type: 'mission', listenerId: number): Promise<void>; 解注册任务状态监听,以promise方式返回执行结果。 +> **说明:** +> +> 从 API version 9开始支持,从API version 10开始废弃,推荐使用[missionManager.off(type: 'missionEvent', listenerId: number)](#missionmanagerofftype-missionevent-listenerid-number10)。 + **需要权限**:ohos.permission.MANAGE_MISSIONS **系统能力**:SystemCapability.Ability.AbilityRuntime.Mission @@ -209,6 +221,7 @@ off(type: 'mission', listenerId: number): Promise<void>; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | type | string | 是 | 调用接口类型,固定填'mission'字符串。 | | listenerId | number | 是 | 系统任务状态监听器的index值,和监听器一一对应,由on方法返回。 | **返回值:** @@ -258,7 +271,7 @@ export default class EntryAbility extends UIAbility { }); } } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); } console.log('[Demo] EntryAbility onDestroy'); } @@ -269,15 +282,100 @@ export default class EntryAbility extends UIAbility { try { listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.error('error: ${paramError.code}, ${paramError.message}'); + console.error(`error: ${paramError.code}, ${paramError.message}`); + } + + 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)}`); + }); + + if (globalThis.flag) { + return; + } + } +}; +``` + +## missionManager.on(type:'missionEvent', listener: MissionListener)10+ + +on(type:'missionEvent', listener: MissionListener): number; + +注册系统任务状态监听器。 + +**需要权限**:ohos.permission.MANAGE_MISSIONS + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission + +**系统API**: 此接口为系统接口,三方应用不支持调用。 + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 调用接口类型,固定填'missionEvent'字符串。 | + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | 是 | 系统任务监听器。 | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | number | 监听器的index值,由系统创建,在注册系统任务状态监听时分配,和监听器一一对应 。 | + +**示例:** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} +}; + +let listenerId = -1; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('[Demo] EntryAbility onCreate'); + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId !== -1) { + missionManager.off('missionEvent', listenerId); + } + } catch (paramError) { + console.error(`error: ${paramError.code}, ${paramError.message}`); + } + console.log('[Demo] EntryAbility onDestroy'); + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log('[Demo] EntryAbility onWindowStageCreate'); + try { + listenerId = missionManager.on('missionEvent', listener); + } catch (paramError) { + console.error(`error: ${paramError.code}, ${paramError.message}`); } windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - console.error('Failed to load the content. Cause: ${JSON.stringify(err)}'); + console.error(`Failed to load the content. Cause: ${JSON.stringify(err)}`); return; } - console.info('Succeeded in loading the content. Data: ${JSON.stringify(data)}'); + console.info(`Succeeded in loading the content. Data: ${JSON.stringify(data)}`); }); if (globalThis.flag) { @@ -287,6 +385,93 @@ export default class EntryAbility extends UIAbility { }; ``` +## missionManager.off(type: 'missionEvent', listenerId: number)10+ + +off(type: 'missionEvent', listenerId: number): void; + +解注册任务状态监听器。 + +**需要权限**:ohos.permission.MANAGE_MISSIONS + +**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission + +**系统API**: 此接口为系统接口,三方应用不支持调用。 + +**参数:** + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 调用接口类型,固定填'missionEvent'字符串。 | + | listenerId | number | 是 | 系统任务状态监器法的index值,和监听器一一对应,由on方法返回。 | + | callback | AsyncCallback<void> | 是 | 执行结果回调函数。 | + +**错误码**: + +| 错误码ID | 错误信息 | +| ------- | -------- | +| 16300002 | Input error. The specified mission listener does not exist. | + +以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)。 + +**示例:** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} +}; + +let listenerId = -1; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('[Demo] EntryAbility onCreate'); + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId !== -1) { + missionManager.off('missionEvent', listenerId); + } + } catch (paramError) { + console.error(`error: ${paramError.code}, ${paramError.message}`); + } + console.log('[Demo] EntryAbility onDestroy'); + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log('[Demo] EntryAbility onWindowStageCreate'); + try { + listenerId = missionManager.on('missionEvent', listener); + } catch (paramError) { + console.error(`error: ${paramError.code}, ${paramError.message}`); + } + + 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)}`); + }); + + if (globalThis.flag) { + return; + } + } +}; +``` ## missionManager.getMissionInfo @@ -1409,4 +1594,5 @@ try { console.log("error: " + paramError.code + ", " + paramError.message); } -``` \ No newline at end of file +``` + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index aa6381e87eb13d41de8d53e19afd1663d67e0e8f..ad0f798a0faa5f2dba8cf5b81641c3c99ebf7059 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -105,9 +105,9 @@ createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallba ```js import { BusinessError } from '@ohos.base'; - let options = { + let options:account_appAccount.CreateAccountOptions = { customData: { - 'age': '10' + age: '10' } } try { @@ -158,9 +158,9 @@ createAccount(name: string, options?: CreateAccountOptions): Promise<void> ```js import { BusinessError } from '@ohos.base'; - let options = { + let options: account_appAccount.CreateAccountOptions = { customData: { - 'age': '10' + age: '10' } } try { @@ -205,20 +205,23 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void ```js import { BusinessError } from '@ohos.base'; import Want from '@ohos.app.ability.Want'; + import common from '@ohos.app.ability.common'; - function onResultCallback(code: number, result: account_appAccount.AuthResult) { + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + + function onResultCallback(code: number, result?: account_appAccount.AuthResult): void { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request: Want) { - let wantInfo = { + function onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { deviceId: '', bundleName: 'com.example.accountjsdemo', action: 'ohos.want.action.viewData', entities: ['entity.system.default'], } - this.context.startAbility(wantInfo).then(() => { + context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); @@ -267,27 +270,30 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, ```js import { BusinessError } from '@ohos.base'; import Want from '@ohos.app.ability.Want'; + import common from '@ohos.app.ability.common'; + + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, result: account_appAccount.AuthResult) { + function onResultCallback(code: number, result?: account_appAccount.AuthResult): void { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request: Want) { - let wantInfo = { + function onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { deviceId: '', bundleName: 'com.example.accountjsdemo', action: 'ohos.want.action.viewData', entities: ['entity.system.default'], } - this.context.startAbility(wantInfo).then(() => { + context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } - let options = { + let options: account_appAccount.CreateAccountImplicitlyOptions = { authType: 'getSocialData', requiredLabels: [ 'student' ] }; @@ -1328,7 +1334,7 @@ on(type: 'accountChange', owners: Array<string>, callback: Callback<Arr **示例:** ```js - function changeOnCallback(data: account_appAccount.AppAccountInfo[]){ + function changeOnCallback(data: account_appAccount.AppAccountInfo[]): void { console.log('receive change data:' + JSON.stringify(data)); } try{ @@ -1363,7 +1369,7 @@ off(type: 'accountChange', callback?: Callback<Array<AppAccountInfo>> **示例:** ```js - function changeOnCallback(data: account_appAccount.AppAccountInfo[]) { + function changeOnCallback(data: account_appAccount.AppAccountInfo[]): void { console.log('receive change data:' + JSON.stringify(data)); } try{ @@ -1412,20 +1418,23 @@ auth(name: string, owner: string, authType: string, callback: AuthCallback): voi ```js import { BusinessError } from '@ohos.base'; import Want from '@ohos.app.ability.Want'; + import common from '@ohos.app.ability.common'; + + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, authResult: account_appAccount.AuthResult) { + function onResultCallback(code: number, authResult?: account_appAccount.AuthResult): void { console.log('resultCode: ' + code); console.log('authResult: ' + JSON.stringify(authResult)); } - function onRequestRedirectedCallback(request: Want) { - let wantInfo = { + function onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { deviceId: '', bundleName: 'com.example.accountjsdemo', action: 'ohos.want.action.viewData', entities: ['entity.system.default'], } - this.context.startAbility(wantInfo).then(() => { + context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); @@ -1476,28 +1485,31 @@ auth(name: string, owner: string, authType: string, options: {[key: string]: Obj ```js import { BusinessError } from '@ohos.base'; import Want from '@ohos.app.ability.Want'; + import common from '@ohos.app.ability.common'; - function onResultCallback(code: number, authResult: account_appAccount.AuthResult) { + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + + function onResultCallback(code: number, authResult?: account_appAccount.AuthResult): void { console.log('resultCode: ' + code); console.log('authResult: ' + JSON.stringify(authResult)); } - function onRequestRedirectedCallback(request: Want) { - let wantInfo = { + function onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { deviceId: '', bundleName: 'com.example.accountjsdemo', action: 'ohos.want.action.viewData', entities: ['entity.system.default'], } - this.context.startAbility(wantInfo).then(() => { + context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); }) } - let options = { - 'password': 'xxxx', + let options: Record = { + password: 'xxxx', }; try { appAccountManager.auth('LiSi', 'com.example.accountjsdemo', 'getSocialData', options, { @@ -2187,16 +2199,16 @@ getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want: Want, param: AbilityConstant.LaunchParam) { - let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + onCreate(want: Want, param: AbilityConstant.LaunchParam) { // ability 生命周期函数 + let sessionId: string = want.parameters![account_appAccount.Constants.KEY_SESSION_ID] as string; try { appAccountManager.getAuthCallback(sessionId, (err: BusinessError, callback: account_appAccount.AuthCallback) => { if (err != null) { console.log('getAuthCallback err: ' + JSON.stringify(err)); return; } - let result = { - accountInfo: { + let result: account_appAccount.AuthResult = { + account: { name: 'Lisi', owner: 'com.example.accountjsdemo', }, @@ -2251,12 +2263,12 @@ getAuthCallback(sessionId: string): Promise<AuthCallback> import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want: Want, param: AbilityConstant.LaunchParam) { - let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + onCreate(want: Want, param: AbilityConstant.LaunchParam) { // ability 生命周期函数 + let sessionId: string = want.parameters![account_appAccount.Constants.KEY_SESSION_ID] as string; try { appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => { - let result = { - accountInfo: { + let result: account_appAccount.AuthResult = { + account: { name: 'Lisi', owner: 'com.example.accountjsdemo', }, @@ -2398,7 +2410,7 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>, cal let labels = ['student']; try { - appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels1, + appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels, (err: BusinessError, hasAllLabels: boolean) => { if (err) { console.log('checkAccountLabels failed, error: ' + JSON.stringify(err)); @@ -2580,12 +2592,12 @@ selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback& ```js import { BusinessError } from '@ohos.base'; - let options = { + let options: account_appAccount.SelectAccountsOptions = { allowedOwners: [ 'com.example.accountjsdemo' ], requiredLabels: [ 'student' ] }; try { - appAccountManager.selectAccountsByOptions(options5, + appAccountManager.selectAccountsByOptions(options, (err: BusinessError, accountArr: account_appAccount.AppAccountInfo[]) => { if (err) { console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err)); @@ -2632,7 +2644,7 @@ selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<App ```js import { BusinessError } from '@ohos.base'; - let options = { + let options: account_appAccount.SelectAccountsOptions = { allowedOwners: ['com.example.accountjsdemo'] }; try { @@ -2680,7 +2692,7 @@ verifyCredential(name: string, owner: string, callback: AuthCallback): void; try { appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', { - onResult: (resultCode: number, result: account_appAccount.AuthResult) => { + onResult: (resultCode: number, result?: account_appAccount.AuthResult) => { console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('verifyCredential onResult, result: ' + JSON.stringify(result)); }, @@ -2726,13 +2738,13 @@ verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, ```js import Want from '@ohos.app.ability.Want'; - let options = { + let options: account_appAccount.VerifyCredentialOptions = { credentialType: 'pin', credential: '123456' }; try { appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', options, { - onResult: (resultCode: number, result: account_appAccount.AuthResult) => { + onResult: (resultCode: number, result?: account_appAccount.AuthResult) => { console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('verifyCredential onResult, result: ' + JSON.stringify(result)); }, @@ -2777,7 +2789,7 @@ setAuthenticatorProperties(owner: string, callback: AuthCallback): void; try { appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', { - onResult: (resultCode: number, result: account_appAccount.AuthResult) => { + onResult: (resultCode: number, result?: account_appAccount.AuthResult) => { console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result)); }, @@ -2821,12 +2833,12 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac ```js import Want from '@ohos.app.ability.Want'; - let options = { - properties: {'prop1': 'value1'} + let options: account_appAccount.SetPropertiesOptions = { + properties: {prop1: 'value1'} }; try { appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', options, { - onResult: (resultCode: number, result: account_appAccount.AuthResult) => { + onResult: (resultCode: number, result?: account_appAccount.AuthResult) => { console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode)); console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result)); }, @@ -2961,20 +2973,23 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a ```js import { BusinessError } from '@ohos.base'; import Want from '@ohos.app.ability.Want'; + import common from '@ohos.app.ability.common'; + + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, result: { [key: string]: any }) { + function onResultCallback(code: number, result: Record): void { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request: Want) { - let wantInfo = { + function onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { deviceId: '', bundleName: 'com.example.accountjsdemo', action: 'ohos.want.action.viewData', entities: ['entity.system.default'], } - this.context.startAbility(wantInfo).then(() => { + context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); @@ -3895,7 +3910,7 @@ on(type: 'change', owners: Array<string>, callback: Callback<Array<A **示例:** ```js - function changeOnCallback(data: account_appAccount.AppAccountInfo[]){ + function changeOnCallback(data: account_appAccount.AppAccountInfo[]): void { console.debug('receive change data:' + JSON.stringify(data)); } try{ @@ -3928,7 +3943,7 @@ off(type: 'change', callback?: Callback<Array<AppAccountInfo>>): voi **示例:** ```js - function changeOnCallback(data: account_appAccount.AppAccountInfo[]){ + function changeOnCallback(data: account_appAccount.AppAccountInfo[]): void { console.debug('receive change data: ' + JSON.stringify(data)); appAccountManager.off('change', () => { console.debug('off finish'); @@ -3969,20 +3984,23 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri ```js import { BusinessError } from '@ohos.base'; import Want from '@ohos.app.ability.Want'; + import common from '@ohos.app.ability.common'; + + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext - function onResultCallback(code: number, result: { [key: string]: Object }) { + function onResultCallback(code: number, result: Record): void { console.log('resultCode: ' + code); console.log('result: ' + JSON.stringify(result)); } - function onRequestRedirectedCallback(request: Want) { - let wantInfo = { + function onRequestRedirectedCallback(request: Want): void { + let wantInfo: Want = { deviceId: '', bundleName: 'com.example.accountjsdemo', action: 'ohos.want.action.viewData', entities: ['entity.system.default'], } - this.context.startAbility(wantInfo).then(() => { + context.startAbility(wantInfo).then(() => { console.log('startAbility successfully'); }).catch((err: BusinessError) => { console.log('startAbility err: ' + JSON.stringify(err)); @@ -4517,19 +4535,20 @@ getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<Authentic import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want: Want, param: AbilityConstant.LaunchParam) { - let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + onCreate(want: Want, param: AbilityConstant.LaunchParam) { // ability 生命周期函数 + let sessionId: string = want.parameters![account_appAccount.Constants.KEY_SESSION_ID] as string; appAccountManager.getAuthenticatorCallback(sessionId, (err: BusinessError, callback: account_appAccount.AuthenticatorCallback) => { if (err.code != account_appAccount.ResultCode.SUCCESS) { console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); return; } - let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', - [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', - [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', - [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, { + name: 'LiSi', + owner: 'com.example.accountjsdemo', + authType: 'getSocialData', + token: 'xxxxxx'} + ); }); } } @@ -4568,15 +4587,16 @@ getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> import AbilityConstant from '@ohos.app.ability.AbilityConstant'; export default class EntryAbility extends UIAbility { - onCreate(want: Want, param: AbilityConstant.LaunchParam) { - let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + onCreate(want: Want, param: AbilityConstant.LaunchParam) { // ability 生命周期函数 + let sessionId: string = want.parameters![account_appAccount.Constants.KEY_SESSION_ID] as string; appAccountManager.getAuthenticatorCallback(sessionId).then(( callback: account_appAccount.AuthenticatorCallback) => { - let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', - [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', - [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', - [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, { + name: 'LiSi', + owner: 'com.example.accountjsdemo', + authType: 'getSocialData', + token: 'xxxxxx'} + ); }).catch((err: BusinessError) => { console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); @@ -4855,8 +4875,8 @@ onResult: (code: number, result?: AuthResult) => void let appAccountManager = account_appAccount.createAppAccountManager(); let sessionId = '1234'; appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => { - let result = { - accountInfo: { + let result: account_appAccount.AuthResult = { + account: { name: 'Lisi', owner: 'com.example.accountjsdemo', }, @@ -4891,16 +4911,17 @@ onRequestRedirected: (request: Want) => void class MyAuthenticator extends account_appAccount.Authenticator { createAccountImplicitly( options: account_appAccount.CreateAccountImplicitlyOptions, callback: account_appAccount.AuthCallback) { - callback.onRequestRedirected({ - bundleName: 'com.example.accountjsdemo', - abilityName: 'com.example.accountjsdemo.LoginAbility', - }); + let want: Want = { + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.LoginAbility', + }; + callback.onRequestRedirected(want); } auth(name: string, authType: string, options: { [key: string]: Object }, callback: account_appAccount.AuthCallback) { - let result = { - accountInfo: { + let result: account_appAccount.AuthResult = { + account: { name: 'Lisi', owner: 'com.example.accountjsdemo', }, @@ -4930,9 +4951,11 @@ onRequestContinued?: () => void let appAccountManager = account_appAccount.createAppAccountManager(); let sessionId = '1234'; appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => { + if (callback.onRequestContinued != undefined) { callback.onRequestContinued(); + } }).catch((err: BusinessError) => { - console.log('getAuthCallback err: ' + JSON.stringify(err)); + console.log('getAuthCallback err: ' + JSON.stringify(err)); }); ``` @@ -4967,11 +4990,12 @@ onResult: (code: number, result: {[key: string]: any}) => void let appAccountManager = account_appAccount.createAppAccountManager(); let sessionId = '1234'; appAccountManager.getAuthenticatorCallback(sessionId).then((callback: account_appAccount.AuthenticatorCallback) => { - let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi', - [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo', - [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData', - [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, { + name: 'LiSi', + owner: 'com.example.accountjsdemo', + authType: 'getSocialData', + token: 'xxxxxx'} + ); }).catch((err: BusinessError) => { console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); }); @@ -4997,44 +5021,24 @@ onRequestRedirected: (request: Want) => void class MyAuthenticator extends account_appAccount.Authenticator { addAccountImplicitly(authType: string, callerBundleName: string, options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { - callback.onRequestRedirected({ - bundleName: 'com.example.accountjsdemo', - abilityName: 'com.example.accountjsdemo.LoginAbility', - }); + let want: Want = { + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.LoginAbility', + }; + callback.onRequestRedirected(want); } authenticate(name: string, authType: string, callerBundleName: string, options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { - let result = {[account_appAccount.Constants.KEY_NAME]: name, - [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, { + name: name, + authType: authType, + token: 'xxxxxx'} + ); } } ``` -### onRequestContinued9+ - -onRequestContinued?: () => void - -通知请求被继续处理。 - -**系统能力:** SystemCapability.Account.AppAccount - -**示例:** - - ```js - import { BusinessError } from '@ohos.base'; - - let appAccountManager = account_appAccount.createAppAccountManager(); - let sessionId = '1234'; - appAccountManager.getAuthenticatorCallback(sessionId).then((callback: account_appAccount.AuthenticatorCallback) => { - callback.onRequestContinued(); - }).catch((err: BusinessError) => { - console.log('getAuthenticatorCallback err: ' + JSON.stringify(err)); - }); - ``` - ## Authenticator8+ 认证器基类。 @@ -5193,49 +5197,57 @@ getRemoteObject(): rpc.RemoteObject; class MyAuthenticator extends account_appAccount.Authenticator { addAccountImplicitly(authType: string, callerBundleName: string, options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { - callback.onRequestRedirected({ + let want: Want = { bundleName: 'com.example.accountjsdemo', abilityName: 'com.example.accountjsdemo.LoginAbility', - }); + }; + callback.onRequestRedirected(want); } authenticate(name: string, authType: string, callerBundleName: string, options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) { - let result = {[account_appAccount.Constants.KEY_NAME]: name, - [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, { + name: name, + authType: authType, + token: 'xxxxxx'} + ); } verifyCredential(name: string, options: account_appAccount.VerifyCredentialOptions, callback: account_appAccount.AuthCallback) { - callback.onRequestRedirected({ + let want: Want = { bundleName: 'com.example.accountjsdemo', abilityName: 'com.example.accountjsdemo.VerifyAbility', parameters: { name: name } - }); + }; + callback.onRequestRedirected(want); } setProperties(options: account_appAccount.SetPropertiesOptions, callback: account_appAccount.AuthCallback) { - callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); + let want: Want = { + bundleName: 'com.example.accountjsdemo', + abilityName: 'com.example.accountjsdemo.SetPropertiesAbility', + parameters: { + options: options + } + }; + callback.onRequestRedirected(want); } checkAccountLabels(name: string, labels: string[], callback: account_appAccount.AuthCallback) { - let result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS); } checkAccountRemovable(name: string, callback: account_appAccount.AuthCallback) { - let result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS); } } - let authenticator = null; + export default { - onConnect(want): rpc.RemoteObject { - authenticator = new MyAuthenticator(); + onConnect(want): rpc.RemoteObject { // serviceAbility 生命周期函数 + let authenticator = new MyAuthenticator(); return authenticator.getRemoteObject(); } } diff --git a/zh-cn/application-dev/reference/apis/js-apis-appControl.md b/zh-cn/application-dev/reference/apis/js-apis-appControl.md index a0a7b55af9f4fd4e745d57d6d11bb97942db3ecb..be06e5fe4406ce1ae33333ff1977c6354618764c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appControl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appControl.md @@ -50,8 +50,8 @@ setDisposedStatus(appId: string, disposedWant: Want): Promise\ **示例:** ```ts -var appId = "com.example.myapplication_xxxxx"; -var want = {bundleName: 'com.example.myapplication'}; +let appId = "com.example.myapplication_xxxxx"; +let want = {bundleName: 'com.example.myapplication'}; try { appControl.setDisposedStatus(appId, want) @@ -96,8 +96,8 @@ setDisposedStatus(appId: string, disposedWant: Want, callback: AsyncCallback\ { @@ -190,7 +190,7 @@ getDisposedStatus(appId: string): Promise\; **示例:** ```ts -var appId = "com.example.myapplication_xxxxx"; +let appId = "com.example.myapplication_xxxxx"; try { appControl.getDisposedStatus(appId) @@ -234,7 +234,7 @@ getDisposedStatus(appId: string, callback: AsyncCallback\): void; **示例:** ```ts -var appId = "com.example.myapplication_xxxxx"; +let appId = "com.example.myapplication_xxxxx"; try { appControl.getDisposedStatus(appId, (error, data) => { @@ -332,7 +332,7 @@ deleteDisposedStatus(appId: string): Promise\ **示例:** ```ts -var appId = "com.example.myapplication_xxxxx"; +let appId = "com.example.myapplication_xxxxx"; try { appControl.deleteDisposedStatus(appId) @@ -376,7 +376,7 @@ deleteDisposedStatus(appId: string, callback: AsyncCallback\) : void **示例:** ```ts -var appId = "com.example.myapplication_xxxxx"; +let appId = "com.example.myapplication_xxxxx"; try { appControl.deleteDisposedStatus(appId, (error, data) => { if (error) { @@ -439,8 +439,8 @@ appId是应用的唯一标识,由应用Bundle名称和签名信息决定,可 ```ts import bundleManager from '@ohos.bundle.bundleManager'; -var bundleName = 'com.example.myapplication'; -var appId; +let bundleName = 'com.example.myapplication'; +let appId: string; try { bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) .then((data) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md index 209e20483059e5ca06dd284e3b52818a517acb2b..4e676cff985be6e0ecceecbd4945ab524b86ddc3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md @@ -92,11 +92,13 @@ onConnect(): void; **示例:** ```ts +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'; + class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { - onConnect() { + onConnect(): void { console.log('AxExtensionAbility onConnect'); } -}; +} ``` ## AccessibilityExtensionAbility.onDisconnect @@ -110,11 +112,13 @@ onDisconnect(): void; **示例:** ```ts +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'; + class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { - onDisconnect() { + onDisconnect(): void { console.log('AxExtensionAbility onDisconnect'); } -}; +} ``` ## AccessibilityExtensionAbility.onAccessibilityEvent @@ -134,14 +138,16 @@ onAccessibilityEvent(event: AccessibilityEvent): void; **示例:** ```ts +import AccessibilityExtensionAbility , { AccessibilityEvent } from '@ohos.application.AccessibilityExtensionAbility'; + class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { - onAccessibilityEvent(event) { + onAccessibilityEvent(event: AccessibilityEvent): void { console.log('AxExtensionAbility onAccessibilityEvent'); if (event.eventType === 'click') { console.log('AxExtensionAbility onAccessibilityEvent: click'); } } -}; +} ``` ## AccessibilityExtensionAbility.onKeyEvent @@ -161,14 +167,17 @@ onKeyEvent(keyEvent: KeyEvent): boolean; **示例:** ```ts +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'; +import { KeyEvent } from '@ohos.multimodalInput.keyEvent'; + class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { - onKeyEvent(keyEvent) { + onKeyEvent(keyEvent: KeyEvent): boolean { console.log('AxExtensionAbility onKeyEvent'); - if (keyEvent.keyCode === 22) { - console.log('AxExtensionAbility onKeyEvent: intercept 22'); + if (keyEvent.key.code === 16) { + console.log('AxExtensionAbility onKeyEvent: intercept 16'); return true; } return false; } -}; +} ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md index 471fc303f6ad40f975d9f8a56f0dfe2af3a93015..95ec4fc5d5b932df7ff377a7cfa3295e7ce63520 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md @@ -11,7 +11,7 @@ ## 导入模块 -```js +```ts import dragController from "@ohos.arkui.dragController"; ``` @@ -35,7 +35,7 @@ executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: DragInfo, callback: ```ts import dragController from "@ohos.arkui.dragController" -import UDMF from '@ohos.data.UDMF' +import UDC from '@ohos.data.unifiedDataChannel'; @Entry @Component @@ -54,8 +54,8 @@ struct DragControllerPage { Button('touch to execute drag') .onTouch((event) => { if (event.type == TouchType.Down) { - let text = new UDMF.Text() - let unifiedData = new UDMF.UnifiedData(text) + let text = new UDC.Text() + let unifiedData = new UDC.UnifiedData(text) let dragInfo: dragController.DragInfo = { pointerId: 0, @@ -101,9 +101,9 @@ executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: DragInfo): Promise&l ```ts import dragController from "@ohos.arkui.dragController" -import UDMF from '@ohos.data.UDMF'; import componentSnapshot from '@ohos.arkui.componentSnapshot'; import image from '@ohos.multimedia.image'; +import UDC from '@ohos.data.unifiedDataChannel'; @Entry @Component @@ -133,8 +133,8 @@ struct DragControllerPage { Button('touch to execute drag') .onTouch((event) => { if (event.type == TouchType.Down) { - let text = new UDMF.Text() - let unifiedData = new UDMF.UnifiedData(text) + let text = new UDC.Text() + let unifiedData = new UDC.UnifiedData(text) let dragInfo: dragController.DragInfo = { pointerId: 0, @@ -178,5 +178,5 @@ struct DragControllerPage { | 名称 | 类型 | 必填 | 说明 | | ----------- | ------------------------------------------------------ | ---- | ---------------------------------------- | | pointerId | number | 是 | 设置启动拖拽时屏幕上触摸点的Id。 | -| data | [UDMF.UnifiedData](./js-apis-data-udmf.md#unifieddata) | 否 | 设置拖拽过程中携带的数据。 | +| data | [unifiedDataChannel.UnifiedData](js-apis-data-unifiedDataChannel.md#unifieddata) | 否 | 设置拖拽过程中携带的数据。 | | extraParams | string | 否 | 设置拖拽事件额外信息,具体功能暂未实现。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md index 4279c05500089d0c813979e311657a7c7e041fd0..47fe1ca88cdadc08ade5db3f1bfd89dcad9bbd68 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md @@ -52,7 +52,7 @@ ArrayList的构造函数。 **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); ``` @@ -87,14 +87,19 @@ add(element: T): boolean **示例:** ```ts -let arrayList = new ArrayList(); -let result = arrayList.add("a"); -let result1 = arrayList.add(1); +class C1 { + name: string = "" + age: string = "" +} +let arrayList: ArrayList | C1> = new ArrayList(); +let result1 = arrayList.add("a"); +let arrayList1: ArrayList = new ArrayList(); +let result2 = arrayList.add(1); let b = [1, 2, 3]; -let result2 = arrayList.add(b); -let c = {name: "Dylon", age: "13"}; -let result3 = arrayList.add(c); -let result4 = arrayList.add(false); +let result3 = arrayList.add(b); +let c : C1 = {name: "Dylon", age: "13"} +let result4 = arrayList.add(c); +let result5 = arrayList.add(false); ``` ### insert @@ -124,7 +129,7 @@ insert(element: T, index: number): void **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.insert("A", 0); arrayList.insert(0, 1); arrayList.insert(true, 2); @@ -161,9 +166,9 @@ has(element: T): boolean **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add("squirrel"); -let result = arrayList.has("squirrel"); +let result: boolean = arrayList.has("squirrel"); ``` ### getIndexOf @@ -197,7 +202,7 @@ getIndexOf(element: T): number **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); @@ -205,7 +210,7 @@ arrayList.add(2); arrayList.add(1); arrayList.add(2); arrayList.add(4); -let result = arrayList.getIndexOf(2); +let result: number = arrayList.getIndexOf(2); ``` ### getLastIndexOf @@ -239,7 +244,7 @@ getLastIndexOf(element: T): number **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); @@ -247,7 +252,7 @@ arrayList.add(2); arrayList.add(1); arrayList.add(2); arrayList.add(4); -let result = arrayList.getLastIndexOf(2); +let result: number = arrayList.getLastIndexOf(2); ``` ### removeByIndex @@ -282,13 +287,13 @@ removeByIndex(index: number): T **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(2); arrayList.add(4); -let result = arrayList.removeByIndex(2); +let result: number = arrayList.removeByIndex(2); ``` ### remove @@ -322,12 +327,12 @@ remove(element: T): boolean **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -let result = arrayList.remove(2); +let result: boolean = arrayList.remove(2); ``` ### removeByRange @@ -357,7 +362,7 @@ removeByRange(fromIndex: number, toIndex: number): void **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); @@ -400,14 +405,14 @@ callbackfn的参数说明: **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -arrayList.replaceAllElements((value) => { - // 用户操作逻辑根据实际场景进行添加。 - return value; +arrayList.replaceAllElements((value: number): number => { + // 用户操作逻辑根据实际场景进行添加。 + return value; }); ``` @@ -446,13 +451,13 @@ callbackfn的参数说明: **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -arrayList.forEach((value, index) => { - console.log("value:" + value, "index:" + index); +arrayList.forEach((value: number, index: number) => { + console.log("hyq value:" + value, "index:" + index); }); ``` @@ -488,7 +493,7 @@ comparator的参数说明: **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); @@ -531,12 +536,12 @@ subArrayList(fromIndex: number, toIndex: number): ArrayList<T> **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -let result = arrayList.subArrayList(2, 4); +let result: ArrayList = arrayList.subArrayList(2, 4); ``` ### clear @@ -558,7 +563,7 @@ clear(): void **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); @@ -592,12 +597,12 @@ clone(): ArrayList<T> **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -let result = arrayList.clone(); +let result: ArrayList = arrayList.clone(); ``` ### getCapacity @@ -625,12 +630,12 @@ getCapacity(): number **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -let result = arrayList.getCapacity(); +let result: number = arrayList.getCapacity(); ``` ### convertToArray @@ -658,12 +663,12 @@ convertToArray(): Array<T> **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -let result = arrayList.convertToArray(); +let result: Array = arrayList.convertToArray(); ``` ### isEmpty @@ -691,12 +696,12 @@ isEmpty(): boolean **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); -let result = arrayList.isEmpty(); +let result: boolean = arrayList.isEmpty(); ``` ### increaseCapacityTo @@ -724,7 +729,7 @@ increaseCapacityTo(newCapacity: number): void **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); @@ -752,7 +757,7 @@ trimToCurrentLength(): void **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); @@ -785,22 +790,23 @@ arrayList.trimToCurrentLength(); **示例:** ```ts -let arrayList = new ArrayList(); +let arrayList: ArrayList = new ArrayList(); arrayList.add(2); arrayList.add(4); arrayList.add(5); arrayList.add(4); // 使用方法一: -for (let item of arrayList) { - console.log(`value:${item}`); -} +let numbers: Array = arrayList.convertToArray() +for (let item of numbers) { + console.log(`hyq value : ${item}`); +} // 使用方法二: let iter = arrayList[Symbol.iterator](); -let temp = iter.next().value; -while(temp != undefined) { - console.log(`value:${temp}`); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log(`value:${temp.value}`); + temp = iter.next(); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index ca460869b665fa549a3fca272acd283b167fd9ca..3284f0899bdf2e2f3c3a269f349c8383184a923a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -115,14 +115,14 @@ getRemainingDelayTime(requestId: number): Promise<number> **示例**: - ```js - let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); - backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then( res => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - }).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); - }) - ``` +```js +let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); + backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then((res:number) => { + console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); +}).catch((err : BusinessError) => { + console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); +}) +``` ## backgroundTaskManager.cancelSuspendDelay @@ -173,31 +173,32 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -function callback(err, data) { - if (err) { - console.error("Operation startBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation startBackgroundRunning succeeded"); - } +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; + +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation startBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation startBackgroundRunning succeeded"); + } } -let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; -wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) }); ``` @@ -207,35 +208,36 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -function callback(err, data) { - if (err) { - console.error("Operation startBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation startBackgroundRunning succeeded"); - } +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; + +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation startBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation startBackgroundRunning succeeded"); + } } export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) - }); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) + }); + } }; ``` @@ -270,27 +272,28 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.app.ability.wantAgent'; - -let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; + +let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; -wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err: BusinessError) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); }); ``` @@ -299,31 +302,32 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -import wantAgent from '@ohos.app.ability.wantAgent'; +import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; +import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - let wantAgentInfo = { - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - }); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + let wantAgentInfo : wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err: BusinessError) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + }); + } }; ``` @@ -349,13 +353,14 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; -function callback(err, data) { - if (err) { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation stopBackgroundRunning succeeded"); - } +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation stopBackgroundRunning succeeded"); + } } backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback); @@ -367,19 +372,20 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; -function callback(err, data) { - if (err) { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - } else { - console.info("Operation stopBackgroundRunning succeeded"); - } +function callback(err: BusinessError, data: void) { + if (err) { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation stopBackgroundRunning succeeded"); + } } export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - backgroundTaskManager.stopBackgroundRunning(this.context, callback); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + backgroundTaskManager.stopBackgroundRunning(this.context, callback); + } }; ``` @@ -410,11 +416,12 @@ FA模型示例: ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); -}).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); + console.info("Operation stopBackgroundRunning succeeded"); +}).catch((err: BusinessError) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); }); ``` @@ -424,15 +431,16 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import { BusinessError } from '@ohos.base'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err: BusinessError) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } }; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-buffer.md b/zh-cn/application-dev/reference/apis/js-apis-buffer.md index f787001b479fd4f31424f98c09faa1f2a49c381b..21f9ec032803a1ccfa2d18123d7f9213fd2eb9f0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-buffer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-buffer.md @@ -604,7 +604,7 @@ let buf1 = buffer.allocUninitializedFromPool(26); let buf2 = buffer.allocUninitializedFromPool(26).fill('!'); for (let i = 0; i < 26; i++) { - buf1[i] = i + 97; + buf1.writeInt8(i + 97, i); } buf1.copy(buf2, 8, 16, 20); @@ -633,8 +633,11 @@ entries(): IterableIterator<[number, number]> import buffer from '@ohos.buffer'; let buf = buffer.from('buffer'); -for (let pair of buf.entries()) { - console.log(pair.toString()); +let pair = buf.entries() +let next = pair.next() +while (!next.done) { + console.info(next.value) + next = pair.next() } ``` @@ -796,7 +799,8 @@ keys(): IterableIterator<number> import buffer from '@ohos.buffer'; let buf = buffer.from('buffer'); -for (const key of buf.keys()) { +let numbers = Array.from(buf.values()) +for (const key of numbers) { console.log(key.toString()); } ``` @@ -1766,7 +1770,7 @@ import buffer from '@ohos.buffer'; let buf1 = buffer.allocUninitializedFromPool(26); for (let i = 0; i < 26; i++) { - buf1[i] = i + 97; + buf1.writeInt8(i + 97, i); } const buf2 = buf1.subarray(0, 3); console.log(buf2.toString('ascii', 0, buf2.length)); @@ -1932,7 +1936,7 @@ import buffer from '@ohos.buffer'; let buf1 = buffer.allocUninitializedFromPool(26); for (let i = 0; i < 26; i++) { - buf1[i] = i + 97; + buf1.writeInt8(i + 97, i); } console.log(buf1.toString('utf-8')); // 打印: abcdefghijklmnopqrstuvwxyz @@ -1958,8 +1962,11 @@ values(): IterableIterator<number> import buffer from '@ohos.buffer'; let buf1 = buffer.from('buffer'); -for (let value of buf1.values()) { - console.log(value.toString()); +let pair = buf1.values() +let next = pair.next() +while (!next.done) { + console.log(next.value.toString()); + next = pair.next() } ``` @@ -2913,8 +2920,14 @@ Blob的构造函数。 ```ts import buffer from '@ohos.buffer'; -let blob = new buffer.Blob(['a', 'b', 'c']); -let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); +let blob: buffer.Blob = new buffer.Blob(['a', 'b', 'c']); + +class option { + endings: string + type: string +} +let o1: option = {endings:'native', type: 'MIME'} +let blob1: buffer.Blob = new buffer.Blob(['a', 'b', 'c'], o1); ``` ### arrayBuffer @@ -2932,10 +2945,12 @@ arrayBuffer(): Promise<ArrayBuffer> **示例:** ```ts -let blob = new buffer.Blob(['a', 'b', 'c']); +import buffer from '@ohos.buffer'; + +let blob: buffer.Blob = new buffer.Blob(['a', 'b', 'c']); let pro = blob.arrayBuffer(); -pro.then(val => { - let uintarr = new Uint8Array(val); +pro.then((val: ArrayBuffer) => { + let uintarr: Uint8Array = new Uint8Array(val); console.log(uintarr.toString()); }); ``` @@ -2962,7 +2977,9 @@ slice(start?: number, end?: number, type?: string): Blob **示例:** ```ts -let blob = new buffer.Blob(['a', 'b', 'c']); +import buffer from '@ohos.buffer'; + +let blob: buffer.Blob = new buffer.Blob(['a', 'b', 'c']); let blob2 = blob.slice(0, 2); let blob3 = blob.slice(0, 2, "MIME"); ``` @@ -2982,9 +2999,11 @@ text(): Promise<string> **示例:** ```ts -let blob = new buffer.Blob(['a', 'b', 'c']); +import buffer from '@ohos.buffer'; + +let blob: buffer.Blob = new buffer.Blob(['a', 'b', 'c']); let pro = blob.text(); -pro.then(val => { - console.log(val) +pro.then((val: string) => { + console.log(val) }); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md index 26a3254206949582ceb3d71d253d2f14bc9e1b8c..4cc5b90e71aea7bb82123ba6b47ff0648ff2e756 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -42,10 +42,20 @@ FA模型示例: // 导入模块 import distributedObject from '@ohos.data.distributedDataObject'; import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; // 获取context let context = featureAbility.getContext(); -// 创建对象,该对象包含4个属性类型:string、number、boolean和Object -let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DataObject = distributedObject.create(context, source); ``` Stage模型示例: @@ -54,13 +64,23 @@ Stage模型示例: // 导入模块 import distributedObject from '@ohos.data.distributedDataObject'; import UIAbility from '@ohos.app.ability.UIAbility'; - -let g_object = null; - +import { BusinessError } from '@ohos.base'; +import window from '@ohos.window'; + +let g_object: distributedObject.DataObject = null; +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - g_object = distributedObject.create(this.context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); + onWindowStageCreate(windowStage: window.WindowStage) { + let source: sourceObject = { + name: "amy", + age:18, + isVis:false + } + g_object = distributedObject.create(this.context, source); } } ``` @@ -83,7 +103,7 @@ genSessionId(): string ```js import distributedObject from '@ohos.data.distributedDataObject'; -let sessionId = distributedObject.genSessionId(); +let sessionId: string = distributedObject.genSessionId(); ``` ## SaveSuccessResponse9+ @@ -179,7 +199,7 @@ g_object.setSessionId(distributedObject.genSessionId(), ()=>{ }); // 退出分布式组网 g_object.setSessionId(() => { - console.info("leave all lession."); + console.info("leave all session."); }); ``` @@ -219,13 +239,13 @@ setSessionId(sessionId?: string): Promise<void> // g_object加入分布式组网 g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ console.info("join session."); - }).catch((error)=>{ + }).catch((error: BusinessError)=>{ console.info("error:" + error.code + error.message); }); // 退出分布式组网 g_object.setSessionId().then (()=>{ - console.info("leave all lession."); - }).catch((error)=>{ + console.info("leave all session."); + }).catch((error: BusinessError)=>{ console.info("error:" + error.code + error.message); }); ``` @@ -248,15 +268,18 @@ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<stri **示例:** ```js -globalThis.changeCallback = (sessionId, changeData) => { - console.info("change" + sessionId); - if (changeData != null && changeData != undefined) { - changeData.forEach(element => { - console.info("changed !" + element + " " + g_object[element]); - }); - } +interface ChangeCallback { + sessionId: string, + fields: Array } -g_object.on("change", globalThis.changeCallback); +g_object.on("change", (changeData: ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); ``` ### off('change')9+ @@ -279,7 +302,14 @@ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<st ```js // 删除数据变更回调changeCallback -g_object.off("change", globalThis.changeCallback); +g_object.off("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); // 删除所有的数据变更回调 g_object.off("change"); ``` @@ -302,10 +332,15 @@ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, st **示例:** ```js -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +interface onStatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' } -g_object.on("status", globalThis.statusCallback); + +g_object.on("status", (statusCallback:onStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); +}); ``` ### off('status')9+ @@ -327,11 +362,15 @@ off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, s **示例:** ```js -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +interface offStatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' } // 删除上下线回调changeCallback -g_object.off("status",globalThis.statusCallback); +g_object.off("status", (statusCallback:StatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); +}); // 删除所有的上下线回调 g_object.off("status"); ``` @@ -363,7 +402,7 @@ save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void ```ts g_object.setSessionId("123456"); -g_object.save("local", (err, result) => { +g_object.save("local", (err: BusinessError, result:distributedObject.SaveSuccessResponse) => { if (err) { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); @@ -408,12 +447,12 @@ save(deviceId: string): Promise<SaveSuccessResponse> ```js g_object.setSessionId("123456"); -g_object.save("local").then((result) => { +g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => { console.info("save callback"); console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}).catch((err) => { +}).catch((err: BusinessError) => { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); }); @@ -441,7 +480,7 @@ revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void ```js g_object.setSessionId("123456"); // 持久化数据 -g_object.save("local", (err, result) => { +g_object.save("local", (err: BusinessError, result: distributedObject.SaveSuccessResponse) => { if (err) { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); @@ -453,7 +492,7 @@ g_object.save("local", (err, result) => { console.info("save deviceId: " + result.deviceId); }); // 删除持久化保存的数据 -g_object.revokeSave((err, result) => { +g_object.revokeSave((err: BusinessError, result: distributedObject.RevokeSaveSuccessResponse) => { if (err) { console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error message: " + err.message); @@ -486,20 +525,20 @@ revokeSave(): Promise<RevokeSaveSuccessResponse> ```ts g_object.setSessionId("123456"); // 持久化数据 -g_object.save("local").then((result) => { +g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => { console.info("save callback"); console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}).catch((err) => { +}).catch((err: BusinessError) => { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); }); // 删除持久化保存的数据 -g_object.revokeSave().then((result) => { +g_object.revokeSave().then((result: distributedObject.RevokeSaveSuccessResponse) => { console.info("revokeSave callback"); console.info("sessionId" + result.sessionId); -}).catch((err)=> { +}).catch((err: BusinessError)=> { console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error message = " + err.message); }); @@ -534,8 +573,17 @@ createDistributedObject(source: object): DistributedObject ```js import distributedObject from '@ohos.data.distributedDataObject'; -// 创建对象,对象包含4个属性类型,string,number,boolean和Object -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); ``` ## DistributedObject(deprecated) @@ -572,7 +620,17 @@ setSessionId(sessionId?: string): boolean ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); // g_object加入分布式组网 g_object.setSessionId(distributedObject.genSessionId()); // 设置为""退出分布式组网 @@ -602,16 +660,29 @@ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<stri ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); -globalThis.changeCallback = (sessionId, changeData) => { - console.info("change" + sessionId); - if (changeData != null && changeData != undefined) { - changeData.forEach(element => { - console.info("changed !" + element + " " + g_object[element]); - }); - } +interface sourceObject{ + name: string, + age: number, + isVis: boolean } -g_object.on("change", globalThis.changeCallback); +interface ChangeCallback { + sessionId: string, + fields: Array +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); +g_object.on("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); ``` ### off('change')(deprecated) @@ -638,9 +709,30 @@ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<st ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +interface ChangeCallback { + sessionId: string, + fields: Array +} +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); // 删除数据变更回调changeCallback -g_object.off("change", globalThis.changeCallback); +g_object.off("change", (changeData:ChangeCallback) => { + console.info("change" + changeData.sessionId); + if (changeData.fields != null && changeData.fields != undefined) { + for (let index: number = 0; index < changeData.fields.length; index++) { + console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); + } + } +}); // 删除所有的数据变更回调 g_object.off("change"); ``` @@ -668,11 +760,27 @@ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, st ```js import distributedObject from '@ohos.data.distributedDataObject'; -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; + +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +interface StatusCallback { + sessionId: string, + networkId: string, + status: 'online' | 'offline' } -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); -g_object.on("status", globalThis.statusCallback); +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); + +g_object.on("status", (statusCallback:StatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); +}); ``` ### off('status')(deprecated) @@ -699,12 +807,26 @@ off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, s ```js import distributedObject from '@ohos.data.distributedDataObject'; -let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); -globalThis.statusCallback = (sessionId, networkId, status) => { - globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +interface sourceObject{ + name: string, + age: number, + isVis: boolean +} +interface offStatusCallback { + sessionId: string, + deviceId: string, + status: 'online' | 'offline' } +let source: sourceObject = { + name: "amy", + age:18, + isVis:false +} +let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); // 删除上下线回调changeCallback -g_object.off("status",globalThis.statusCallback); +g_object.off("status", (statusCallback:offStatusCallback) => { + console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId); +}); // 删除所有的上下线回调 g_object.off("status"); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md index 7b5075441c0fb2e06881530e4aaabc71d2a97c57..b9ea1bd0f99eafe3ea98bd3d49f2d7dee68422e6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @@ -49,11 +49,13 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base'; + let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - data_preferences.getPreferences(context, 'mystore', function (err, val) { + data_preferences.getPreferences(context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -70,16 +72,18 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.getPreferences(this.context, 'mystore', function (err, val) { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { if (err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); - return; + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + return; } preferences = val; console.info("Succeeded in getting preferences."); @@ -119,15 +123,17 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - let promise = data_preferences.getPreferences(context, 'mystore'); - promise.then((object) => { + let promise = data_preferences.getPreferences(context, 'myStore'); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -139,17 +145,19 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.getPreferences(this.context, 'mystore'); - promise.then((object) => { + let promise = data_preferences.getPreferences(this.context, 'myStore'); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -191,11 +199,14 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - data_preferences.getPreferences(context, { name: 'mystore' }, function (err, val) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -213,13 +224,16 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, val) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -271,15 +285,17 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - let promise = data_preferences.getPreferences(context, { name: 'mystore' }); - promise.then((object) => { + let options: data_preferences.Options = { name: 'myStore' }; + let promise = data_preferences.getPreferences(context, options); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -291,17 +307,20 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; -let preferences = null; +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }); - promise.then((object) => { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.getPreferences(this.context, options); + promise.then((object: data_preferences.Preferences) => { preferences = object; console.info("Succeeded in getting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -348,11 +367,14 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); -let preferences = null; +let preferences: data_preferences.Preferences = null; try { - preferences = data_preferences.getPreferencesSync(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + preferences = data_preferences.getPreferencesSync(context, options); } catch(err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); } @@ -362,12 +384,16 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -let preferences = null; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences = null; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - preferences = data_preferences.getPreferencesSync(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + preferences = data_preferences.getPreferencesSync(this.context, options); } catch(err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); } @@ -408,10 +434,12 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - data_preferences.deletePreferences(context, 'mystore', function (err) { + data_preferences.deletePreferences(context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -427,11 +455,13 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.deletePreferences(this.context, 'mystore', function (err) { + data_preferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -483,13 +513,15 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - let promise = data_preferences.deletePreferences(context, 'mystore'); + let promise = data_preferences.deletePreferences(context, 'myStore'); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -501,14 +533,16 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try{ - let promise = data_preferences.deletePreferences(this.context, 'mystore'); + let promise = data_preferences.deletePreferences(this.context, 'myStore'); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -553,10 +587,13 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - data_preferences.deletePreferences(context, { name: 'mystore' }, function (err) { + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.deletePreferences(context, options, (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -572,11 +609,14 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.deletePreferences(this.context, options, (err: BusinessError) => { if (err) { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); return; @@ -631,13 +671,16 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - let promise = data_preferences.deletePreferences(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + let promise = data_preferences.deletePreferences(context, options); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -649,14 +692,17 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try{ - let promise = data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.deletePreferences(this.context, options); promise.then(() => { console.info("Succeeded in deleting preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -694,9 +740,11 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { + data_preferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -712,11 +760,13 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { + data_preferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -762,12 +812,14 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' + let context = featureAbility.getContext(); try { - let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); + let promise = data_preferences.removePreferencesFromCache(context, 'myStore'); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -779,14 +831,16 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore'); + let promise = data_preferences.removePreferencesFromCache(this.context, 'myStore'); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -824,7 +878,7 @@ FA模型示例: import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCacheSync(context, 'mystore'); + data_preferences.removePreferencesFromCacheSync(context, 'myStore'); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -836,9 +890,9 @@ Stage模型示例: import UIAbility from '@ohos.app.ability.UIAbility'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCacheSync(this.context, 'mystore'); + data_preferences.removePreferencesFromCacheSync(this.context, 'myStore'); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -882,9 +936,11 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCache(context, { name: 'mystore' }, function (err) { + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.removePreferencesFromCache(context, options, (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -900,11 +956,14 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -959,12 +1018,14 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility'; +import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); try { - let promise = data_preferences.removePreferencesFromCache(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + let promise = data_preferences.removePreferencesFromCache(context, options); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -976,14 +1037,17 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - let promise = data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.removePreferencesFromCache(this.context, options); promise.then(() => { console.info("Succeeded in removing preferences."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -1030,7 +1094,8 @@ FA模型示例: import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { - data_preferences.removePreferencesFromCacheSync(context, { name: 'mystore' }); + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.removePreferencesFromCacheSync(context, options); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -1040,11 +1105,13 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { try { - data_preferences.removePreferencesFromCacheSync(this.context, { name: 'mystore', dataGroupId:'myId' }); + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCacheSync(this.context, options); } catch(err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); } @@ -1090,7 +1157,7 @@ get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): ```js try { - preferences.get('startup', 'default', function (err, val) { + preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => { if (err) { console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1129,9 +1196,9 @@ get(key: string, defValue: ValueType): Promise<ValueType> ```js try { let promise = preferences.get('startup', 'default'); - promise.then((data) => { + promise.then((data: data_preferences.ValueType) => { console.info("Succeeded in getting value of 'startup'. Data: " + data); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -1164,7 +1231,7 @@ getSync(key: string, defValue: ValueType): ValueType ```js try { - let value = preferences.getSync('startup', 'default'); + let value: data_preferences.ValueType = preferences.getSync('startup', 'default'); console.info("Succeeded in getting value of 'startup'. Data: " + value); } catch(err) { console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); @@ -1189,14 +1256,14 @@ getAll(callback: AsyncCallback<Object>): void; ```js try { - preferences.getAll(function (err, value) { + preferences.getAll((err: BusinessError, value: data_preferences.ValueType) => { if (err) { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); return; } - let allKeys = Object.keys(value); - console.info("getAll keys = " + allKeys); - console.info("getAll object = " + JSON.stringify(value)); + let allKeys = Object.keys(value); + console.info("getAll keys = " + allKeys); + console.info("getAll object = " + JSON.stringify(value)); }) } catch (err) { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); @@ -1223,11 +1290,11 @@ getAll(): Promise<Object> ```js try { let promise = preferences.getAll(); - promise.then((value) => { + promise.then((value: data_preferences.ValueType) => { let allKeys = Object.keys(value); console.info('getAll keys = ' + allKeys); console.info("getAll object = " + JSON.stringify(value)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); }) } catch (err) { @@ -1282,7 +1349,7 @@ put(key: string, value: ValueType, callback: AsyncCallback<void>): void ```js try { - preferences.put('startup', 'auto', function (err) { + preferences.put('startup', 'auto', (err: BusinessError) => { if (err) { console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1323,7 +1390,7 @@ try { let promise = preferences.put('startup', 'auto'); promise.then(() => { console.info("Succeeded in putting value of 'startup'."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); }) } catch(err) { @@ -1377,7 +1444,7 @@ has(key: string, callback: AsyncCallback<boolean>): void ```js try { - preferences.has('startup', function (err, val) { + preferences.has('startup', (err: BusinessError, val: boolean) => { if (err) { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1387,7 +1454,7 @@ try { } else { console.info("The key 'startup' dose not contain."); } - }) + }) } catch (err) { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); } @@ -1419,15 +1486,15 @@ has(key: string): Promise<boolean> ```js try { let promise = preferences.has('startup'); - promise.then((val) => { + promise.then((val: boolean) => { if (val) { console.info("The key 'startup' is contained."); } else { console.info("The key 'startup' dose not contain."); } - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); - }) + }) } catch(err) { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); } @@ -1458,7 +1525,7 @@ hasSync(key: string): boolean ```js try { - let isExist = preferences.hasSync('startup'); + let isExist: boolean = preferences.hasSync('startup'); if (isExist) { console.info("The key 'startup' is contained."); } else { @@ -1489,7 +1556,7 @@ delete(key: string, callback: AsyncCallback<void>): void ```js try { - preferences.delete('startup', function (err) { + preferences.delete('startup', (err: BusinessError) => { if (err) { console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); return; @@ -1529,7 +1596,7 @@ try { let promise = preferences.delete('startup'); promise.then(() => { console.info("Succeeded in deleting the key 'startup'."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); }) } catch(err) { @@ -1581,7 +1648,7 @@ flush(callback: AsyncCallback<void>): void ```js try { - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. code =" + err.code + ", message =" + err.message); return; @@ -1615,7 +1682,7 @@ try { let promise = preferences.flush(); promise.then(() => { console.info("Succeeded in flushing."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to flush. code =" + err.code + ", message =" + err.message); }) } catch (err) { @@ -1642,7 +1709,7 @@ clear(callback: AsyncCallback<void>): void ```js try { - preferences.clear(function (err) { + preferences.clear((err: BusinessError) =>{ if (err) { console.error("Failed to clear. code =" + err.code + ", message =" + err.message); return; @@ -1676,7 +1743,7 @@ try { let promise = preferences.clear(); promise.then(() => { console.info("Succeeded in clearing."); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error("Failed to clear. code =" + err.code + ", message =" + err.message); }) } catch(err) { @@ -1722,29 +1789,31 @@ on(type: 'change', callback: Callback<{ key : string }>): void **示例:** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('change', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('change', observer); - preferences.put('startup', 'manual', function (err) { + }); + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { - console.error("Failed to put the value of 'startup'. Cause: " + err); - return; + console.error("Failed to put the value of 'startup'. Cause: " + err); + return; } console.info("Succeeded in putting the value of 'startup'."); - preferences.flush(function (err) { - if (err) { - console.error("Failed to flush. Cause: " + err); - return; - } - console.info("Succeeded in flushing."); + preferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Succeeded in flushing."); }) }) }) @@ -1781,24 +1850,26 @@ on(type: 'multiProcessChange', callback: Callback<{ key : string }>): void **示例1:** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('multiProcessChange', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('multiProcessChange', observer); - preferences.put('startup', 'manual', function (err) { + }); + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Succeeded in putting the value of 'startup'."); - - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. Cause: " + err); return; @@ -1815,17 +1886,21 @@ try { **示例2:** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) { + let options: data_preferences.Options = { name: 'myStore' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } preferences = val; - let observer = function (key) { + preferences.on('multiProcessChange', (key: observer) => { console.info("The key " + key + " changed."); try { - data_preferences.removePreferencesFromCache(this.context, { name: 'mystore' }, function (err) { + data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { if (err) { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); return; @@ -1838,7 +1913,7 @@ try { } try { - data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) { + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); return; @@ -1849,16 +1924,15 @@ try { } catch (err) { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); } - } - preferences.on('multiProcessChange', observer); - preferences.put('startup', 'manual', function (err) { + }); + preferences.put('startup', 'manual', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Succeeded in putting the value of 'startup'."); - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. Cause: " + err); return; @@ -1890,31 +1964,35 @@ off(type: 'change', callback?: Callback<{ key : string }>): void **示例:** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('change', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { + }); + preferences.put('startup', 'auto', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Succeeded in putting the value of 'startup'."); - preferences.flush(function (err) { + preferences.flush((err: BusinessError) =>{ if (err) { console.error("Failed to flush. Cause: " + err); return; } console.info("Succeeded in flushing."); }) - preferences.off('change', observer); + preferences.off('change', (key: observer) => { + console.info("The key " + key + " changed."); + }); }) }) } catch (err) { @@ -1940,31 +2018,36 @@ off(type: 'multiProcessChange', callback?: Callback<{ key : string }>): vo **示例:** ```js +interface observer { + key: string +} try { - data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => { if (err) { console.error("Failed to get preferences."); return; } - let observer = function (key) { + preferences.on('multiProcessChange', (key: observer) => { console.info("The key " + key + " changed."); - } - preferences.on('multiProcessChange', observer); - preferences.put('startup', 'auto', function (err) { + }); + preferences.put('startup', 'auto', (err: BusinessError) => { if (err) { console.error("Failed to put the value of 'startup'. Cause: " + err); return; } console.info("Succeeded in putting the value of 'startup'."); - preferences.flush(function (err) { + preferences.flush((err: BusinessError) => { if (err) { console.error("Failed to flush. Cause: " + err); return; } console.info("Succeeded in flushing."); }) - preferences.off('multiProcessChange', observer); + preferences.off('multiProcessChange', (key: observer) => { + console.info("The key " + key + " changed."); + }); }) }) } catch (err) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md index 5463cec6921c5d2e46e313f8b20f90a5c7e473c8..910b37c0a0e4db3b7307714ad5d6bb5dcfd46f73 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @@ -18,6 +18,8 @@ ```js import data_rdb from '@ohos.data.rdb'; +import { BusinessError } from "@ohos.base" +import window from '@ohos.window'; ``` ## data_rdb.getRdbStore @@ -43,11 +45,11 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db"} -data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { +data_rdb.getRdbStore(context, STORE_CONFIG, 1, (err, rdbStore) => { if (err) { console.info("Get RdbStore failed, err: " + err) return @@ -62,22 +64,23 @@ Stage模型示例: // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; -let context; -class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } +let context: Context; +interface storeConfig { + name: string } -// 获取context后调用getRdbStore -const STORE_CONFIG = { name: "RdbTest.db"} -data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { - if (err) { +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage){ + let STORE_CONFIG: storeConfig = { name: "RdbTest.db"}; + data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, (err: BusinessError, rdbStore: data_rdb.RdbStore) => { + if (err) { console.info("Get RdbStore failed, err: " + err) return - } - console.log("Get RdbStore successfully.") -}) + } + console.log("Get RdbStore successfully.") + }) + } +} ``` ## data_rdb.getRdbStore @@ -109,7 +112,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db" } @@ -127,20 +130,23 @@ Stage模型示例: // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; -let context; +let context: Context; +interface storeConfig { + name: string +} class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } + onWindowStageCreate(windowStage: window.WindowStage){ + context = this.context + } } // 获取context后调用getRdbStore -const STORE_CONFIG = { name: "RdbTest.db" } +let STORE_CONFIG: storeConfig = { name: "RdbTest.db"}; let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1); -promise.then(async (rdbStore) => { - console.log("Get RdbStore successfully.") -}).catch((err) => { - console.log("Get RdbStore failed, err: " + err) +promise.then(async (rdbStore: data_rdb.RdbStore) => { + console.log("Get RdbStore successfully.") +}).catch((err: BusinessError) => { + console.log("Get RdbStore failed, err: " + err) }) ``` @@ -167,15 +173,15 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // 获取context后调用deleteRdbStore -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Delete RdbStore failed, err: " + err) - return - } - console.log("Delete RdbStore successfully.") +data_rdb.deleteRdbStore(context, "RdbTest.db", (err) => { + if (err) { + console.info("Delete RdbStore failed, err: " + err) + return + } + console.log("Delete RdbStore successfully.") }) ``` @@ -185,20 +191,20 @@ Stage模型示例: // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; -let context; +let context: Context; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } + onWindowStageCreate(windowStage: window.WindowStage){ + context = this.context + } } // 获取context后调用deleteRdbStore -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Delete RdbStore failed, err: " + err) - return - } - console.log("Delete RdbStore successfully.") +data_rdb.deleteRdbStore(context, "RdbTest.db", (err) => { + if (err) { + console.info("Delete RdbStore failed, err: " + err) + return + } + console.log("Delete RdbStore successfully.") }) ``` @@ -230,7 +236,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() +let context: Context; // 获取context后调用deleteRdbStore let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") @@ -247,19 +253,19 @@ Stage模型示例: // 获取context import UIAbility from '@ohos.app.ability.UIAbility'; -let context; +let context: Context; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - context = this.context - } + onWindowStageCreate(windowStage: window.WindowStage){ + context = this.context + } } // 获取context后调用deleteRdbStore let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") promise.then(()=>{ - console.log("Delete RdbStore successfully.") -}).catch((err) => { - console.info("Delete RdbStore failed, err: " + err) + console.log("Delete RdbStore successfully.") +}).catch((err: BusinessError) => { + console.info("Delete RdbStore failed, err: " + err) }) ``` @@ -371,8 +377,8 @@ inDevices(devices: Array<string>): RdbPredicates ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmInstance = null; -let deviceIds = []; +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { if (err) { @@ -381,7 +387,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) } dmInstance = manager; let devices = dmInstance.getTrustedDeviceListSync(); - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].deviceId; } }) diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md index 9f5428715b5002fb0bd0853e133ef99f4b1a39a4..c4d6bc6c9b470c92598a633749a8cf633a7a2820 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -16,6 +16,10 @@ ```js import relationalStore from '@ohos.data.relationalStore' +import window from '@ohos.window'; +import deviceManager from '@ohos.distributedHardware.deviceManager'; +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +import { BusinessError } from "@ohos.base" ``` ## relationalStore.getRdbStore @@ -54,17 +58,17 @@ FA模型示例: import featureAbility from '@ohos.ability.featureAbility' -var store; +let store: relationalStore.RdbStore; // 获取context let context = featureAbility.getContext(); -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => { store = rdbStore; if (err) { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); @@ -80,14 +84,14 @@ Stage模型示例: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - var store; - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage) { + let store: relationalStore.RdbStore; + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; - relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => { store = rdbStore; if (err) { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); @@ -139,21 +143,21 @@ FA模型示例: ```js import featureAbility from '@ohos.ability.featureAbility' -var store; +let store: relationalStore.RdbStore; // 获取context let context = featureAbility.getContext(); -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -let promise = relationalStore.getRdbStore(context, STORE_CONFIG); -promise.then(async (rdbStore) => { +let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG); +promise.then(async (rdbStore: relationalStore.RdbStore) => { store = rdbStore; - console.info(`Get RdbStore successfully.`); -}).catch((err) => { + console.info(`Get RdbStore successfully.`) +}).catch((err: BusinessError) => { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -164,18 +168,18 @@ Stage模型示例: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - var store; - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage) { + let store: relationalStore.RdbStore; + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; - + let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG); - promise.then(async (rdbStore) => { + promise.then(async (rdbStore: relationalStore.RdbStore) => { store = rdbStore; console.info(`Get RdbStore successfully.`) - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) } @@ -216,12 +220,12 @@ FA模型示例: ```js import featureAbility from '@ohos.ability.featureAbility' -var store; +let store: relationalStore.RdbStore; // 获取context let context = featureAbility.getContext() -relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) { +relationalStore.deleteRdbStore(this.context, "RdbTest.db", (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -236,11 +240,11 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility' -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) { + onWindowStageCreate(windowStage: window.WindowStage){ + relationalStore.deleteRdbStore(this.context, "RdbTest.db", (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -291,16 +295,16 @@ FA模型示例: ```js import featureAbility from '@ohos.ability.featureAbility' -var store; +let store: relationalStore.RdbStore; // 获取context let context = featureAbility.getContext(); -let promise = relationalStore.deleteRdbStore(context, "RdbTest.db"); +let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -310,15 +314,15 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility' -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ + onWindowStageCreate(windowStage: window.WindowStage){ let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) } @@ -361,16 +365,16 @@ FA模型示例: ```js import featureAbility from '@ohos.ability.featureAbility' -var store; +let store: relationalStore.RdbStore; // 获取context let context = featureAbility.getContext() -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.deleteRdbStore(context, STORE_CONFIG, function (err) { +relationalStore.deleteRdbStore(this.context, STORE_CONFIG, (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -385,15 +389,15 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility' -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage){ + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; - relationalStore.deleteRdbStore(this.context, STORE_CONFIG, function (err) { + relationalStore.deleteRdbStore(this.context, STORE_CONFIG, (err: BusinessError) => { if (err) { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); return; @@ -446,20 +450,20 @@ FA模型示例: ```js import featureAbility from '@ohos.ability.featureAbility' -var store; +let store: relationalStore.RdbStore; // 获取context let context = featureAbility.getContext(); -const STORE_CONFIG = { +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -let promise = relationalStore.deleteRdbStore(context, STORE_CONFIG); +let promise = relationalStore.deleteRdbStore(this.context, STORE_CONFIG); promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -469,11 +473,11 @@ Stage模型示例: ```ts import UIAbility from '@ohos.app.ability.UIAbility' -var store; +let store: relationalStore.RdbStore; class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { + onWindowStageCreate(windowStage: window.WindowStage){ + const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; @@ -481,7 +485,7 @@ class EntryAbility extends UIAbility { promise.then(()=>{ store = null; console.info(`Delete RdbStore successfully.`); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); }) } @@ -820,13 +824,13 @@ inDevices(devices: Array<string>): RdbPredicates ```js import deviceManager from '@ohos.distributedDeviceManager'; -let dmInstance = null; -let deviceIds = []; +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; try { dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); let devices = dmInstance.getAvailableDeviceListSync(); - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].networkId; } } catch (err) { @@ -1640,6 +1644,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]); **示例:** ```js +let store: relationalStore.RdbStore; // 设置数据库版本 store.version = 3; // 获取数据库版本 @@ -1674,13 +1679,21 @@ insert(table: string, values: ValuesBucket, callback: AsyncCallback<number> **示例:** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -store.insert("EMPLOYEE", valueBucket, function (err, rowId) { +store.insert("EMPLOYEE", valueBucket, (err, rowId) => { if (err) { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); return; @@ -1718,13 +1731,21 @@ insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callb **示例:** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rowId) { +store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rowId) => { if (err) { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); return; @@ -1766,16 +1787,24 @@ insert(table: string, values: ValuesBucket):Promise<number> **示例:** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let promise = store.insert("EMPLOYEE", valueBucket); -promise.then((rowId) => { +promise.then((rowId: number) => { console.info(`Insert is successful, rowId = ${rowId}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1814,16 +1843,24 @@ insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promi **示例:** ```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let promise = store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); -promise.then((rowId) => { +promise.then((rowId: number) => { console.info(`Insert is successful, rowId = ${rowId}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1856,27 +1893,43 @@ batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCal **示例:** ```js -const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); +const valueBucket1: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) +const valueBucket2: ValuesBucket = { + key1: value5, + key2: value6, + key3: value7, + key4: value8, }; -const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) +const valueBucket3: ValuesBucket = { + key1: value9, + key2: value10, + key3: value11, + key4: value12, }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -store.batchInsert("EMPLOYEE", valueBuckets, function(err, insertNum) { +store.batchInsert("EMPLOYEE", valueBuckets, (err, insertNum) => { if (err) { console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); return; @@ -1918,30 +1971,46 @@ batchInsert(table: string, values: Array<ValuesBucket>):Promise<number& **示例:** ```js -const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); +const valueBucket1: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; -const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) +const valueBucket2: ValuesBucket = { + key1: value5, + key2: value6, + key3: value7, + key4: value8, }; -const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) +const valueBucket3: ValuesBucket = { + key1: value9, + key2: value10, + key3: value11, + key4: value12, }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); let promise = store.batchInsert("EMPLOYEE", valueBuckets); -promise.then((insertNum) => { +promise.then((insertNum: number) => { console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -1974,11 +2043,19 @@ update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback& **示例:** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); @@ -2020,15 +2097,23 @@ update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolu **示例:** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { +store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rows) => { if (err) { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); return; @@ -2070,18 +2155,26 @@ update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> **示例:** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); let promise = store.update(valueBucket, predicates); -promise.then(async (rows) => { +promise.then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2120,18 +2213,26 @@ update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolu **示例:** ```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); let promise = store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); -promise.then(async (rows) => { +promise.then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2170,15 +2271,23 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); -store.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { +store.update("EMPLOYEE", valueBucket, predicates, (err, rows) => { if (err) { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); return; @@ -2226,18 +2335,26 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), +let key1 = "NAME"; +let key2 = "AGE"; +let key3 = "SALARY"; +let key4 = "CODES"; +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); let promise = store.update("EMPLOYEE", valueBucket, predicates); -promise.then(async (rows) => { +promise.then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2271,7 +2388,7 @@ delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void ```js let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -store.delete(predicates, function (err, rows) { +store.delete(predicates, (err, rows) => { if (err) { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); return; @@ -2315,9 +2432,9 @@ delete(predicates: RdbPredicates):Promise<number> let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); let promise = store.delete(predicates); -promise.then((rows) => { +promise.then((rows: Number) => { console.info(`Delete rows: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2357,7 +2474,7 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callb import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); -store.delete("EMPLOYEE", predicates, function (err, rows) { +store.delete("EMPLOYEE", predicates, (err, rows) => { if (err) { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); return; @@ -2407,9 +2524,9 @@ import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Lisa"); let promise = store.delete("EMPLOYEE", predicates); -promise.then((rows) => { +promise.then((rows: Number) => { console.info(`Delete rows: ${rows}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2442,7 +2559,7 @@ query(predicates: RdbPredicates, callback: AsyncCallback<ResultSet>):void ```js let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -store.query(predicates, function (err, resultSet) { +store.query(predicates, (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2490,7 +2607,7 @@ query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCa ```js let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2544,7 +2661,7 @@ query(predicates: RdbPredicates, columns?: Array<string>):Promise<Resul let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 while (resultSet.goToNextRow()) { @@ -2556,7 +2673,7 @@ promise.then((resultSet) => { } // 释放数据集的内存 resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2595,7 +2712,7 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, callba import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Rose"); -store.query("EMPLOYEE", predicates, function (err, resultSet) { +store.query("EMPLOYEE", predicates, (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2649,7 +2766,7 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Rose"); -store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2709,7 +2826,7 @@ import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo("NAME", "Rose"); let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 while (resultSet.goToNextRow()) { @@ -2721,7 +2838,7 @@ promise.then((resultSet) => { } // 释放数据集的内存 resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -2760,8 +2877,8 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A ```js import deviceManager from '@ohos.distributedDeviceManager'; -let dmInstance = null; -let deviceId = null; +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; try { dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); @@ -2773,25 +2890,22 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); -store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet) { - if (err) { - console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); - return; - } - console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); - // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 - while (resultSet.goToNextRow()) { - const id = resultSet.getLong(resultSet.getColumnIndex("ID")); - const name = resultSet.getString(resultSet.getColumnIndex("NAME")); - const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); - const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); - console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); - } - // 释放数据集的内存 - resultSet.close(); +let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet: relationalStore.ResultSet) => { + console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); + // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 + while (resultSet.goToNextRow()) { + const id = resultSet.getLong(resultSet.getColumnIndex("ID")); + const name = resultSet.getString(resultSet.getColumnIndex("NAME")); + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`); } -) + // 释放数据集的内存 + resultSet.close(); +}).catch((err: BusinessError) => { + console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); +}) ``` ### remoteQuery @@ -2833,8 +2947,8 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A ```js import deviceManager from '@ohos.distributedDeviceManager'; -let dmInstance = null; -let deviceId = null; +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; try { dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); @@ -2847,7 +2961,7 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 while (resultSet.goToNextRow()) { @@ -2859,7 +2973,7 @@ promise.then((resultSet) => { } // 释放数据集的内存 resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`); }) ``` @@ -2890,7 +3004,7 @@ querySql(sql: string, callback: AsyncCallback<ResultSet>):void **示例:** ```js -store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", function (err, resultSet) { +store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2936,7 +3050,7 @@ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback& **示例:** ```js -store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { +store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); return; @@ -2988,7 +3102,7 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> ```js let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'"); -promise.then((resultSet) => { +promise.then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 while (resultSet.goToNextRow()) { @@ -3000,7 +3114,7 @@ promise.then((resultSet) => { } // 释放数据集的内存 resultSet.close(); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Query failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3033,7 +3147,7 @@ executeSql(sql: string, callback: AsyncCallback<void>):void ```js const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" -store.executeSql(SQL_DELETE_TABLE, function(err) { +store.executeSql(SQL_DELETE_TABLE, (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); return; @@ -3071,7 +3185,7 @@ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallbac ```js const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?" -store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], function(err) { +store.executeSql(SQL_DELETE_TABLE, ['zhangsan'], (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); return; @@ -3116,9 +3230,9 @@ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" let promise = store.executeSql(SQL_DELETE_TABLE); promise.then(() => { - console.info(`Delete table done.`); -}).catch((err) => { - console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); + console.info(`Delete table done.`); +}).catch((err: BusinessError) => { + console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3151,12 +3265,12 @@ getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[], call ```js let PRIKey = [1, 4, 2, 3]; -store.getModifyTime("cloud_tasks", "uuid", PRIKey, function (err, modifyTime) { - if (err) { - console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); - return; - } - let size = modifyTime.size(); +store.getModifyTime("cloud_tasks", "uuid", PRIKey, (err, modifyTime: relationalStore.ModifyTime)=> { + if (err) { + console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); + return; + } + let size = modifyTime.size; }); ``` @@ -3194,10 +3308,10 @@ getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[]): Pro ```js let PRIKey = [1, 2, 3]; -store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime) => { - let size = modifyTime.size(); -}).catch((err) => { - console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); +store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime: relationalStore.ModifyTime) => { + let size = modifyTime.size; +}).catch((err: BusinessError) => { + console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3223,21 +3337,29 @@ beginTransaction():void ```js import featureAbility from '@ohos.ability.featureAbility' let context = featureAbility.getContext(); -const STORE_CONFIG = { +let key1 = "name"; +let key2 = "age"; +let key3 = "SALARY"; +let key4 = "blobType"; +let value1 = "Lisi"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3]); +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => { if (err) { console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } store.beginTransaction(); - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), + const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; await store.insert("test", valueBucket); store.commit(); @@ -3257,21 +3379,29 @@ commit():void ```js import featureAbility from '@ohos.ability.featureAbility' let context = featureAbility.getContext(); -const STORE_CONFIG = { +let key1 = "name"; +let key2 = "age"; +let key3 = "SALARY"; +let key4 = "blobType"; +let value1 = "Lisi"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3]); +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => { if (err) { console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } store.beginTransaction(); - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), + const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, }; await store.insert("test", valueBucket); store.commit(); @@ -3291,24 +3421,31 @@ rollBack():void ```js import featureAbility from '@ohos.ability.featureAbility' let context = featureAbility.getContext(); -const STORE_CONFIG = { +let key1 = "name"; +let key2 = "age"; +let key3 = "SALARY"; +let key4 = "blobType"; +let value1 = "Lisi"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3]); +const STORE_CONFIG: relationalStore.StoreConfig = { name: "RdbTest.db", securityLevel: relationalStore.SecurityLevel.S1 }; -relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { +relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err, store) => { if (err) { console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`); return; } try { store.beginTransaction() - const valueBucket = { - "id": 1, - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - }; + const valueBucket: ValuesBucket = { + key1: value1, + key2: value2, + key3: value3, + key4: value4, + }; await store.insert("test", valueBucket); store.commit(); } catch (err) { @@ -3344,7 +3481,7 @@ backup(destName:string, callback: AsyncCallback<void>):void **示例:** ```js -store.backup("dbBackup.db", function(err) { +store.backup("dbBackup.db", (err) => { if (err) { console.error(`Backup failed, code is ${err.code},message is ${err.message}`); return; @@ -3387,7 +3524,7 @@ backup(destName:string): Promise<void> let promiseBackup = store.backup("dbBackup.db"); promiseBackup.then(()=>{ console.info(`Backup success.`); -}).catch((err)=>{ +}).catch((err: BusinessError)=>{ console.error(`Backup failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3418,7 +3555,7 @@ restore(srcName:string, callback: AsyncCallback<void>):void **示例:** ```js -store.restore("dbBackup.db", function(err) { +store.restore("dbBackup.db", (err) => { if (err) { console.error(`Restore failed, code is ${err.code},message is ${err.message}`); return; @@ -3461,7 +3598,7 @@ restore(srcName:string): Promise<void> let promiseRestore = store.restore("dbBackup.db"); promiseRestore.then(()=>{ console.info(`Restore success.`); -}).catch((err)=>{ +}).catch((err: BusinessError)=>{ console.error(`Restore failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3494,7 +3631,7 @@ setDistributedTables(tables: Array<string>, callback: AsyncCallback<voi **示例:** ```js -store.setDistributedTables(["EMPLOYEE"], function (err) { +store.setDistributedTables(["EMPLOYEE"], (err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); return; @@ -3539,7 +3676,7 @@ store.setDistributedTables(["EMPLOYEE"], function (err) { let promise = store.setDistributedTables(["EMPLOYEE"]); promise.then(() => { console.info(`SetDistributedTables successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3574,7 +3711,7 @@ setDistributedTables(tables: Array<string>, type: DistributedType, callbac **示例:** ```js -store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, function (err) { +store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, (err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); return; @@ -3618,7 +3755,7 @@ setDistributedTables(tables: Array<string>, type: DistributedType, config: ```js store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, { autoSync: true -}, function (err) { +},(err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); return; @@ -3668,7 +3805,7 @@ let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.Distribut }); promise.then(() => { console.info(`SetDistributedTables successfully.`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3707,8 +3844,8 @@ obtainDistributedTableName(device: string, table: string, callback: AsyncCallbac ```js import deviceManager from '@ohos.distributedDeviceManager'; -let dmInstance = null; -let deviceId = null; +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; try { dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); @@ -3718,12 +3855,12 @@ try { console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); } -store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { - if (err) { - console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); - return; - } - console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); +store.obtainDistributedTableName(deviceId, "EMPLOYEE", (err, tableName) => { + if (err) { + console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); + return; + } + console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }) ``` @@ -3766,8 +3903,8 @@ store.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) ```js import deviceManager from '@ohos.distributedDeviceManager'; -let dmInstance = null; -let deviceId = null; +let dmInstance: deviceManager.DeviceManager = null; +let deviceId: string = null; try { dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); @@ -3778,9 +3915,9 @@ try { } let promise = store.obtainDistributedTableName(deviceId, "EMPLOYEE"); -promise.then((tableName) => { +promise.then((tableName: string) => { console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3815,13 +3952,13 @@ sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array ```js import deviceManager from '@ohos.distributedDeviceManager'; -let dmInstance = null; -let deviceIds = []; +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; try { dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); let devices = dmInstance.getAvailableDeviceListSync(); - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].networkId; } } catch (err) { @@ -3830,7 +3967,7 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); -store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { +store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => { if (err) { console.error(`Sync failed, code is ${err.code},message is ${err.message}`); return; @@ -3877,13 +4014,13 @@ store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, r ```js import deviceManager from '@ohos.distributedDeviceManager'; -let dmInstance = null; -let deviceIds = []; +let dmInstance: deviceManager.DeviceManager = null; +let deviceIds: Array = []; try { dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify"); let devices = dmInstance.getAvailableDeviceListSync(); - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { deviceIds[i] = devices[i].networkId; } } catch (err) { @@ -3893,12 +4030,12 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates); -promise.then((result) =>{ +promise.then((result: Object[][]) =>{ console.info(`Sync done.`); for (let i = 0; i < result.length; i++) { console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); } -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`Sync failed, code is ${err.code},message is ${err.message}`); }) ``` @@ -3924,14 +4061,14 @@ cloudSync(mode: SyncMode, progress: Callback<ProgressDetails>, callback: A **示例:** ```js -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) { - console.info(`Progess: ${progressDetails}`); -}, function (err) { - if (err) { - console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); - return; - } - console.info('Cloud sync succeeded'); +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetails) => { + console.info(`Progess: ${progressDetails}`); +}, (err) =>{ + if (err) { + console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); + return; + } + console.info('Cloud sync succeeded'); }); ``` @@ -3961,13 +4098,11 @@ cloudSync(mode: SyncMode, progress: Callback<ProgressDetails>): Promise< **示例:** ```js -function progress(progressDetail) { +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetail: relationalStore.ProgressDetails) => { console.info(`progress: ${progressDetail}`); -} - -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => { +}).then(() => { console.info('Cloud sync succeeded'); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -3995,14 +4130,14 @@ cloudSync(mode: SyncMode, tables: string[], progress: Callback<ProgressDetail ```js const tables = ["table1", "table2"]; -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) { - console.info(`Progess: ${progressDetails}`); -}, function (err) { - if (err) { - console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); - return; - } - console.info('Cloud sync succeeded'); +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, (progressDetail: relationalStore.ProgressDetails) => { + console.info(`Progess: ${progressDetails}`); +}, (err) => { + if (err) { + console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`); + return; + } + console.info('Cloud sync succeeded'); }); ``` @@ -4034,13 +4169,12 @@ cloudSync(mode: SyncMode, tables: string[], progress: Callback<ProgressDetail ```js const tables = ["table1", "table2"]; -function progress(progressDetail) { - console.info(`progress: ${progressDetail}`); -} -store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => { +store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetail: relationalStore.ProgressDetails) => { + console.info(`progress: ${progressDetail}`); +}).then(() => { console.info('Cloud sync succeeded'); -}).catch((err) => { +}).catch((err: BusinessError) => { console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); }); ``` @@ -4064,13 +4198,14 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri **示例:** ```js -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.info(`device= ${devices[i]} data changed`); - } -} try { - store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => { + let devices: string; + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } + } + ); } catch (err) { console.error(`Register observer failed, code is ${err.code},message is ${err.message}`); } @@ -4135,11 +4270,10 @@ on(event: string, interProcess: boolean, observer: Callback\): void **示例:** ```js -function storeObserver() { - console.info(`storeObserver`); -} try { - store.on('storeObserver', false, storeObserver); + store.on('storeObserver', false, (storeObserver) => { + console.info(`storeObserver`); + }); } catch (err) { console.error(`Register observer failed, code is ${err.code},message is ${err.message}`); } @@ -4164,13 +4298,14 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri **示例:** ``` -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.info(`device= ${devices[i]} data changed`); - } -} try { - store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => { + let devices: string; + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } + } + ); } catch (err) { console.error(`Unregister observer failed, code is ${err.code},message is ${err.message}`); } @@ -4195,13 +4330,14 @@ off(event:'dataChange', type: SubscribeType, observer?: Callback<Array<str **示例:** ```js -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.info(`device= ${devices[i]} data changed`); - } -} try { - store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); + store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => { + let devices: string; + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } + } + ); } catch (err) { console.error(`Unregister observer failed, code is ${err.code},message is ${err.message}`); } @@ -4235,11 +4371,11 @@ off(event: string, interProcess: boolean, observer?: Callback\): void **示例:** ```js -function storeObserver() { - console.info(`storeObserver`); -} try { - store.off('storeObserver', false, storeObserver); + store.off('storeObserver', false, (storeObserver) => { + console.info(`storeObserver`); + } + ); } catch (err) { console.error(`Register observer failed, code is ${err.code},message is ${err.message}`); } @@ -4283,11 +4419,11 @@ store.emit('storeObserver'); 首先需要获取resultSet对象。 ```js -let resultSet = null; +let resultSet: relationalStore.ResultSet = null; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("AGE", 18); let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((result) => { +promise.then((result: relationalStore.ResultSet) => { resultSet = result; console.info(`resultSet columnNames: ${resultSet.columnNames}`); console.info(`resultSet columnCount: ${resultSet.columnCount}`); @@ -4341,7 +4477,6 @@ getColumnIndex(columnName: string): number **示例:** ```js -resultSet.goToFirstRow(); const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); @@ -4415,14 +4550,7 @@ goTo(offset:number): boolean **示例:** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise= store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goTo(1); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToRow @@ -4456,14 +4584,7 @@ goToRow(position: number): boolean **示例:** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToRow(5); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToFirstRow @@ -4492,14 +4613,7 @@ goToFirstRow(): boolean **示例:** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToFirstRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToLastRow @@ -4527,14 +4641,7 @@ goToLastRow(): boolean **示例:** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToLastRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToNextRow @@ -4562,14 +4669,7 @@ goToNextRow(): boolean **示例:** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToNextRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### goToPreviousRow @@ -4597,14 +4697,7 @@ goToPreviousRow(): boolean **示例:** ```js -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSet) => { resultSet.goToPreviousRow(); - resultSet.close(); -}).catch((err) => { - console.error(`query failed, code is ${err.code},message is ${err.message}`); -}); ``` ### getBlob @@ -4857,13 +4950,7 @@ close(): void **示例:** ```js -let predicatesClose = new relationalStore.RdbPredicates("EMPLOYEE"); -let promiseClose = store.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSet) => { resultSet.close(); -}).catch((err) => { - console.error(`resultset close failed, code is ${err.code},message is ${err.message}`); -}); ``` **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md b/zh-cn/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md index 18d326b90d190eb0c3313cbe17aa061bac1a8eb2..2b28024c44318c481d82ff1e759d4e2b4c28eb19 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-unifiedDataChannel.md @@ -1,4 +1,4 @@ -# @ohos.data.unifiedDataChannel(标准化数据通路) +# @ohos.data.unifiedDataChannel (标准化数据通路) 本模块为统一数据管理框架(Unified Data Management Framework,UDMF)的组成部分,针对多对多跨应用数据共享的不同业务场景提供了标准化的数据通路,提供了标准化的数据接入与读取接口。同时对文本、图片等数据类型提供了标准化定义,方便不同应用间进行数据交互,减少数据类型适配的工作量。 @@ -97,10 +97,10 @@ let records = unifiedData.getRecords(); for (let i = 0; i < records.length; i++) { let record = records[i]; if (record.getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { - let plainText = (record); + let plainText = record as unifiedDataChannel.PlainText; console.info(`textContent: ${plainText.textContent}`); } else if (record.getType() == uniformTypeDescriptor.UniformDataType.HYPERLINK) { - let hyperlink = (record); + let hyperlink = record as unifiedDataChannel.Hyperlink; console.info(`linkUrl: ${hyperlink.url}`); } } @@ -148,8 +148,8 @@ let unifiedData = new unifiedDataChannel.UnifiedData(text); let records = unifiedData.getRecords(); if (records[0].getType() == uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { - let plainText = (records[0]); - console.info(`textContent: ${plainText.textContent}`); + let plainText = records[0] as unifiedDataChannel.PlainText; + console.info(`textContent: ${plainText.textContent}`); } ``` @@ -426,19 +426,23 @@ let unifiedData = new unifiedDataChannel.UnifiedData(appItem); import image from '@ohos.multimedia.image'; // PixelMap类定义所在模块 const color = new ArrayBuffer(96); // 创建pixelmap对象 -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +let opts: image.InitializationOptions = { + editable: true, pixelFormat: 3, size: { + height: 4, width: 6 + } +} image.createPixelMap(color, opts, (error, pixelmap) => { - if(error) { - console.error('Failed to create pixelmap.'); - } else { - console.info('Succeeded in creating pixelmap.'); - let arrayBuf = new ArrayBuffer(pixelmap.getPixelBytesNumber()); - pixelmap.readPixelsToBuffer(arrayBuf); - let u8Array = new Uint8Array(arrayBuf); - let sdpixel = new unifiedDataChannel.SystemDefinedPixelMap(); - sdpixel.rawData = u8Array; - let unifiedData = new unifiedDataChannel.UnifiedData(sdpixel); - } + if (error) { + console.error('Failed to create pixelmap.'); + } else { + console.info('Succeeded in creating pixelmap.'); + let arrayBuf = new ArrayBuffer(pixelmap.getPixelBytesNumber()); + pixelmap.readPixelsToBuffer(arrayBuf); + let u8Array = new Uint8Array(arrayBuf); + let sdpixel = new unifiedDataChannel.SystemDefinedPixelMap(); + sdpixel.rawData = u8Array; + let unifiedData = new unifiedDataChannel.UnifiedData(sdpixel); + } }) ``` @@ -507,24 +511,26 @@ insertData(options: Options, data: UnifiedData, callback: AsyncCallback<strin ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - intention: unifiedDataChannel.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB } try { - unifiedDataChannel.insertData(options, unifiedData, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in inserting data. key = ${data}`); - } else { - console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); - } - }); -} catch(e) { - console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.insertData(options, unifiedData, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in inserting data. key = ${data}`); + } else { + console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); + } + }); + } catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `); } ``` @@ -554,22 +560,24 @@ insertData(options: Options, data: UnifiedData): Promise<string> ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - intention: unifiedDataChannel.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB } try { - unifiedDataChannel.insertData(options, unifiedData).then((data) => { - console.info(`Succeeded in inserting data. key = ${data}`); - }).catch((err) => { - console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Insert data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.insertData(options, unifiedData).then((data) => { + console.info(`Succeeded in inserting data. key = ${data}`); + }).catch((err: BusinessError) => { + console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `); } ``` @@ -593,25 +601,27 @@ updateData(options: Options, data: UnifiedData, callback: AsyncCallback<void& ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - unifiedDataChannel.updateData(options, unifiedData, (err) => { - if (err === undefined) { - console.info('Succeeded in updating data.'); - } else { - console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); - } - }); -} catch(e) { - console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.updateData(options, unifiedData, (err) => { + if (err === undefined) { + console.info('Succeeded in updating data.'); + } else { + console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); + } + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `); } ``` @@ -640,23 +650,25 @@ updateData(options: Options, data: UnifiedData): Promise<void> ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; +import { BusinessError } from '@ohos.base'; let plainText = new unifiedDataChannel.PlainText(); plainText.textContent = 'hello world!'; let unifiedData = new unifiedDataChannel.UnifiedData(plainText); -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - unifiedDataChannel.updateData(options, unifiedData).then(() => { - console.info('Succeeded in updating data.'); - }).catch((err) => { - console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Update data throws an exception. code is ${e.code},message is ${e.message} `); + unifiedDataChannel.updateData(options, unifiedData).then(() => { + console.info('Succeeded in updating data.'); + }).catch((err: BusinessError) => { + console.error(`Failed to update data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `); } ``` @@ -680,30 +692,32 @@ queryData(options: Options, callback: AsyncCallback<Array<UnifiedData>& ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - intention: unifiedDataChannel.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - unifiedDataChannel.queryData(options, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in querying data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } - } - } else { - console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + unifiedDataChannel.queryData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in querying data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); + } } - }); -} catch(e) { - console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); + } + } else { + console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + } + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `); } ``` @@ -732,28 +746,30 @@ queryData(options: Options): Promise<Array<UnifiedData>> ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - unifiedDataChannel.queryData(options).then((data) => { - console.info(`Succeeded in querying data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } + unifiedDataChannel.queryData(options).then((data) => { + console.info(`Succeeded in querying data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); } - }).catch((err) => { - console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Query data throws an exception. code is ${e.code},message is ${e.message} `); + } + } + }).catch((err: BusinessError) => { + console.error(`Failed to query data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `); } ``` @@ -777,30 +793,32 @@ deleteData(options: Options, callback: AsyncCallback<Array<UnifiedData> ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - intention: unifiedDataChannel.Intention.DATA_HUB +let options: unifiedDataChannel.Options = { + intention: unifiedDataChannel.Intention.DATA_HUB }; try { - unifiedDataChannel.deleteData(options, (err, data) => { - if (err === undefined) { - console.info(`Succeeded in deleting data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } - } - } else { - console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + unifiedDataChannel.deleteData(options, (err, data) => { + if (err === undefined) { + console.info(`Succeeded in deleting data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); + } } - }); -} catch(e) { - console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); + } + } else { + console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + } + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `); } ``` @@ -829,27 +847,29 @@ deleteData(options: Options): Promise<Array<UnifiedData>> ```ts import unifiedDataChannel from '@ohos.data.unifiedDataChannel'; import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +import { BusinessError } from '@ohos.base'; -let options = { - key: 'udmf://DataHub/com.ohos.test/0123456789' +let options: unifiedDataChannel.Options = { + key: 'udmf://DataHub/com.ohos.test/0123456789' }; try { - unifiedDataChannel.deleteData(options).then((data) => { - console.info(`Succeeded in deleting data. size = ${data.length}`); - for (let i = 0; i < data.length; i++) { - let records = data[i].getRecords(); - for (let j = 0; j < records.length; j++) { - if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { - let text = (records[j]); - console.info(`${i + 1}.${text.textContent}`); - } - } + unifiedDataChannel.deleteData(options).then((data) => { + console.info(`Succeeded in deleting data. size = ${data.length}`); + for (let i = 0; i < data.length; i++) { + let records = data[i].getRecords(); + for (let j = 0; j < records.length; j++) { + if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) { + let text = records[j] as unifiedDataChannel.PlainText; + console.info(`${i + 1}.${text.textContent}`); } - }).catch((err) => { - console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); - }); -} catch(e) { - console.error(`Delete data throws an exception. code is ${e.code},message is ${e.message} `); + } + } + }).catch((err: BusinessError) => { + console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + let error: BusinessError = e as BusinessError; + console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md b/zh-cn/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md index 96d1150c184e0ab7cb9dd81a696b9d9f00df1643..939a3be12a178028fd8fe7cffd5fb36024f37034 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-uniformTypeDescriptor.md @@ -1,4 +1,4 @@ -# @ohos.data.uniformTypeDescriptor(标准化数据定义与描述) +# @ohos.data.uniformTypeDescriptor (标准化数据定义与描述) 本模块描述OpenHarmony标准化数据类型的抽象定义。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-deque.md b/zh-cn/application-dev/reference/apis/js-apis-deque.md index 53b7c9b23add423f17a31e208aa1403502bccc66..78cd11dee5ca7ced1a340937bacc6ad3c3f23818 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-deque.md +++ b/zh-cn/application-dev/reference/apis/js-apis-deque.md @@ -51,7 +51,7 @@ Deque的构造函数。 **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); ``` ### insertFront @@ -79,12 +79,16 @@ insertFront(element: T): void **示例:** ```ts -let deque = new Deque(); +class C1 { + name: string + age: string +} +let deque: Deque | C1> = new Deque(); deque.insertFront("a"); deque.insertFront(1); let b = [1, 2, 3]; deque.insertFront(b); -let c = {name : "Dylon", age : "13"}; +let c: C1 = {name : "Dylon", age : "13"}; deque.insertFront(c); deque.insertFront(false); ``` @@ -114,12 +118,17 @@ insertEnd(element: T): void **示例:** ```ts -let deque = new Deque(); +class C1 { + name: string + age: string +} + +let deque: Deque | C1> = new Deque(); deque.insertEnd("a"); deque.insertEnd(1); let b = [1, 2, 3]; deque.insertEnd(b); -let c = {name : "Dylon", age : "13"}; +let c: C1 = {name : "Dylon", age : "13"}; deque.insertEnd(c); deque.insertEnd(false); ``` @@ -155,7 +164,7 @@ has(element: T): boolean **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); deque.insertFront("squirrel"); let result = deque.has("squirrel"); ``` @@ -185,7 +194,7 @@ popFirst(): T **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); deque.insertFront(2); deque.insertFront(4); deque.insertEnd(5); @@ -219,7 +228,7 @@ popLast(): T **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); deque.insertFront(2); deque.insertEnd(4); deque.insertFront(5); @@ -263,13 +272,13 @@ callbackfn的参数说明: **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); deque.insertFront(2); deque.insertEnd(4); deque.insertFront(5); deque.insertEnd(4); -deque.forEach((value, index) => { - console.log("value:" + value, "index:" + index); +deque.forEach((value: number, index: number) => { + console.log("value:" + value, "index:" + index); }); ``` @@ -298,7 +307,7 @@ getFirst(): T **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); deque.insertEnd(2); deque.insertEnd(4); deque.insertFront(5); @@ -331,7 +340,7 @@ getLast(): T **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); deque.insertFront(2); deque.insertFront(4); deque.insertFront(5); @@ -363,15 +372,16 @@ let result = deque.getLast(); **示例:** ```ts -let deque = new Deque(); +let deque: Deque = new Deque(); deque.insertFront(2); deque.insertFront(4); deque.insertFront(5); deque.insertFront(4); // 使用方法一: -for (let item of deque) { - console.log("value:" + item); +let nums: Array = Array.from(deque) +for (let item of nums) { + console.log("value:" + item); } // 使用方法二: diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index 3f28830d8aa18c113b4489ee756d409b6de959be..c32ed9763d199893a40e100894245e4fa04b95f4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -297,7 +297,8 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallbac import { BusinessError } from '@ohos.base'; const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + let accountInfo: account_distributedAccount.DistributedInfo = + {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfo(accountInfo, (err: BusinessError) => { if (err) { @@ -346,7 +347,8 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> import { BusinessError } from '@ohos.base'; const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + let accountInfo: account_distributedAccount.DistributedInfo = + {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfo(accountInfo).then(() => { console.log('setOsAccountDistributedInfo successfully'); @@ -391,7 +393,8 @@ setOsAccountDistributedInfoByLocalId(localId: number, distributedInfo: Distribut import { BusinessError } from '@ohos.base'; const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + let accountInfo: account_distributedAccount.DistributedInfo = + {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo, (err: BusinessError) => { if (err) { @@ -444,7 +447,8 @@ setOsAccountDistributedInfoByLocalId(localId: number, distributedInfo: Distribut import { BusinessError } from '@ohos.base'; const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + let accountInfo: account_distributedAccount.DistributedInfo = + {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; try { accountAbility.setOsAccountDistributedInfoByLocalId(100, accountInfo).then(() => { console.log('setOsAccountDistributedInfoByLocalId successfully'); @@ -482,7 +486,8 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall import { BusinessError } from '@ohos.base'; const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + let accountInfo: account_distributedAccount.DistributedInfo = + {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; accountAbility.updateOsAccountDistributedInfo(accountInfo, (err: BusinessError) => { if (err) { console.log('queryOsAccountDistributedInfo exception: ' + JSON.stringify(err)); @@ -521,7 +526,8 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> import { BusinessError } from '@ohos.base'; const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + let accountInfo: account_distributedAccount.DistributedInfo = + {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { console.log('updateOsAccountDistributedInfo successfully'); }).catch((err: BusinessError) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributedBundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-distributedBundleManager.md index 4bcaceb89bd653ad30a3b634672cf98bd3ca4844..96822823444a709c69529f144405f81c526763a1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedBundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedBundleManager.md @@ -59,13 +59,16 @@ getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback\ { + }, (err: BusinessError, data: distributedBundle.RemoteAbilityInfo) => { if (err) { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { @@ -115,15 +118,18 @@ getRemoteAbilityInfo(elementName: ElementName): Promise\; **示例:** ```ts +import distributedBundle from '@ohos.bundle.distributedBundleManager'; +import { BusinessError } from '@ohos.base'; + try { distributedBundle.getRemoteAbilityInfo( { deviceId: '1', bundleName: 'com.example.application', abilityName: 'EntryAbility' - }).then(data => { + }).then((data: distributedBundle.RemoteAbilityInfo) => { console.info('Operation succeed:' + JSON.stringify(data)); - }).catch(err => { + }).catch((err: BusinessError) => { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { @@ -164,6 +170,9 @@ getRemoteAbilityInfo(elementNames: Array\, callback: AsyncCallback\ **示例:** ```ts +import distributedBundle from '@ohos.bundle.distributedBundleManager'; +import { BusinessError } from '@ohos.base'; + try { distributedBundle.getRemoteAbilityInfo( [ @@ -177,7 +186,7 @@ try { bundleName: 'com.example.application2', abilityName: 'EntryAbility' } - ], (err, data) => { + ], (err: BusinessError, data: distributedBundle.RemoteAbilityInfo[]) => { if (err) { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { @@ -227,6 +236,9 @@ getRemoteAbilityInfo(elementNames: Array\): Promise\ { + ]).then((data: distributedBundle.RemoteAbilityInfo[]) => { console.info('Operation succeed:' + JSON.stringify(data)); - }).catch(err => { + }).catch((err: BusinessError) => { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { @@ -284,13 +296,16 @@ getRemoteAbilityInfo(elementName: ElementName, locale: string, callback: AsyncCa **示例:** ```ts +import distributedBundle from '@ohos.bundle.distributedBundleManager'; +import { BusinessError } from '@ohos.base'; + try { distributedBundle.getRemoteAbilityInfo( { deviceId: '1', bundleName: 'com.example.application', abilityName: 'EntryAbility' - }, 'zh-Hans-CN', (err, data) => { + }, 'zh-Hans-CN', (err: BusinessError, data: distributedBundle.RemoteAbilityInfo) => { if (err) { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { @@ -341,15 +356,18 @@ getRemoteAbilityInfo(elementName: ElementName, locale: string): Promise\ { + }, 'zh-Hans-CN').then((data: distributedBundle.RemoteAbilityInfo) => { console.info('Operation succeed:' + JSON.stringify(data)); - }).catch(err => { + }).catch((err: BusinessError) => { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { @@ -391,6 +409,9 @@ getRemoteAbilityInfo(elementNames: Array\, locale: string, callback **示例:** ```ts +import distributedBundle from '@ohos.bundle.distributedBundleManager'; +import { BusinessError } from '@ohos.base'; + try { distributedBundle.getRemoteAbilityInfo( [ @@ -404,7 +425,7 @@ try { bundleName: 'com.example.application2', abilityName: 'EntryAbility' } - ], 'zh-Hans-CN', (err, data) => { + ], 'zh-Hans-CN', (err: BusinessError, data: distributedBundle.RemoteAbilityInfo[]) => { if (err) { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { @@ -455,6 +476,9 @@ getRemoteAbilityInfo(elementNames: Array\, locale: string): Promise **示例:** ```ts +import distributedBundle from '@ohos.bundle.distributedBundleManager'; +import { BusinessError } from '@ohos.base'; + try { distributedBundle.getRemoteAbilityInfo( [ @@ -468,9 +492,9 @@ try { bundleName: 'com.example.application2', abilityName: 'EntryAbility' } - ], 'zh-Hans-CN').then(data => { + ], 'zh-Hans-CN').then((data: distributedBundle.RemoteAbilityInfo[]) => { console.info('Operation succeed:' + JSON.stringify(data)); - }).catch(err => { + }).catch((err: BusinessError) => { console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md index 3e629cc7644d65ab86b3760e232a52bef271688e..4c48afe9b0c47196d45d0a96c2e0951bd89c08a4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-file-picker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-file-picker.md @@ -8,8 +8,9 @@ ## 导入模块 -```js +```ts import picker from '@ohos.file.picker'; +import { BusinessError } from '@ohos.base'; ``` ## PhotoViewPicker @@ -47,15 +48,15 @@ select(option?: PhotoSelectOptions) : Promise<PhotoSelectResult> **示例:** ```ts -async function example() { +async example01() { try { let PhotoSelectOptions = new picker.PhotoSelectOptions(); PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.maxSelectNumber = 5; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => { + photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: picker.PhotoSelectResult) => { console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error('PhotoViewPicker.select failed with err: ' + err); }); } catch (err) { @@ -82,13 +83,13 @@ select(option: PhotoSelectOptions, callback: AsyncCallback<PhotoSelectResult& **示例:** ```ts -async function example() { - try { +async example02() { + try { let PhotoSelectOptions = new picker.PhotoSelectOptions(); PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.maxSelectNumber = 5; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.select(PhotoSelectOptions, (err, PhotoSelectResult) => { + photoPicker.select(PhotoSelectOptions, (err: BusinessError, PhotoSelectResult: picker.PhotoSelectResult) => { if (err) { console.error('PhotoViewPicker.select failed with err: ' + err); return; @@ -118,10 +119,10 @@ select(callback: AsyncCallback<PhotoSelectResult>) : void **示例:** ```ts -async function example() { - try { +async example03() { + try { let photoPicker = new picker.PhotoViewPicker(); - photoPicker.select((err, PhotoSelectResult) => { + photoPicker.select((err: BusinessError, PhotoSelectResult: picker.PhotoSelectResult) => { if (err) { console.error('PhotoViewPicker.select failed with err: ' + err); return; @@ -157,14 +158,14 @@ save(option?: PhotoSaveOptions) : Promise<Array<string>> **示例:** ```ts -async function example() { - try { +async example04() { + try { let PhotoSaveOptions = new picker.PhotoSaveOptions(); PhotoSaveOptions.newFileNames = ['PhotoViewPicker01.jpg', 'PhotoViewPicker01.mp4']; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult) => { + photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult: Array) => { console.info('PhotoViewPicker.save successfully, PhotoSaveResult uri: ' + JSON.stringify(PhotoSaveResult)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error('PhotoViewPicker.save failed with err: ' + err); }); } catch (err) { @@ -191,12 +192,12 @@ save(option: PhotoSaveOptions, callback: AsyncCallback<Array<string>> **示例:** ```ts -async function example() { +async example05() { try { let PhotoSaveOptions = new picker.PhotoSaveOptions(); PhotoSaveOptions.newFileNames = ['PhotoViewPicker02.jpg','PhotoViewPicker02.mp4']; let photoPicker = new picker.PhotoViewPicker(); - photoPicker.save(PhotoSaveOptions, (err, PhotoSaveResult) => { + photoPicker.save(PhotoSaveOptions, (err: BusinessError, PhotoSaveResult: Array) => { if (err) { console.error('PhotoViewPicker.save failed with err: ' + err); return; @@ -226,10 +227,10 @@ save(callback: AsyncCallback<Array<string>>) : void **示例:** ```ts -async function example() { +async example06() { try { let photoPicker = new picker.PhotoViewPicker(); - photoPicker.save((err, PhotoSaveResult) => { + photoPicker.save((err: BusinessError, PhotoSaveResult: Array) => { if (err) { console.error('PhotoViewPicker.save failed with err: ' + err); return; @@ -277,13 +278,13 @@ select(option?: DocumentSelectOptions) : Promise<Array<string>> **示例:** ```ts -async function example() { +async example07() { try { let DocumentSelectOptions = new picker.DocumentSelectOptions(); let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => { + documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult: Array) => { console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error('DocumentViewPicker.select failed with err: ' + err); }); } catch (err) { @@ -310,11 +311,11 @@ select(option: DocumentSelectOptions, callback: AsyncCallback<Array<string **示例:** ```ts -async function example() { +async example08() { try { let DocumentSelectOptions = new picker.DocumentSelectOptions(); let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select(DocumentSelectOptions, (err, DocumentSelectResult) => { + documentPicker.select(DocumentSelectOptions, (err: BusinessError, DocumentSelectResult: Array) => { if (err) { console.error('DocumentViewPicker.select failed with err: ' + err); return; @@ -344,10 +345,10 @@ select(callback: AsyncCallback<Array<string>>) : void **示例:** ```ts -async function example() { +async example09() { try { let documentPicker = new picker.DocumentViewPicker(); - documentPicker.select((err, DocumentSelectResult) => { + documentPicker.select((err: BusinessError, DocumentSelectResult: Array) => { if (err) { console.error('DocumentViewPicker.select failed with err: ' + err); return; @@ -384,14 +385,14 @@ save(option?: DocumentSaveOptions) : Promise<Array<string>> **示例:** ```ts -async function example() { +async example10() { try { let DocumentSaveOptions = new picker.DocumentSaveOptions(); DocumentSaveOptions.newFileNames = ['DocumentViewPicker01.txt']; let documentPicker = new picker.DocumentViewPicker(); - documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult) => { + documentPicker.save(DocumentSaveOptions).then((DocumentSaveResult: Array) => { console.info('DocumentViewPicker.save successfully, DocumentSaveResult uri: ' + JSON.stringify(DocumentSaveResult)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error('DocumentViewPicker.save failed with err: ' + err); }); } catch (err) { @@ -418,12 +419,12 @@ save(option: DocumentSaveOptions, callback: AsyncCallback<Array<string> **示例:** ```ts -async function example() { +async example11() { try { let DocumentSaveOptions = new picker.DocumentSaveOptions(); DocumentSaveOptions.newFileNames = ['DocumentViewPicker02.txt']; let documentPicker = new picker.DocumentViewPicker(); - documentPicker.save(DocumentSaveOptions, (err, DocumentSaveResult) => { + documentPicker.save(DocumentSaveOptions, (err: BusinessError, DocumentSaveResult: Array) => { if (err) { console.error('DocumentViewPicker.save failed with err: ' + err); return; @@ -453,10 +454,10 @@ save(callback: AsyncCallback<Array<string>>) : void **示例:** ```ts -async function example() { +async example12() { try { let documentPicker = new picker.DocumentViewPicker(); - documentPicker.save((err, DocumentSaveResult) => { + documentPicker.save((err: BusinessError, DocumentSaveResult: Array) => { if (err) { console.error('DocumentViewPicker.save failed with err: ' + err); return; @@ -504,13 +505,13 @@ select(option?: AudioSelectOptions) : Promise<Array<string>> **示例:** ```ts -async function example() { +async example13() { try { let AudioSelectOptions = new picker.AudioSelectOptions(); let audioPicker = new picker.AudioViewPicker(); - audioPicker.select(AudioSelectOptions).then((AudioSelectResult) => { + audioPicker.select(AudioSelectOptions).then((AudioSelectResult: Array) => { console.info('AudioViewPicker.select successfully, AudioSelectResult uri: ' + JSON.stringify(AudioSelectResult)); - }).catch((err) => { + }).catch((err: BusinessError) => { console.error('AudioViewPicker.select failed with err: ' + err); }); } catch (err) { @@ -537,11 +538,11 @@ select(option: AudioSelectOptions, callback: AsyncCallback<Array<string> **示例:** ```ts -async function example() { +async example14() { try { let AudioSelectOptions = new picker.AudioSelectOptions(); let audioPicker = new picker.AudioViewPicker(); - audioPicker.select(AudioSelectOptions, (err, AudioSelectResult) => { + audioPicker.select(AudioSelectOptions, (err: BusinessError, AudioSelectResult: Array) => { if (err) { console.error('AudioViewPicker.select failed with err: ' + err); return; @@ -571,10 +572,10 @@ select(callback: AsyncCallback<Array<string>>) : void **示例:** ```ts -async function example() { +async example15() { try { let audioPicker = new picker.AudioViewPicker(); - audioPicker.select((err, AudioSelectResult) => { + audioPicker.select((err: BusinessError, AudioSelectResult: Array) => { if (err) { console.error('AudioViewPicker.select failed with err: ' + err); return; @@ -610,14 +611,14 @@ save(option?: AudioSaveOptions) : Promise<Array<string>> **示例:** ```ts -async function example() { +async example16() { try { let AudioSaveOptions = new picker.AudioSaveOptions(); AudioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; let audioPicker = new picker.AudioViewPicker(); - audioPicker.save(AudioSaveOptions).then((AudioSaveResult) => { + audioPicker.save(AudioSaveOptions).then((AudioSaveResult: Array) => { console.info('AudioViewPicker.save successfully, AudioSaveResult uri: ' + JSON.stringify(AudioSaveResult)) - }).catch((err) => { + }).catch((err: BusinessError) => { console.error('AudioViewPicker.save failed with err: ' + err); }); } catch (err) { @@ -644,12 +645,12 @@ save(option: AudioSaveOptions, callback: AsyncCallback<Array<string>> **示例:** ```ts -async function example() { +async example17() { try { let AudioSaveOptions = new picker.AudioSaveOptions(); AudioSaveOptions.newFileNames = ['AudioViewPicker02.mp3']; let audioPicker = new picker.AudioViewPicker(); - audioPicker.save(AudioSaveOptions, (err, AudioSaveResult) => { + audioPicker.save(AudioSaveOptions, (err: BusinessError, AudioSaveResult: Array) => { if (err) { console.error('AudioViewPicker.save failed with err: ' + err); return; @@ -679,10 +680,10 @@ save(callback: AsyncCallback<Array<string>>) : void **示例:** ```ts -async function example() { +async example18() { try { let audioPicker = new picker.AudioViewPicker(); - audioPicker.save((err, AudioSaveResult) => { + audioPicker.save((err: BusinessError, AudioSaveResult: Array) => { if (err) { console.error('AudioViewPicker.save failed with err: ' + err); return; diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md index 09bc18d8ea3c14d32c02aeb1ea8245905569ef0e..3b7d17589fb1468c435cbf286913c2a3a3b94369 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md @@ -53,7 +53,7 @@ HashMap的构造函数。 **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); ``` @@ -82,7 +82,7 @@ isEmpty(): boolean **示例:** ```ts -const hashMap = new HashMap(); +const hashMap: HashMap = new HashMap(); let result = hashMap.isEmpty(); ``` @@ -118,7 +118,7 @@ hasKey(key: K): boolean **示例:** ```ts -let hashMap = new HashMap(); +const hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); let result = hashMap.hasKey("squirrel"); ``` @@ -155,7 +155,7 @@ hasValue(value: V): boolean **示例:** ```ts -let hashMap = new HashMap(); +const hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); let result = hashMap.hasValue(123); ``` @@ -192,7 +192,7 @@ get(key: K): V **示例:** ```ts -let hashMap = new HashMap(); +const hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.get("sparrow"); @@ -224,10 +224,10 @@ setAll(map: HashMap): void **示例:** ```ts -let hashMap = new HashMap(); +const hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); -let newHashMap = new HashMap(); +let newHashMap: HashMap = new HashMap(); newHashMap.set("newMap", 99); hashMap.setAll(newHashMap); ``` @@ -265,7 +265,7 @@ set(key: K, value: V): Object **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); let result = hashMap.set("squirrel", 123); ``` @@ -301,7 +301,7 @@ remove(key: K): V **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.remove("sparrow"); @@ -327,7 +327,7 @@ clear(): void **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); hashMap.clear(); @@ -359,14 +359,14 @@ keys(): IterableIterator<K> **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let iter = hashMap.keys(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value:" + temp.value); + temp = iter.next(); } ``` @@ -396,14 +396,14 @@ values(): IterableIterator<V> **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let iter = hashMap.values(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value:" + temp.value); + temp = iter.next(); } ``` @@ -440,7 +440,7 @@ replace(key: K, newValue: V): boolean **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("sparrow", 123); let result = hashMap.replace("sparrow", 357); ``` @@ -479,11 +479,11 @@ callbackfn的参数说明: **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("sparrow", 123); hashMap.set("gull", 357); -hashMap.forEach((value, key) => { - console.log("value:" + value, "key:" + key); +hashMap.forEach((value: number, key: string) => { + console.log("value:" + value, "key:" + key); }); ``` @@ -513,15 +513,15 @@ entries(): IterableIterator<[K, V]> **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let iter = hashMap.entries(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("key:" + temp[0]); - console.log("value:" + temp[1]); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("key:" + temp.value[0]); + console.log("value:" + temp.value[1]); + temp = iter.next(); } ``` @@ -550,7 +550,7 @@ while(temp != undefined) { **示例:** ```ts -let hashMap = new HashMap(); +let hashMap: HashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashset.md b/zh-cn/application-dev/reference/apis/js-apis-hashset.md index 271f205dd59956d677d97f1da26e51d3f41e6ce9..c005c709c1d7622e76a0daa2e5ec4023462a957f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashset.md @@ -33,7 +33,7 @@ import HashSet from '@ohos.util.HashSet'; **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add(1); hashSet.add(2); hashSet.add(3); @@ -61,7 +61,7 @@ HashSet的构造函数。 **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); ``` @@ -90,7 +90,7 @@ isEmpty(): boolean **示例:** ```ts -const hashSet = new HashSet(); +const hashSet: HashSet = new HashSet(); let result = hashSet.isEmpty(); ``` @@ -126,7 +126,7 @@ has(value: T): boolean **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add("squirrel"); let result = hashSet.has("squirrel"); ``` @@ -163,7 +163,7 @@ add(value: T): boolean **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); let result = hashSet.add("squirrel"); ``` @@ -199,7 +199,7 @@ remove(value: T): boolean **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); let result = hashSet.remove("sparrow"); @@ -225,7 +225,7 @@ clear(): void **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); hashSet.clear(); @@ -257,14 +257,14 @@ values(): IterableIterator<T> **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); let iter = hashSet.values(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value:" + temp.value); + temp = iter.next(); } ``` @@ -302,11 +302,11 @@ callbackfn的参数说明: **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add("sparrow"); hashSet.add("squirrel"); -hashSet.forEach((value, key) => { - console.log("value:" + value, "key:" + key); +hashSet.forEach((value: string, key: string) => { + console.log("value:" + value, "key:" + key); }); ``` @@ -335,15 +335,15 @@ entries(): IterableIterator<[T, T]> **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); let iter = hashSet.entries(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("key:" + temp[0]); - console.log("value:" + temp[1]); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("key:" + temp.value[0]); + console.log("value:" + temp.value[1]); + temp = iter.next(); } ``` @@ -373,20 +373,21 @@ while(temp != undefined) { **示例:** ```ts -let hashSet = new HashSet(); +let hashSet: HashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); // 使用方法一: -for (let item of hashSet) { +let val: Array = Array.from(hashSet.values()) +for (let item of val) { console.log("value: " + item); } // 使用方法二: let iter = hashSet[Symbol.iterator](); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value: " + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value: " + temp.value); + temp = iter.next(); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-i18n.md b/zh-cn/application-dev/reference/apis/js-apis-i18n.md index e0538ffcb03136c8f5c62a078f1955c388114881..1cfca139061a79fbf4b7c42c9f5a4a903ca80465 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-i18n.md +++ b/zh-cn/application-dev/reference/apis/js-apis-i18n.md @@ -11,7 +11,7 @@ ## 导入模块 -```js +```ts import I18n from '@ohos.i18n'; ``` @@ -49,11 +49,14 @@ static getDisplayCountry(country: string, locale: string, sentenceCase?: boolean | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let displayCountry: string = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China" } catch (error) { - console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -88,11 +91,14 @@ static getDisplayLanguage(language: string, locale: string, sentenceCase?: boole | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let displayLanguage: string = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese } catch(error) { - console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -119,11 +125,14 @@ static getSystemLanguages(): Array<string> | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let systemLanguages: Array = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ] } catch(error) { - console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -156,11 +165,14 @@ static getSystemCountries(language: string): Array<string> | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let systemCountries: Array = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ],共计240个国家或地区 } catch(error) { - console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -194,11 +206,14 @@ static isSuggested(language: string, region?: string): boolean | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let res: boolean = I18n.System.isSuggested('zh', 'CN'); // res = true } catch(error) { - console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -225,11 +240,14 @@ static getSystemLanguage(): string | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let systemLanguage: string = I18n.System.getSystemLanguage(); // systemLanguage为当前系统语言 } catch(error) { - console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -260,11 +278,14 @@ static setSystemLanguage(language: string): void | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { I18n.System.setSystemLanguage('zh'); // 设置系统当前语言为 "zh" } catch(error) { - console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -291,11 +312,14 @@ static getSystemRegion(): string | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let systemRegion: string = I18n.System.getSystemRegion(); // 获取系统当前地区设置 } catch(error) { - console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -326,11 +350,14 @@ static setSystemRegion(region: string): void | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { I18n.System.setSystemRegion('CN'); // 设置系统当前地区为 "CN" } catch(error) { - console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -357,11 +384,14 @@ static getSystemLocale(): string | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let systemLocale: string = I18n.System.getSystemLocale(); // 获取系统当前Locale } catch(error) { - console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -392,11 +422,14 @@ static setSystemLocale(locale: string): void | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { I18n.System.setSystemLocale('zh-CN'); // 设置系统当前Locale为 "zh-CN" } catch(error) { - console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -423,11 +456,14 @@ static is24HourClock(): boolean | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let is24HourClock: boolean = I18n.System.is24HourClock(); // 系统24小时开关是否开启 } catch(error) { - console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -458,12 +494,15 @@ static set24HourClock(option: boolean): void | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + // 将系统时间设置为24小时制 try { I18n.System.set24HourClock(true); } catch(error) { - console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -495,14 +534,17 @@ static addPreferredLanguage(language: string, index?: number): void | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + // 将语言zh-CN添加到系统偏好语言列表中 let language = 'zh-CN'; let index = 0; try { I18n.System.addPreferredLanguage(language, index); // 将zh-CN添加到系统偏好语言列表的第1位 } catch(error) { - console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -533,13 +575,16 @@ static removePreferredLanguage(index: number): void | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + // 删除系统偏好语言列表中的第一个偏好语言 let index: number = 0; try { I18n.System.removePreferredLanguage(index); } catch(error) { - console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -566,11 +611,14 @@ static getPreferredLanguageList(): Array<string> | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let preferredLanguageList: Array = I18n.System.getPreferredLanguageList(); // 获取系统当前偏好语言列表 } catch(error) { - console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -597,11 +645,14 @@ static getFirstPreferredLanguage(): string | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let firstPreferredLanguage: string = I18n.System.getFirstPreferredLanguage(); // 获取系统当前偏好语言列表中的第一个偏好语言 } catch(error) { - console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -628,11 +679,14 @@ static getAppPreferredLanguage(): string | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let appPreferredLanguage: string = I18n.System.getAppPreferredLanguage(); // 获取应用偏好语言 } catch(error) { - console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -664,10 +718,13 @@ static setUsingLocalDigit(flag: boolean): void **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { I18n.System.setUsingLocalDigit(true); // 打开本地化数字开关 } catch(error) { - console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -695,10 +752,13 @@ static getUsingLocalDigit(): boolean **示例:** ```ts + import { BusinessError } from '@ohos.base'; + try { let status: boolean = I18n.System.getUsingLocalDigit(); // 判断本地化数字开关是否打开 } catch(error) { - console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -724,7 +784,7 @@ isRTL(locale: string): boolean | boolean | true表示该locale从右至左显示语言;false表示该locale从左至右显示语言。 | **示例:** - ```js + ```ts I18n.isRTL("zh-CN");// 中文不是RTL语言,返回false I18n.isRTL("ar-EG");// 阿语是RTL语言,返回true ``` @@ -752,7 +812,7 @@ getCalendar(locale: string, type? : string): Calendar | [Calendar](#calendar8) | 日历对象。 | **示例:** - ```js + ```ts I18n.getCalendar("zh-Hans", "chinese"); // 获取中国农历日历对象 ``` @@ -775,7 +835,7 @@ setTime(date: Date): void | date | Date | 是 | 将要设置的日历对象的内部时间日期。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("en-US", "gregory"); let date: Date = new Date(2021, 10, 7, 8, 0, 0, 0); calendar.setTime(date); @@ -797,7 +857,7 @@ setTime(time: number): void | time | number | 是 | time为从1970.1.1 00:00:00 GMT逝去的毫秒数。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("en-US", "gregory"); calendar.setTime(10540800000); ``` @@ -823,7 +883,7 @@ set(year: number, month: number, date:number, hour?: number, minute?: number, se | second | number | 否 | 设置的秒。默认值:系统秒。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 ``` @@ -844,7 +904,7 @@ setTimeZone(timezone: string): void | timezone | string | 是 | 设置的时区id,如“Asia/Shanghai”。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); ``` @@ -865,7 +925,7 @@ getTimeZone(): string | string | 日历对象的时区id。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); let timezone: string = calendar.getTimeZone(); // timezone = "Asia/Shanghai" @@ -887,7 +947,7 @@ getFirstDayOfWeek(): number | number | 获取一周的起始日,1代表周日,7代表周六。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("en-US", "gregory"); let firstDayOfWeek: number = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` @@ -908,7 +968,7 @@ setFirstDayOfWeek(value: number): void | value | number | 是 | 设置一周的起始日,1代表周日,7代表周六。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); calendar.setFirstDayOfWeek(3); let firstDayOfWeek: number = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3 @@ -930,7 +990,7 @@ getMinimalDaysInFirstWeek(): number | number | 一年中第一周的最小天数。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); let minimalDaysInFirstWeek: number = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1 ``` @@ -951,7 +1011,7 @@ setMinimalDaysInFirstWeek(value: number): void | value | number | 是 | 一年中第一周的最小天数。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); calendar.setMinimalDaysInFirstWeek(3); let minimalDaysInFirstWeek: number = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 @@ -979,7 +1039,7 @@ get(field: string): number | number | 与field相关联的值,如当前Calendar对象的内部日期的年份为1990,get("year")返回1990。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 let hourOfDay: number = calendar.get("hour_of_day"); // hourOfDay = 8 @@ -1007,7 +1067,7 @@ getDisplayName(locale: string): string | string | 日历在locale所指示的区域的名字。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("en-US", "buddhist"); let calendarName: string = calendar.getDisplayName("zh"); // calendarName = "佛历" ``` @@ -1034,7 +1094,7 @@ isWeekend(date?: Date): boolean | boolean | 若判断指定日期为周末时,返回true,否则返回false。 | **示例:** - ```js + ```ts let calendar: I18n.Calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 calendar.isWeekend(); // false @@ -1062,7 +1122,7 @@ constructor(country: string, options?: PhoneNumberFormatOptions) | options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | 否 | 电话号码格式化对象的相关选项。默认值:NATIONAL。 | **示例:** - ```js + ```ts let option: I18n.PhoneNumberFormatOptions = {type: "E164"}; let phoneNumberFormat: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN", option); ``` @@ -1089,7 +1149,7 @@ isValidNumber(number: string): boolean | boolean | 返回true表示电话号码的格式正确,返回false表示电话号码的格式错误。 | **示例:** - ```js + ```ts let phonenumberfmt: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN"); let isValidNumber: boolean = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true ``` @@ -1116,7 +1176,7 @@ format(number: string): string | string | 格式化后的电话号码。 | **示例:** - ```js + ```ts let phonenumberfmt: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN"); let formattedPhoneNumber: string = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312" ``` @@ -1144,7 +1204,7 @@ getLocationName(number: string, locale: string): string | string | 电话号码归属地。 | **示例:** - ```js + ```ts let phonenumberfmt: I18n.PhoneNumberFormat = new I18n.PhoneNumberFormat("CN"); let locationName: string = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "广东省湛江市" ``` @@ -1194,7 +1254,7 @@ getInstance(locale?:string): IndexUtil | [IndexUtil](#indexutil8) | locale对应的IndexUtil对象。 | **示例:** - ```js + ```ts let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN"); ``` @@ -1217,7 +1277,7 @@ getIndexList(): Array<string> | Array<string> | 返回当前locale对应的索引列表。 | **示例:** - ```js + ```ts let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN"); // indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", // "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ] @@ -1240,7 +1300,7 @@ addLocale(locale: string): void | locale | string | 是 | 区域设置信息的字符串,包括语言以及可选的脚本和区域。 | **示例:** - ```js + ```ts let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN"); indexUtil.addLocale("en-US"); ``` @@ -1267,7 +1327,7 @@ getIndex(text: string): string | string | 输入文本对应的索引值。 | **示例:** - ```js + ```ts let indexUtil: I18n.IndexUtil = I18n.getInstance("zh-CN"); let index: string = indexUtil.getIndex("hi"); // index = "H" ``` @@ -1294,7 +1354,7 @@ getLineInstance(locale: string): BreakIterator | [BreakIterator](#breakiterator8) | 用于进行断句的处理器。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); ``` @@ -1317,7 +1377,7 @@ setLineBreakText(text: string): void | text | string | 是 | 指定BreakIterator进行断句的文本。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); // 设置短句文本 ``` @@ -1338,7 +1398,7 @@ getLineBreakText(): string | string | BreakIterator对象正在处理的文本 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let breakText: string = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit." @@ -1360,7 +1420,7 @@ current(): number | number | BreakIterator在当前所处理的文本中的位置。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let currentPos: number = iterator.current(); // currentPos = 0 @@ -1382,7 +1442,7 @@ first(): number | number | 被处理文本的第一个分割点的偏移量。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let firstPos: number = iterator.first(); // firstPos = 0 @@ -1404,7 +1464,7 @@ last(): number | number | 被处理的文本的最后一个分割点的偏移量 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let lastPos: number = iterator.last(); // lastPos = 27 @@ -1432,7 +1492,7 @@ next(index?: number): number | number | 返回移动了index个分割点后,当前BreakIterator在文本中的位置。若移动index个分割点后超出了所处理的文本的长度范围,返回-1。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let pos: number = iterator.first(); // pos = 0 @@ -1456,7 +1516,7 @@ previous(): number | number | 返回移动到前一个分割点后,当前BreakIterator在文本中的位置。若移动index个分割点后超出了所处理的文本的长度范围,返回-1。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let pos: number = iterator.first(); // pos = 0 @@ -1486,7 +1546,7 @@ following(offset: number): number | number | 返回BreakIterator移动后的位置,如果由offset所指定的位置的下一个分割点超出了文本的范围则返回-1。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let pos: number = iterator.following(0); // pos = 6 @@ -1516,7 +1576,7 @@ isBoundary(offset: number): boolean | boolean | 如果是一个分割点返回true, 否则返回false。 | **示例:** - ```js + ```ts let iterator: I18n.BreakIterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); let isBoundary: boolean = iterator.isBoundary(0); // isBoundary = true; @@ -1545,7 +1605,7 @@ getTimeZone(zoneID?: string): TimeZone | TimeZone | 时区ID对应的时区对象。 | **示例:** - ```js + ```ts let timezone: I18n.TimeZone = I18n.getTimeZone(); ``` @@ -1568,7 +1628,7 @@ getID(): string | string | 时区对象对应的时区ID。 | **示例:** - ```js + ```ts let timezone: I18n.TimeZone = I18n.getTimeZone(); let timezoneID: string = timezone.getID(); // timezoneID = "Asia/Shanghai" ``` @@ -1596,7 +1656,7 @@ getDisplayName(locale?: string, isDST?: boolean): string | string | 时区对象在指定区域的表示。 | **示例:** - ```js + ```ts let timezone: I18n.TimeZone = I18n.getTimeZone(); let timezoneName: string = timezone.getDisplayName("zh-CN", false); // timezoneName = "中国标准时间" ``` @@ -1617,7 +1677,7 @@ getRawOffset(): number | number | 时区对象表示的时区与UTC时区的偏差。 | **示例:** - ```js + ```ts let timezone: I18n.TimeZone = I18n.getTimeZone(); let offset: number = timezone.getRawOffset(); // offset = 28800000 ``` @@ -1638,7 +1698,7 @@ getOffset(date?: number): number | number | 某一时刻时区对象表示的时区与UTC时区的偏差。默认值:系统时间。 | **示例:** - ```js + ```ts let timezone: I18n.TimeZone = I18n.getTimeZone(); let offset: number = timezone.getOffset(1234567890); // offset = 28800000 ``` @@ -1760,7 +1820,7 @@ static getTimezonesByLocation(longitude: number, latitude: number): Array<Tim | Array<[TimeZone](#timezone)> | 时区对象的数组 | **示例:** - ```js + ```ts let timezoneArray: Array = I18n.TimeZone.getTimezonesByLocation(-118.1, 34.0); for (let i = 0; i < timezoneArray.length; i++) { let tzId: string = timezoneArray[i].getID(); @@ -1870,7 +1930,7 @@ static isDigit(char: string): boolean | boolean | 返回true表示输入的字符是数字,返回false表示输入的字符不是数字。 | **示例:** - ```js + ```ts let isdigit: boolean = I18n.Unicode.isDigit("1"); // isdigit = true ``` @@ -1896,7 +1956,7 @@ static isSpaceChar(char: string): boolean | boolean | 返回true表示输入的字符是空格符,返回false表示输入的字符不是空格符。 | **示例:** - ```js + ```ts let isspacechar: boolean = I18n.Unicode.isSpaceChar("a"); // isspacechar = false ``` @@ -1922,7 +1982,7 @@ static isWhitespace(char: string): boolean | boolean | 返回true表示输入的字符是空白符,返回false表示输入的字符不是空白符。 | **示例:** - ```js + ```ts let iswhitespace: boolean = I18n.Unicode.isWhitespace("a"); // iswhitespace = false ``` @@ -1948,7 +2008,7 @@ static isRTL(char: string): boolean | boolean | 返回true表示输入的字符是从右到左语言的字符,返回false表示输入的字符不是从右到左语言的字符。 | **示例:** - ```js + ```ts let isrtl: boolean = I18n.Unicode.isRTL("a"); // isrtl = false ``` @@ -1974,7 +2034,7 @@ static isIdeograph(char: string): boolean | boolean | 返回true表示输入的字符是表意文字,返回false表示输入的字符不是表意文字。 | **示例:** - ```js + ```ts let isideograph: boolean = I18n.Unicode.isIdeograph("a"); // isideograph = false ``` @@ -2000,7 +2060,7 @@ static isLetter(char: string): boolean | boolean | 返回true表示输入的字符是字母,返回false表示输入的字符不是字母。 | **示例:** - ```js + ```ts let isletter: boolean = I18n.Unicode.isLetter("a"); // isletter = true ``` @@ -2026,7 +2086,7 @@ static isLowerCase(char: string): boolean | boolean | 返回true表示输入的字符是小写字母,返回false表示输入的字符不是小写字母。 | **示例:** - ```js + ```ts let islowercase: boolean = I18n.Unicode.isLowerCase("a"); // islowercase = true ``` @@ -2052,7 +2112,7 @@ static isUpperCase(char: string): boolean | boolean | 返回true表示输入的字符是大写字母,返回false表示输入的字符不是大写字母。 | **示例:** - ```js + ```ts let isuppercase: boolean = I18n.Unicode.isUpperCase("a"); // isuppercase = false ``` @@ -2114,7 +2174,7 @@ static getType(char: string): string | U_OTHER_SYMBOL | U_OTHER_SYMBOL | 表示其它符号。 | **示例:** - ```js + ```ts let type: string = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER" ``` @@ -2146,8 +2206,10 @@ static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: | string | 按照toUnit的单位格式化后,得到的字符串。 | **示例:** - ```js - let res: string = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters + ```ts + let fromUnit: I18n.UnitInfo = {unit: "cup", measureSystem: "US"}; + let toUnit: I18n.UnitInfo = {unit: "liter", measureSystem: "SI"}; + let res: string = I18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, "en-US", "long"); // res = 236.588 liters ``` @@ -2172,7 +2234,7 @@ static getDateOrder(locale: string): string | string | 返回该区域年、月、日的排列顺序。 | **示例:** - ```js + ```ts let order: string = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" ``` @@ -2200,7 +2262,7 @@ static getInstance(mode: NormalizerMode): Normalizer | [Normalizer](#normalizer10) | 返回指定范式的文本正则化对象。 | **示例:** - ```js + ```ts let normalizer: I18n.Normalizer = I18n.Normalizer.getInstance(I18n.NormalizerMode.NFC); ``` @@ -2226,7 +2288,7 @@ normalize(text: string): string | string | 正则化后的字符串。 | **示例:** - ```js + ```ts let normalizer: I18n.Normalizer = I18n.Normalizer.getInstance(I18n.NormalizerMode.NFC); let normalizedText: string = normalizer.normalize('\u1E9B\u0323'); // normalizedText = \u1E9B\u0323 ``` @@ -2260,7 +2322,7 @@ constructor() **系统能力**:SystemCapability.Global.I18n **示例:** - ```js + ```ts let systemLocaleManager: I18n.SystemLocaleManager = new I18n.SystemLocaleManager(); ``` @@ -2297,7 +2359,9 @@ getLanguageInfoArray(languages: Array<string>, options?: SortOptions): Arr | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + // 当系统语言为zh-Hans,系统地区为CN,系统Locale为zh-Hans-CN时 let systemLocaleManager: I18n.SystemLocaleManager = new I18n.SystemLocaleManager(); let languages: string[] = ["zh-Hans", "en-US", "pt", "ar"]; @@ -2306,7 +2370,8 @@ getLanguageInfoArray(languages: Array<string>, options?: SortOptions): Arr // 排序后的语言顺序为: [zh-Hans, en-US, pt, ar] let sortedLanguages: Array = systemLocaleManager.getLanguageInfoArray(languages, sortOptions); } catch(error) { - console.error(`call systemLocaleManager.getLanguageInfoArray failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -2343,7 +2408,9 @@ getRegionInfoArray(regions: Array<string>, options?: SortOptions): Array&l | 890001 | param value not valid | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + // 当系统语言为zh-Hans,系统地区为CN,系统Locale为zh-Hans-CN时 let systemLocaleManager: I18n.SystemLocaleManager = new I18n.SystemLocaleManager(); let regions: string[] = ["CN", "US", "PT", "EG"]; @@ -2352,7 +2419,8 @@ getRegionInfoArray(regions: Array<string>, options?: SortOptions): Array&l // 排序后的地区顺序为: [CN, EG, US, PT] let sortedRegions: Array = systemLocaleManager.getRegionInfoArray(regions, sortOptions); } catch(error) { - console.error(`call systemLocaleManager.getRegionInfoArray failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -2373,7 +2441,9 @@ static getTimeZoneCityItemArray(): Array<TimeZoneCityItem> | Array<[TimeZoneCityItem](#timezonecityitem10)> | 排序后的时区城市组合信息的数组。 | **示例:** - ```js + ```ts + import { BusinessError } from '@ohos.base'; + try { let timeZoneCityItemArray: Array = I18n.SystemLocaleManager.getTimeZoneCityItemArray(); for (let i = 0; i < timeZoneCityItemArray.length; i++) { @@ -2381,7 +2451,8 @@ static getTimeZoneCityItemArray(): Array<TimeZoneCityItem> ", " + timeZoneCityItemArray[i].offset + "\r\n"); } } catch(error) { - console.error(`call SystemLocaleManager.getTimeZoneCityItemArray failed, error code: ${error.code}, message: ${error.message}.`); + let err: BusinessError = error as BusinessError; + console.error(`call System.getDisplayCountry failed, error code: ${err.code}, message: ${err.message}.`); } ``` @@ -2473,7 +2544,7 @@ getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): stri | string | 指定国家的本地化显示文本。 | **示例:** - ```js + ```ts let countryName: string = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true ``` @@ -2504,7 +2575,7 @@ getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): st | string | 指定语言的本地化显示文本。 | **示例:** - ```js + ```ts let languageName: string = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese" languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese" ``` @@ -2527,7 +2598,7 @@ getSystemLanguage(): string | string | 系统语言ID。 | **示例:** - ```js + ```ts let systemLanguage: string = I18n.getSystemLanguage(); // 返回当前系统语言 ``` @@ -2549,7 +2620,7 @@ getSystemRegion(): string | string | 系统地区ID。 | **示例:** - ```js + ```ts let region: string = I18n.getSystemRegion(); // 返回当前系统地区 ``` @@ -2571,7 +2642,7 @@ getSystemLocale(): string | string | 系统区域ID。 | **示例:** - ```js + ```ts let locale: string = I18n.getSystemLocale(); // 返回系统Locale ``` @@ -2593,7 +2664,7 @@ is24HourClock(): boolean | boolean | 返回true,表示系统24小时开关开启;返回false,表示系统24小时开关关闭。 | **示例:** - ```js + ```ts let is24HourClock: boolean = I18n.is24HourClock(); ``` @@ -2623,7 +2694,7 @@ set24HourClock(option: boolean): boolean | boolean | 返回true,表示修改成功;返回false,表示修改失败。 | **示例:** - ```js + ```ts // 将系统时间设置为24小时制 let success: boolean = I18n.set24HourClock(true); ``` @@ -2655,7 +2726,7 @@ addPreferredLanguage(language: string, index?: number): boolean | boolean | 返回true,表示添加成功;返回false,表示添加失败。 | **示例:** - ```js + ```ts // 将语言zh-CN添加到系统偏好语言列表中 let language: string = 'zh-CN'; let index: number = 0; @@ -2688,7 +2759,7 @@ removePreferredLanguage(index: number): boolean | boolean | 返回true,表示删除成功;返回false,表示删除失败。 | **示例:** - ```js + ```ts // 删除系统偏好语言列表中的第一个偏好语言 let index: number = 0; let success: boolean = I18n.removePreferredLanguage(index); @@ -2712,7 +2783,7 @@ getPreferredLanguageList(): Array<string> | Array<string> | 系统偏好语言列表。 | **示例:** - ```js + ```ts let preferredLanguageList: Array = I18n.getPreferredLanguageList(); // 获取系统偏好语言列表 ``` @@ -2734,7 +2805,7 @@ getFirstPreferredLanguage(): string | string | 偏好语言列表中的第一个语言。 | **示例:** - ```js + ```ts let firstPreferredLanguage: string = I18n.getFirstPreferredLanguage(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md index 0054d61a952a3b20a9e6be5bdc5b895e00c2c9b5..43ee71cf267cc6321af03b5a0b30344644924b21 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md @@ -15,9 +15,10 @@ WorkSchedulerExtensionContext可直接作为WorkSchedulerExtension的上下文 ```ts import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; +import workScheduler from '@ohos.resourceschedule.workScheduler'; class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { - onWorkStart(workInfo) { + onWorkStart(workInfo: workScheduler.WorkInfo) { let WorkSchedulerExtensionContext = this.context; // 获取WorkSchedulerExtensionContext } } diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index 0dcb39397c41e3063ff5934f98b1a6e3473c443f..2b81283439f6686e16ea8043eca6469fe9afd9d9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -102,11 +102,11 @@ let targetNames = ['com.ohos.xyz']; try { axContext.setTargetBundleName(targetNames).then(() => { console.info('set target bundle names success'); - }).catch((err) => { - console.error('failed to set target bundle names, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to set target bundle names, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to set target bundle names, because ${JSON.stringify(exception)}'); + console.error(`failed to set target bundle names, because ${JSON.stringify(exception)}`); }; ``` @@ -131,14 +131,14 @@ setTargetBundleName(targetNames: Array\, callback: AsyncCallback\) let targetNames = ['com.ohos.xyz']; try { axContext.setTargetBundleName(targetNames, (err, data) => { - if (err && err.code) { - console.error('failed to set target bundle names, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to set target bundle names, because ${JSON.stringify(err)}`); return; } console.info('set target bundle names success'); }); } catch (exception) { - console.error('failed to set target bundle names, because ${JSON.stringify(exception)}'); + console.error(`failed to set target bundle names, because ${JSON.stringify(exception)}`); }; ``` @@ -178,11 +178,11 @@ try { axContext.getFocusElement().then((data) => { focusElement = data; console.log('get focus element success'); - }).catch((err) => { - console.error('failed to get focus element, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to get focus element, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to get focus element, because ${JSON.stringify(exception)}'); + console.error(`failed to get focus element, because ${JSON.stringify(exception)}`); } ``` @@ -214,15 +214,15 @@ getFocusElement(callback: AsyncCallback\): void; let focusElement; try { axContext.getFocusElement((err, data) => { - if (err && err.code) { - console.error('failed to get focus element, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to get focus element, because ${JSON.stringify(err)}`); return; } focusElement = data; console.info('get focus element success'); }); } catch (exception) { - console.error('failed to get focus element, because ${JSON.stringify(exception)}'); + console.error(`failed to get focus element, because ${JSON.stringify(exception)}`); } ``` @@ -256,15 +256,15 @@ let focusElement; let isAccessibilityFocus = true; try { axContext.getFocusElement(isAccessibilityFocus, (err, data) => { - if (err && err.code) { - console.error('failed to get focus element, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to get focus element, because ${JSON.stringify(err)}`); return; } focusElement = data; console.info('get focus element success'); }); } catch (exception) { - console.error('failed to get focus element, because ${JSON.stringify(exception)}'); + console.error(`failed to get focus element, because ${JSON.stringify(exception)}`); } ``` ## AccessibilityExtensionContext.getWindowRootElement @@ -303,11 +303,11 @@ try { axContext.getWindowRootElement().then((data) => { rootElement = data; console.log('get root element of the window success'); - }).catch((err) => { - console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to get root element of the window, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to get root element of the window, ${JSON.stringify(exception)}'); + console.error(`failed to get root element of the window, ${JSON.stringify(exception)}`); } ``` @@ -339,15 +339,15 @@ getWindowRootElement(callback: AsyncCallback\): void; let rootElement; try { axContext.getWindowRootElement((err, data) => { - if (err && err.code) { - console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to get root element of the window, because ${JSON.stringify(err)}`); return; } rootElement = data; console.info('get root element of the window success'); }); } catch (exception) { - console.error('failed to get root element of the window, because ${JSON.stringify(exception)}'); + console.error(`failed to get root element of the window, because ${JSON.stringify(exception)}`); } ``` @@ -381,15 +381,15 @@ let rootElement; let windowId = 10; try { axContext.getWindowRootElement(windowId, (err, data) => { - if (err && err.code) { - console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to get root element of the window, because ${JSON.stringify(err)}`); return; } rootElement = data; console.info('get root element of the window success'); }); } catch (exception) { - console.error('failed to get root element of the window, because ${JSON.stringify(exception)}'); + console.error(`failed to get root element of the window, because ${JSON.stringify(exception)}`); } ``` @@ -429,11 +429,11 @@ try { axContext.getWindows().then((data) => { windows = data; console.log('get windows success'); - }).catch((err) => { - console.error('failed to get windows, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to get windows, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to get windows, because ${JSON.stringify(exception)}'); + console.error(`failed to get windows, because ${JSON.stringify(exception)}`); } ``` @@ -465,15 +465,15 @@ getWindows(callback: AsyncCallback\>): void; let windows; try { axContext.getWindows((err, data) => { - if (err && err.code) { - console.error('failed to get windows, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to get windows, because ${JSON.stringify(err)}`); return; } windows = data; console.info('get windows success'); }); } catch (exception) { - console.error('failed to get windows, because ${JSON.stringify(exception)}'); + console.error(`failed to get windows, because ${JSON.stringify(exception)}`); } ``` @@ -507,15 +507,15 @@ let windows; let displayId = 10; try { axContext.getWindows(displayId, (err, data) => { - if (err && err.code) { - console.error('failed to get windows, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to get windows, because ${JSON.stringify(err)}`); return; } windows = data; console.info('get windows success'); }); } catch (exception) { - console.error('failed to get windows, because ${JSON.stringify(exception)}'); + console.error(`failed to get windows, because ${JSON.stringify(exception)}`); } ``` @@ -560,11 +560,11 @@ try { } axContext.injectGesture(gesturePath).then(() => { console.info('inject gesture success'); - }).catch((err) => { - console.error('failed to inject gesture, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to inject gesture, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to inject gesture, because ${JSON.stringify(exception)}'); + console.error(`failed to inject gesture, because ${JSON.stringify(exception)}`); } ``` ## AccessibilityExtensionContext.injectGesture @@ -602,14 +602,14 @@ try { gesturePath.points.push(gesturePoint); } axContext.injectGesture(gesturePath, (err, data) => { - if (err && err.code) { - console.error('failed to inject gesture, because ${JSON.stringify(err)}'); + if (err) { + console.error(`failed to inject gesture, because ${JSON.stringify(err)}`); return; } console.info('inject gesture success'); }); } catch (exception) { - console.error('failed to inject gesture, because ${JSON.stringify(exception)}'); + console.error(`failed to inject gesture, because ${JSON.stringify(exception)}`); } ``` ## AccessibilityElement9+ @@ -639,8 +639,8 @@ let attributeNames; rootElement.attributeNames().then((data) => { console.log('get attribute names success'); attributeNames = data; -}).catch((err) => { - console.log('failed to get attribute names, because ${JSON.stringify(err)}'); +}).catch((err: object) => { + console.log(`failed to get attribute names, because ${JSON.stringify(err)}`); }); ``` ### attributeNames @@ -663,7 +663,7 @@ attributeNames\(callback: AsyncCallback\ let attributeNames; rootElement.attributeNames((err, data) => { if (err) { - console.error('failed to get attribute names, because ${JSON.stringify(err)}'); + console.error(`failed to get attribute names, because ${JSON.stringify(err)}`); return; } attributeNames = data; @@ -707,11 +707,11 @@ try { rootElement.attributeValue(attributeName).then((data) => { console.log('get attribute value by name success'); attributeValue = data; - }).catch((err) => { - console.error('failed to get attribute value, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to get attribute value, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); + console.error(`failed to get attribute value, because ${JSON.stringify(exception)}`); } ``` ### attributeValue @@ -746,14 +746,14 @@ let attributeName = 'name'; try { rootElement.attributeValue(attributeName, (err, data) => { if (err) { - console.error('failed to get attribute value, because ${JSON.stringify(err)}'); + console.error(`failed to get attribute value, because ${JSON.stringify(err)}`); return; } attributeValue = data; console.info('get attribute value success'); }); } catch (exception) { - console.error('failed to get attribute value, because ${JSON.stringify(exception)}'); + console.error(`failed to get attribute value, because ${JSON.stringify(exception)}`); } ``` ### actionNames @@ -777,8 +777,8 @@ let actionNames; rootElement.actionNames().then((data) => { console.log('get action names success'); actionNames = data; -}).catch((err) => { - console.error('failed to get action names because ${JSON.stringify(err)}'); +}).catch((err: object) => { + console.error(`failed to get action names because ${JSON.stringify(err)}`); }); ``` ### actionNames @@ -801,7 +801,7 @@ actionNames(callback: AsyncCallback\>): void; let actionNames; rootElement.actionNames((err, data) => { if (err) { - console.error('failed to get action names, because ${JSON.stringify(err)}'); + console.error(`failed to get action names, because ${JSON.stringify(err)}`); return; } actionNames = data; @@ -843,11 +843,11 @@ performAction(actionName: string, parameters?: object): Promise\; try { rootElement.performAction('action').then((data) => { console.info('perform action success'); - }).catch((err) => { - console.error('failed to perform action, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to perform action, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to perform action, because ${JSON.stringify(exception)}'); + console.error(`failed to perform action, because ${JSON.stringify(exception)}`); } ``` ### performAction @@ -879,13 +879,13 @@ performAction(actionName: string, callback: AsyncCallback\): void; try { rootElement.performAction('action', (err, data) => { if (err) { - console.error('failed to perform action, because ${JSON.stringify(err)}'); + console.error(`failed to perform action, because ${JSON.stringify(err)}`); return; } console.info('perform action success'); }); } catch (exception) { - console.error('failed to perform action, because ${JSON.stringify(exception)}'); + console.error(`failed to perform action, because ${JSON.stringify(exception)}`); } ``` ### performAction @@ -922,13 +922,13 @@ let parameters = { try { rootElement.performAction(actionName, parameters, (err, data) => { if (err) { - console.error('failed to perform action, because ${JSON.stringify(err)}'); + console.error(`failed to perform action, because ${JSON.stringify(err)}`); return; } console.info('perform action success'); }); } catch (exception) { - console.error('failed to perform action, because ${JSON.stringify(exception)}'); + console.error(`failed to perform action, because ${JSON.stringify(exception)}`); } ``` ### findElement('content') @@ -962,11 +962,11 @@ try { rootElement.findElement(type, condition).then((data) => { elements = data; console.log('find element success'); - }).catch((err) => { - console.error('failed to find element, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to find element, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to find element, because ${JSON.stringify(exception)}'); + console.error(`failed to find element, because ${JSON.stringify(exception)}`); } ``` ### findElement('content') @@ -994,14 +994,14 @@ let elements; try { rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element, because ${JSON.stringify(err)}'); + console.error(`failed to find element, because ${JSON.stringify(err)}`); return; } elements = data; console.info('find element success'); }); } catch (exception) { - console.error('failed to find element, because ${JSON.stringify(exception)}'); + console.error(`failed to find element, because ${JSON.stringify(exception)}`); } ``` ### findElement('focusType') @@ -1035,11 +1035,11 @@ try { rootElement.findElement(type, condition).then((data) => { element = data; console.log('find element success'); - }).catch((err) => { - console.error('failed to find element, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to find element, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to find element, because ${JSON.stringify(exception)}'); + console.error(`failed to find element, because ${JSON.stringify(exception)}`); } ``` ### findElement('focusType') @@ -1067,14 +1067,14 @@ let element; try { rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element, because ${JSON.stringify(err)}'); + console.error(`failed to find element, because ${JSON.stringify(err)}`); return; } element = data; console.info('find element success'); }); } catch (exception) { - console.error('failed to find element, because ${JSON.stringify(exception)}'); + console.error(`failed to find element, because ${JSON.stringify(exception)}`); } ``` ### findElement('focusDirection') @@ -1108,11 +1108,11 @@ try { rootElement.findElement(type, condition).then((data) => { element = data; console.log('find element success'); - }).catch((err) => { - console.error('failed to find element, because ${JSON.stringify(err)}'); + }).catch((err: object) => { + console.error(`failed to find element, because ${JSON.stringify(err)}`); }); } catch (exception) { - console.error('failed to find element, because ${JSON.stringify(exception)}'); + console.error(`failed to find element, because ${JSON.stringify(exception)}`); } ``` ### findElement('focusDirection') @@ -1140,13 +1140,13 @@ let elements; try { rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element, because ${JSON.stringify(err)}'); + console.error(`failed to find element, because ${JSON.stringify(err)}`); return; } elements = data; console.info('find element success'); }); } catch (exception) { - console.error('failed to find element, because ${JSON.stringify(exception)}'); + console.error(`failed to find element, because ${JSON.stringify(exception)}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md b/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md index 9b73e3ce7fc3e2d0689acfb896cea239d8bae90d..ca66792be26f9709d397610ce7da46281d47b5e2 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @@ -8,18 +8,15 @@ > > - 本模块接口为系统接口。 - ## 导入模块 - ```js import inputConsumer from '@ohos.multimodalInput.inputConsumer'; ``` - ## inputConsumer.on -on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): void +on(type: 'key', keyOptions: KeyOptions, callback: Callback<KeyOptions>): void 订阅组合按键,当满足条件的组合按键输入事件发生时,使用Callback异步方式上报组合按键数据。 @@ -29,7 +26,7 @@ on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): v | 参数名 | 类型 | 必填 | 说明 | | ---------- | -------------------------- | ---- | ---------------------------------------- | -| type | string | 是 | 事件类型,目前只支持”key“。 | +| type | string | 是 | 事件类型,目前仅支持'key'。 | | keyOptions | [KeyOptions](#keyoptions) | 是 | 组合键选项。 | | callback | Callback<KeyOptions> | 是 | 回调函数,当满足条件的组合按键输入事件发生时,异步上报组合按键数据。 | @@ -50,7 +47,7 @@ try { ## inputConsumer.off -off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): void +off(type: 'key', keyOptions: KeyOptions, callback?: Callback<KeyOptions>): void 取消订阅组合按键。 @@ -60,9 +57,9 @@ off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): | 参数名 | 类型 | 必填 | 说明 | | ---------- | -------------------------- | ---- | ------------------------------- | -| type | string | 是 | 事件类型,当前只支持”key“。 | +| type | string | 是 | 事件类型,当前仅支持 'key'。 | | keyOptions | [KeyOptions](#keyoptions) | 是 | 组合键选项。 | -| callback | Callback<KeyOptions> | 否 | 需要取消订阅的回调函数,若无此参数,则取消当前应用的组合键选项已订阅的所有回调函数。 | +| callback | Callback<KeyOptions> | 否 | 需要取消订阅的回调函数。若不填,则取消当前应用组合键选项已订阅的所有回调函数。 | **示例:** @@ -99,7 +96,6 @@ try { } ``` - ## KeyOptions 组合键选项。 @@ -108,7 +104,7 @@ try { | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | ---- | ---- | ------- | -| preKeys | Array\ | 是 | 否 | 前置按键集合,数量范围[0, 4],前置按键无顺序要求。 | -| finalKey | number | 是 | 否 | 最终按键,此项必填,最终按键触发上报回调函数。 | -| isFinalKeyDown | boolean | 是 | 否 | 最终按键状态。 | -| finalKeyDownDuration | number | 是 | 否 | 最终按键保持按下持续时间,为0时立即触发回调函数,大于0时,当isFinalKeyDown为true,则最终按键按下超过此时长后触发回调函数,当isFinalKeyDown为false,则最终按键按下到抬起时间小于此时长时触发回调函数。 | +| preKeys | Array\ | 是 | 否 | 前置按键集合,数量范围[0, 4],前置按键无顺序要求。
如组合按键Ctrl+Alt+A中,Ctrl+Alt称为前置按键。 | +| finalKey | number | 是 | 否 | 最终按键,此项必填,最终按键触发上报回调函数。
如组合按键Ctrl+Alt+A中,A称为最终按键按键。 | +| isFinalKeyDown | boolean | 是 | 否 | 最终按键状态。
ture表示按键按下,false表示按键抬起。 | +| finalKeyDownDuration | number | 是 | 否 | 最终按键保持按下持续时间,单位为微秒(μs)。
当finalKeyDownDuration为0时,立即触发回调函数。
当finalKeyDownDuration大于0时,isFinalKeyDown为true,则最终按键按下超过设置时长后触发回调函数;isFinalKeyDown为false,则最终按键按下到抬起时间小于设置时长时触发回调函数。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputevent.md b/zh-cn/application-dev/reference/apis/js-apis-inputevent.md index 4a36d8191d6ad5c9ffc63b990777c64bc5770308..83e45be5b00e36da99a8a1c7e25a775861755b64 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputevent.md @@ -22,6 +22,6 @@ import InputEvent from '@ohos.multimodalInput.inputEvent'; | ---------- | ------ | ---- | ---- | -------------- | | id | number | 是 | 否 | 事件id | | deviceId | number | 是 | 否 | 上报输入事件的设备id | -| actionTime | number | 是 | 否 | 输入事件的上报时间 | +| actionTime | number | 是 | 否 | 上报输入事件的时间 | | screenId | number | 是 | 否 | 目标屏幕id | | windowId | number | 是 | 否 | 目标窗口id | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md b/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md index e5f61c963a42b5d54ab860dd724e9e0111dfef09..788500960d79c5cf3cd5f19c27bf32e5e036e199 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @@ -8,20 +8,17 @@ > > - 本模块接口为系统接口。 - ## 导入模块 - ```js import inputEventClient from '@ohos.multimodalInput.inputEventClient'; ``` - ## inputEventClient.injectEvent injectEvent({KeyEvent: KeyEvent}): void -按键注入,当前仅支持返回键(键值2)注入。 +按键注入,当前仅支持返回键/KEYCODE_BACK(键码值2)注入。 **系统能力:** SystemCapability.MultimodalInput.Input.InputSimulator @@ -55,7 +52,6 @@ try { } ``` - ## KeyEvent 按键注入描述信息。 @@ -64,8 +60,8 @@ try { | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | ---- | ---- | ------- | -| isPressed | boolean | 是 | 否 | 按键是否按下。 | -| keyCode | number | 是 | 否 | 按键键值,当前只支持back键。 | -| keyDownDuration | number | 是 | 否 | 按键按下持续时间。 | -| isIntercepted | boolean | 是 | 否 | 按键是否可以被拦截。 | +| isPressed | boolean | 是 | 否 | 按键是否按下。
ture表示按键按下,false表示按键抬起。 | +| keyCode | number | 是 | 否 | 按键键码值。当前仅支持返回键/KEYCODE_BACK键。 | +| keyDownDuration | number | 是 | 否 | 按键按下持续时间,单位为微秒(μs)。 | +| isIntercepted | boolean | 是 | 否 | 按键是否可以被拦截。
ture表示可以被拦截,false表示不可被拦截。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md b/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md index a444ba50565a8415d49443d747f94cd640019ae5..c690ff89eeb352f8b6b089e749d2874ef6f488e7 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,27 +1,26 @@ # @ohos.multimodalInput.inputMonitor (输入监听) -输入监听模块,提供了监听输入设备事件(当前支持触屏、鼠标和触控板手势)的能力。 +输入监听模块,提供了监听输入设备事件的能力。输入设备事件当前包括触摸(触屏)事件、鼠标输入事件和触控板输入事件。 -> **说明:** +>**说明:** > -> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +>- 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > -> - 本模块接口均为系统接口。 - +>- 本模块接口均为系统接口。 +> +>- 文档中“全局”表示整个触控屏或触控板。如监听全局触摸事件,表示触摸触控板任何位置时,整个触控板的触摸事件均被监听。 ## 导入模块 - ```js import inputMonitor from '@ohos.multimodalInput.inputMonitor'; ``` - ## inputMonitor.on('touch') on(type: 'touch', receiver: TouchEventReceiver): void -监听全局触屏事件。 +监听全局触摸(触屏)事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -31,7 +30,7 @@ on(type: 'touch', receiver: TouchEventReceiver): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“touch”。 | +| type | string | 是 | 输入设备事件类型,取值'touch'。 | | receiver | [TouchEventReceiver](#toucheventreceiver) | 是 | 回调函数,异步上报触摸屏输入事件。 | **示例:** @@ -61,7 +60,7 @@ on(type: 'mouse', receiver: Callback<MouseEvent>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“mouse”。 | +| type | string | 是 | 输入设备事件类型,取值'mouse'。 | | receiver | Callback<MouseEvent> | 是 | 回调函数,异步上报鼠标输入事件。 | **示例:** @@ -77,13 +76,11 @@ try { } ``` - - ## inputMonitor.off('touch') off(type: 'touch', receiver?: TouchEventReceiver): void -取消监听全局触屏事件。 +取消监听全局触摸(触屏)事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -93,8 +90,8 @@ off(type: 'touch', receiver?: TouchEventReceiver): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“touch”。 | -| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | +| type | string | 是 | 输入设备事件类型,取值'touch'。 | +| receiver | [TouchEventReceiver](#toucheventreceiver) | 否 | 需要取消监听的回调函数。若不填,则取消当前应用监听的所有回调函数。 | **示例:** @@ -142,8 +139,8 @@ off(type: 'mouse', receiver?: Callback<MouseEvent>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“mouse”。 | -| receiver | Callback<MouseEvent> | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | +| type | string | 是 | 输入设备事件类型,取值'mouse'。 | +| receiver | Callback<MouseEvent> | 否 | 需要取消监听的回调函数。若不填,则取消当前应用监听的所有回调函数。 | **示例:** @@ -179,7 +176,7 @@ try { ## TouchEventReceiver -触摸输入事件的回调函数。 +触摸(触屏)输入事件的回调函数。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -216,7 +213,7 @@ try { on(type: 'pinch', receiver: Callback<[Pinch](js-apis-multimodalinput-gestureevent.md#pinch)>): void -监听全局的触控板捏合事件。 +监听全局触控板的捏合事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -226,7 +223,7 @@ on(type: 'pinch', receiver: Callback<[Pinch](js-apis-multimodalinput-gesturee | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“pinch”。 | +| type | string | 是 | 输入设备事件类型,取值'pinch'。 | | receiver | Callback<[Pinch](js-apis-multimodalinput-gestureevent.md#pinch)> | 是 | 回调函数,异步上报捏合输入事件。 | **示例:** @@ -246,7 +243,7 @@ try { off(type: 'pinch', receiver?: Callback<[Pinch](js-apis-multimodalinput-gestureevent.md#pinch)>): void -取消监听全局的触控板捏合事件。 +取消监听全局触控板的捏合事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -256,8 +253,8 @@ off(type: 'pinch', receiver?: Callback<[Pinch](js-apis-multimodalinput-gestur | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“pinch”。 | -| receiver | Callback<[Pinch](js-apis-multimodalinput-gestureevent.md#pinch)> | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | +| type | string | 是 | 输入设备事件类型,取值'pinch'。 | +| receiver | Callback<[Pinch](js-apis-multimodalinput-gestureevent.md#pinch)> | 否 | 需要取消监听的回调函数。若不填,则取消当前应用监听的所有回调函数。 | **示例:** @@ -295,7 +292,7 @@ try { on(type: 'threeFingersSwipe', receiver: Callback<[ThreeFingersSwipe](js-apis-multimodalinput-gestureevent.md#threefingersswipe)>): void -监听全局的触控板三指滑动事件。 +监听全局触控板的三指滑动事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -305,7 +302,7 @@ on(type: 'threeFingersSwipe', receiver: Callback<[ThreeFingersSwipe](js-apis- | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“threeFingersSwipe”。 | +| type | string | 是 | 输入设备事件类型,取值'threeFingersSwipe'。 | | receiver | Callback<[ThreeFingersSwipe](js-apis-multimodalinput-gestureevent.md#threefingersswipe)> | 是 | 回调函数,异步上报三指滑动输入事件。 | **示例:** @@ -325,7 +322,7 @@ try { off(type: 'threeFingersSwipe', receiver?: Callback<[ThreeFingersSwipe](js-apis-multimodalinput-gestureevent.md#threefingersswipe)>): void -取消监听全局的触控板三指滑动事件。 +取消监听全局触控板的三指滑动事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -335,8 +332,8 @@ off(type: 'threeFingersSwipe', receiver?: Callback<[ThreeFingersSwipe](js-api | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“threeFingersSwipe”。 | -| receiver | Callback<[ThreeFingersSwipe](js-apis-multimodalinput-gestureevent.md#threefingersswipe)> | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | +| type | string | 是 | 输入设备事件类型,取值'threeFingersSwipe'。 | +| receiver | Callback<[ThreeFingersSwipe](js-apis-multimodalinput-gestureevent.md#threefingersswipe)> | 否 | 需要取消监听的回调函数。若不填,则取消当前应用监听的所有回调函数。 | **示例:** @@ -374,7 +371,7 @@ try { on(type: 'fourFingersSwipe', receiver: Callback<[FourFingersSwipe](js-apis-multimodalinput-gestureevent.md#fourfingersswipe)>): void -监听全局的触控板四指滑动事件。 +监听全局触控板的四指滑动事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -384,7 +381,7 @@ on(type: 'fourFingersSwipe', receiver: Callback<[FourFingersSwipe](js-apis-mu | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“fourFingersSwipe”。 | +| type | string | 是 | 输入设备事件类型,取值'fourFingersSwipe'。 | | receiver | Callback<[FourFingersSwipe](js-apis-multimodalinput-gestureevent.md#fourfingersswipe)> | 是 | 回调函数,异步上报四指滑动输入事件。 | **示例:** @@ -404,7 +401,7 @@ try { off(type: 'fourFingersSwipe', receiver?: Callback<[FourFingersSwipe](js-apis-multimodalinput-gestureevent.md#fourfingersswipe)>): void -取消监听全局的触控板四指滑动事件。 +取消监听全局触控板的四指滑动事件。 **需要权限:** ohos.permission.INPUT_MONITORING @@ -414,8 +411,8 @@ off(type: 'fourFingersSwipe', receiver?: Callback<[FourFingersSwipe](js-apis- | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ------------------- | -| type | string | 是 | 输入设备事件类型,取值“fourFingersSwipe”。 | -| receiver | Callback<[FourFingersSwipe](js-apis-multimodalinput-gestureevent.md#fourfingersswipe)> | 否 | 需要取消监听的回调函数,若无此参数,则取消当前应用监听的所有回调函数。 | +| type | string | 是 | 输入设备事件类型,取值'fourFingersSwipe'。 | +| receiver | Callback<[FourFingersSwipe](js-apis-multimodalinput-gestureevent.md#fourfingersswipe)> | 否 | 需要取消监听的回调函数。若不填,则取消当前应用监听的所有回调函数。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-installer.md b/zh-cn/application-dev/reference/apis/js-apis-installer.md index 95ea29e2378213b65cb0521c1aa99cdf72d5ff61..64dc39275f9eb4b4e8a90dfb618a91549a283137 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-installer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-installer.md @@ -46,9 +46,10 @@ getBundleInstaller(callback: AsyncCallback\): void; ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; try { - installer.getBundleInstaller((err, data) => { + installer.getBundleInstaller((err: BusinessError, data: installer.BundleInstaller) => { if (err) { console.error('getBundleInstaller failed:' + err.message); } else { @@ -79,11 +80,12 @@ getBundleInstaller(): Promise\; ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; try { - installer.getBundleInstaller().then((data) => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { console.info('getBundleInstaller successfully.'); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -176,23 +178,25 @@ install(hapFilePaths: Array<string>, installParam: InstallParam, callback: ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; -let installParam = { +let installParam: installer.InstallParam = { userId: 100, isKeepData: false, installFlag: 1, }; try { - installer.getBundleInstaller().then(data => { - data.install(hapFilePaths, installParam, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.install(hapFilePaths, installParam, (err: BusinessError) => { if (err) { console.error('install failed:' + err.message); } else { console.info('install successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -254,18 +258,20 @@ install(hapFilePaths: Array<string>, callback: AsyncCallback<void>): ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; try { - installer.getBundleInstaller().then(data => { - data.install(hapFilePaths, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.install(hapFilePaths, (err: BusinessError) => { if (err) { console.error('install failed:' + err.message); } else { console.info('install successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -336,22 +342,24 @@ install(hapFilePaths: Array\, installParam?: InstallParam) : Promise\ { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { data.install(hapFilePaths, installParam) - .then((data) => { + .then((data: void) => { console.info('install successfully: ' + JSON.stringify(data)); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('install failed:' + error.message); }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -395,23 +403,25 @@ uninstall(bundleName: string, installParam: InstallParam, callback: AsyncCallbac ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let bundleName = 'com.ohos.demo'; -let installParam = { +let installParam: installer.InstallParam = { userId: 100, isKeepData: false, installFlag: 1 }; try { - installer.getBundleInstaller().then(data => { - data.uninstall(bundleName, installParam, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.uninstall(bundleName, installParam, (err: BusinessError) => { if (err) { console.error('uninstall failed:' + err.message); } else { console.info('uninstall successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -453,18 +463,20 @@ uninstall(bundleName: string, callback: AsyncCallback<void>): void; ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let bundleName = 'com.ohos.demo'; try { - installer.getBundleInstaller().then(data => { - data.uninstall(bundleName, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.uninstall(bundleName, (err: BusinessError) => { if (err) { console.error('uninstall failed:' + err.message); } else { console.info('uninstall successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -511,22 +523,24 @@ uninstall(bundleName: string, installParam?: InstallParam) : Promise\; **示例:** ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let bundleName = 'com.ohos.demo'; -let installParam = { +let installParam: installer.InstallParam = { userId: 100, isKeepData: false, installFlag: 1, }; try { - installer.getBundleInstaller().then(data => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { data.uninstall(bundleName, installParam) - .then((data) => { + .then((data: void) => { console.info('uninstall successfully: ' + JSON.stringify(data)); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('uninstall failed:' + error.message); }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -567,23 +581,25 @@ recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback& ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let bundleName = 'com.ohos.demo'; -let installParam = { +let installParam: installer.InstallParam = { userId: 100, isKeepData: false, installFlag: 1 }; try { - installer.getBundleInstaller().then(data => { - data.recover(bundleName, installParam, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.recover(bundleName, installParam, (err: BusinessError) => { if (err) { console.error('recover failed:' + err.message); } else { console.info('recover successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -623,18 +639,20 @@ recover(bundleName: string, callback: AsyncCallback<void>): void; ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let bundleName = 'com.ohos.demo'; try { - installer.getBundleInstaller().then(data => { - data.recover(bundleName, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.recover(bundleName, (err: BusinessError) => { if (err) { console.error('recover failed:' + err.message); } else { console.info('recover successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -679,22 +697,24 @@ recover(bundleName: string, installParam?: InstallParam) : Promise\; **示例:** ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let bundleName = 'com.ohos.demo'; -let installParam = { +let installParam: installer.InstallParam = { userId: 100, isKeepData: false, installFlag: 1, }; try { - installer.getBundleInstaller().then(data => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { data.recover(bundleName, installParam) - .then((data) => { + .then((data: void) => { console.info('recover successfully: ' + JSON.stringify(data)); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('recover failed:' + error.message); }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -735,20 +755,22 @@ uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : voi ```ts import installer from '@ohos.bundle.installer'; -let uninstallParam = { - bundleName : "com.ohos.demo", +import { BusinessError } from '@ohos.base'; + +let uninstallParam: installer.UninstallParam = { + bundleName: "com.ohos.demo", }; try { - installer.getBundleInstaller().then(data => { - data.uninstall(uninstallParam, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.uninstall(uninstallParam, (err: BusinessError) => { if (err) { console.error('uninstall failed:' + err.message); } else { console.info('uninstall successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -794,20 +816,22 @@ uninstall(uninstallParam: UninstallParam) : Promise\; ```ts import installer from '@ohos.bundle.installer'; -let uninstallParam = { - bundleName : "com.ohos.demo", +import { BusinessError } from '@ohos.base'; + +let uninstallParam: installer.UninstallParam = { + bundleName: "com.ohos.demo", }; try { - installer.getBundleInstaller().then(data => { - data.uninstall(uninstallParam, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.uninstall(uninstallParam, (err: BusinessError) => { if (err) { console.error('uninstall failed:' + err.message); } else { console.info('uninstall successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -864,23 +888,25 @@ updateBundleForSelf(hapFilePaths: Array\, installParam: InstallParam, c ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; -let installParam = { +let installParam: installer.InstallParam = { userId: 100, isKeepData: false, installFlag: 1, }; try { - installer.getBundleInstaller().then(data => { - data.updateBundleForSelf(hapFilePaths, installParam, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.updateBundleForSelf(hapFilePaths, installParam, (err: BusinessError) => { if (err) { console.error('updateBundleForSelf failed:' + err.message); } else { console.info('updateBundleForSelf successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -935,18 +961,20 @@ updateBundleForSelf(hapFilePaths: Array\, callback: AsyncCallback\ { - data.updateBundleForSelf(hapFilePaths, err => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { + data.updateBundleForSelf(hapFilePaths, (err: BusinessError) => { if (err) { console.error('updateBundleForSelf failed:' + err.message); } else { console.info('updateBundleForSelf successfully.'); } }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { @@ -1002,22 +1030,24 @@ updateBundleForSelf(hapFilePaths: Array\, installParam?: InstallParam): ```ts import installer from '@ohos.bundle.installer'; +import { BusinessError } from '@ohos.base'; + let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; -let installParam = { +let installParam: installer.InstallParam = { userId: 100, isKeepData: false, installFlag: 1, }; try { - installer.getBundleInstaller().then(data => { + installer.getBundleInstaller().then((data: installer.BundleInstaller) => { data.updateBundleForSelf(hapFilePaths, installParam) - .then((data) => { + .then((data: void) => { console.info('updateBundleForSelf successfully: ' + JSON.stringify(data)); - }).catch((error) => { + }).catch((error: BusinessError) => { console.error('updateBundleForSelf failed:' + error.message); }); - }).catch(error => { + }).catch((error: BusinessError) => { console.error('getBundleInstaller failed. Cause: ' + error.message); }); } catch (error) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-keycode.md b/zh-cn/application-dev/reference/apis/js-apis-keycode.md index ec2c089f1f5a158c50a013682842892e1e702eea..26e851cb21d0afd811e46a9f80f2abf6f017cf4c 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-keycode.md +++ b/zh-cn/application-dev/reference/apis/js-apis-keycode.md @@ -1,8 +1,9 @@ # @ohos.multimodalInput.keyCode (键值) -按键设备键值。 +按键设备的键码值,按键设备包括键盘、电源键、拍照键等。 -> **说明:** +> **说明:** +> > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -13,7 +14,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; ## KeyCode -按键键码值。 +键码值。 **系统能力**:SystemCapability.MultimodalInput.Input.Core @@ -23,20 +24,20 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | KEYCODE_UNKNOWN | -1 | 未知按键 | | KEYCODE_HOME | 1 | 功能(Home)键 | | KEYCODE_BACK | 2 | 返回键 | -| KEYCODE_MEDIA_PLAY_PAUSE | 10 | 多媒体键 播放/暂停 | -| KEYCODE_MEDIA_STOP | 11 | 多媒体键 停止 | -| KEYCODE_MEDIA_NEXT | 12 | 多媒体键 下一首 | -| KEYCODE_MEDIA_PREVIOUS | 13 | 多媒体键 上一首 | -| KEYCODE_MEDIA_REWIND | 14 | 多媒体键 快退 | -| KEYCODE_MEDIA_FAST_FORWARD | 15 | 多媒体键 快进 | +| KEYCODE_MEDIA_PLAY_PAUSE | 10 | 多媒体键:播放/暂停 | +| KEYCODE_MEDIA_STOP | 11 | 多媒体键:停止 | +| KEYCODE_MEDIA_NEXT | 12 | 多媒体键:下一首 | +| KEYCODE_MEDIA_PREVIOUS | 13 | 多媒体键:上一首 | +| KEYCODE_MEDIA_REWIND | 14 | 多媒体键:快退 | +| KEYCODE_MEDIA_FAST_FORWARD | 15 | 多媒体键:快进 | | KEYCODE_VOLUME_UP | 16 | 音量增加键 | | KEYCODE_VOLUME_DOWN | 17 | 音量减小键 | | KEYCODE_POWER | 18 | 电源键 | | KEYCODE_CAMERA | 19 | 拍照键 | | KEYCODE_VOLUME_MUTE | 22 | 扬声器静音键 | | KEYCODE_MUTE | 23 | 话筒静音键 | -| KEYCODE_BRIGHTNESS_UP | 40 | 亮度调节按键 调亮 | -| KEYCODE_BRIGHTNESS_DOWN | 41 | 亮度调节按键 调暗 | +| KEYCODE_BRIGHTNESS_UP | 40 | 亮度调节按键:调亮 | +| KEYCODE_BRIGHTNESS_DOWN | 41 | 亮度调节按键:调暗 | | KEYCODE_0 | 2000 | 按键'0' | | KEYCODE_1 | 2001 | 按键'1' | | KEYCODE_2 | 2002 | 按键'2' | @@ -49,11 +50,11 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | KEYCODE_9 | 2009 | 按键'9' | | KEYCODE_STAR | 2010 | 按键'*' | | KEYCODE_POUND | 2011 | 按键'#' | -| KEYCODE_DPAD_UP | 2012 | 导航键 向上 | -| KEYCODE_DPAD_DOWN | 2013 | 导航键 向下 | -| KEYCODE_DPAD_LEFT | 2014 | 导航键 向左 | -| KEYCODE_DPAD_RIGHT | 2015 | 导航键 向右 | -| KEYCODE_DPAD_CENTER | 2016 | 导航键 确定键 | +| KEYCODE_DPAD_UP | 2012 | 导航键:向上 | +| KEYCODE_DPAD_DOWN | 2013 | 导航键:向下 | +| KEYCODE_DPAD_LEFT | 2014 | 导航键:向左 | +| KEYCODE_DPAD_RIGHT | 2015 | 导航键:向右 | +| KEYCODE_DPAD_CENTER | 2016 | 导航键:确定键 | | KEYCODE_A | 2017 | 按键'A' | | KEYCODE_B | 2018 | 按键'B' | | KEYCODE_C | 2019 | 按键'C' | @@ -89,8 +90,8 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | KEYCODE_TAB | 2049 | Tab键 | | KEYCODE_SPACE | 2050 | 空格键 | | KEYCODE_SYM | 2051 | 符号修改器按键 | -| KEYCODE_EXPLORER | 2052 | 浏览器功能键,此键用于启动浏览器应用程序。 | -| KEYCODE_ENVELOPE | 2053 | 电子邮件功能键,此键用于启动电子邮件应用程序。 | +| KEYCODE_EXPLORER | 2052 | 浏览器功能键,此键用于启动浏览器应用程序 | +| KEYCODE_ENVELOPE | 2053 | 电子邮件功能键,此键用于启动电子邮件应用程序 | | KEYCODE_ENTER | 2054 | 回车键 | | KEYCODE_DEL | 2055 | 退格键 | | KEYCODE_GRAVE | 2056 | 按键'`' | @@ -122,11 +123,11 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | KEYCODE_MOVE_END | 2082 | 光标移动到末尾键 | | KEYCODE_INSERT | 2083 | 插入键 | | KEYCODE_FORWARD | 2084 | 前进键 | -| KEYCODE_MEDIA_PLAY | 2085 | 多媒体键 播放 | -| KEYCODE_MEDIA_PAUSE | 2086 | 多媒体键 暂停 | -| KEYCODE_MEDIA_CLOSE | 2087 | 多媒体键 关闭 | -| KEYCODE_MEDIA_EJECT | 2088 | 多媒体键 弹出 | -| KEYCODE_MEDIA_RECORD | 2089 | 多媒体键 录音 | +| KEYCODE_MEDIA_PLAY | 2085 | 多媒体键:播放 | +| KEYCODE_MEDIA_PAUSE | 2086 | 多媒体键:暂停 | +| KEYCODE_MEDIA_CLOSE | 2087 | 多媒体键:关闭 | +| KEYCODE_MEDIA_EJECT | 2088 | 多媒体键:弹出 | +| KEYCODE_MEDIA_RECORD | 2089 | 多媒体键:录音 | | KEYCODE_F1 | 2090 | 按键'F1' | | KEYCODE_F2 | 2091 | 按键'F2' | | KEYCODE_F3 | 2092 | 按键'F3' | diff --git a/zh-cn/application-dev/reference/apis/js-apis-keyevent.md b/zh-cn/application-dev/reference/apis/js-apis-keyevent.md index 9b5a2174858e9050be55fd7987917959f1a72633..040cbb6f5cea4dda99c264b1b3abad31de3e55f5 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-keyevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-keyevent.md @@ -33,7 +33,7 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------- | -------- | ---- | ---- | -------------- | | code | KeyCode | 是 | 否 | 按键码 | -| pressedTime | number | 是 | 否 | 按键按下时间 | +| pressedTime | number | 是 | 否 | 按键按下时间,单位为微秒(μs) | | deviceId | number | 是 | 否 | 按键所属设备id | ## KeyEvent @@ -44,15 +44,15 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------- | -------- | ---- | ---- | ------------------------------ | -| action | Action | 是 | 否 | 按键动作 | -| key | Key | 是 | 否 | 当前上报的按键 | +| action | [Action](#action) | 是 | 否 | 按键动作 | +| key | [Key](#key) | 是 | 否 | 当前上报的按键 | | unicodeChar | number | 是 | 否 | 按键对应的uniCode字符 | | keys | Key[] | 是 | 否 | 当前处于按下状态的按键列表 | -| ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态 | +| ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态
ture表示处于按下状态,false表示处于抬起状态。 | | altKey | boolean | 是 | 否 | 当前altKey是否处于按下状态 | | shiftKey | boolean | 是 | 否 | 当前shiftKey是否处于按下状态 | | logoKey | boolean | 是 | 否 | 当前logoKey是否处于按下状态 | | fnKey | boolean | 是 | 否 | 当前fnKey是否处于按下状态 | -| capsLock | boolean | 是 | 否 | 当前capsLock是否处于激活状态 | +| capsLock | boolean | 是 | 否 | 当前capsLock是否处于激活状态
ture表示处于激活状态,false表示处于未激活状态。 | | numLock | boolean | 是 | 否 | 当前numLock是否处于激活状态 | | scrollLock | boolean | 是 | 否 | 当前scrollLock是否处于激活状态 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md index da9dff1fd8b36082cddf45731166ce4727206555..a208ff72a2ff6fb399d14957edcebb8626db4109 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @@ -51,9 +51,11 @@ getLauncherAbilityInfo(bundleName: string, userId: number, callback: AsyncCallba ```ts import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; +import { BusinessError } from '@ohos.base'; try { - launcherBundleManager.getLauncherAbilityInfo('com.example.demo', 100, (errData, data) => { + launcherBundleManager.getLauncherAbilityInfo('com.example.demo', 100, + (errData: BusinessError, data: launcherBundleManager.LauncherAbilityInfo[]) => { if (errData !== null) { console.error(`errData is errCode:${errData.code} message:${errData.message}`); } else { @@ -101,13 +103,15 @@ getLauncherAbilityInfo(bundleName: string, userId: number) : Promise { + launcherBundleManager.getLauncherAbilityInfo("com.example.demo", 100) + .then((data: launcherBundleManager.LauncherAbilityInfo[]) => { console.log("data is " + JSON.stringify(data)); - }).catch (errData => { + }).catch ((errData: BusinessError) => { console.error(`errData is errCode:${errData.code} message:${errData.message}`); }) } catch (errData) { @@ -151,7 +155,7 @@ getLauncherAbilityInfoSync(bundleName: string, userId: number) : Array\<[Launche **示例:** -```typescript +```ts import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; try { @@ -198,9 +202,11 @@ getAllLauncherAbilityInfo(userId: number, callback: AsyncCallback { + launcherBundleManager.getAllLauncherAbilityInfo(100, + (errData: BusinessError, data: launcherBundleManager.LauncherAbilityInfo[]) => { if (errData !== null) { console.error(`errData is errCode:${errData.code} message:${errData.message}`); } else { @@ -247,11 +253,13 @@ getAllLauncherAbilityInfo(userId: number) : Promise { + launcherBundleManager.getAllLauncherAbilityInfo(100) + .then((data: launcherBundleManager.LauncherAbilityInfo[]) => { console.log("data is " + JSON.stringify(data)); - }).catch (errData => { + }).catch ((errData: BusinessError) => { console.error(`errData is errCode:${errData.code} message:${errData.message}`); }); } catch (errData) { @@ -293,9 +301,11 @@ getShortcutInfo(bundleName :string, callback: AsyncCallback { + launcherBundleManager.getShortcutInfo("com.example.demo", + (errData: BusinessError, data: launcherBundleManager.ShortcutInfo[]) => { if (errData !== null) { console.error(`errData is errCode:${errData.code} message:${errData.message}`); } else { @@ -341,11 +351,13 @@ getShortcutInfo(bundleName : string) : Promise { + launcherBundleManager.getShortcutInfo("com.example.demo") + .then((data: launcherBundleManager.ShortcutInfo[]) => { console.log("data is " + JSON.stringify(data)); - }).catch (errData => { + }).catch ((errData: BusinessError) => { console.error(`errData is errCode:${errData.code} message:${errData.message}`); }); } catch (errData) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md index 25c16fc8d59372933640b80ac32e4faf394243c4..8fba1f137b9d741627a716cf9e151fa42e276469 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @@ -56,7 +56,7 @@ LightWeightMap的构造函数。 **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); ``` @@ -85,7 +85,7 @@ isEmpty(): boolean **示例:** ```ts -const lightWeightMap = new LightWeightMap(); +const lightWeightMap: LightWeightMap = new LightWeightMap(); let result = lightWeightMap.isEmpty(); ``` @@ -121,10 +121,10 @@ hasAll(map: LightWeightMap): boolean **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); -let map = new LightWeightMap(); +let map: LightWeightMap = new LightWeightMap(); map.set("sparrow", 356); let result = lightWeightMap.hasAll(map); ``` @@ -161,7 +161,7 @@ hasKey(key: K): boolean; **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); let result = lightWeightMap.hasKey("squirrel"); ``` @@ -198,7 +198,7 @@ hasValue(value: V): boolean **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); let result = lightWeightMap.hasValue(123); ``` @@ -229,7 +229,7 @@ increaseCapacityTo(minimumCapacity: number): void **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.increaseCapacityTo(10); ``` @@ -265,7 +265,7 @@ get(key: K): V **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.get("sparrow"); @@ -303,7 +303,7 @@ getIndexOfKey(key: K): number **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfKey("sparrow"); @@ -341,7 +341,7 @@ getIndexOfValue(value: V): number **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfValue(123); @@ -380,7 +380,7 @@ getKeyAt(index: number): K **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getKeyAt(1); @@ -412,10 +412,10 @@ setAll(map: LightWeightMap): void **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); -let map = new LightWeightMap(); +let map: LightWeightMap = new LightWeightMap(); map.setAll(lightWeightMap); // 将lightWeightMap中所有的元素添加到map中 ``` @@ -451,7 +451,7 @@ set(key: K, value: V): Object **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); let result = lightWeightMap.set("squirrel", 123); ``` @@ -487,7 +487,7 @@ remove(key: K): V **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.remove("sparrow"); @@ -525,7 +525,7 @@ removeAt(index: number): boolean **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.removeAt(1); @@ -565,7 +565,7 @@ setValueAt(index: number, newValue: V): boolean **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.setValueAt(1, 3546); @@ -604,7 +604,7 @@ getValueAt(index: number): V **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getValueAt(1); @@ -630,7 +630,7 @@ clear(): void **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.clear(); @@ -662,14 +662,14 @@ keys(): IterableIterator<K> **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let iter = lightWeightMap.keys(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value:" + temp.value); + temp = iter.next(); } ``` @@ -699,14 +699,14 @@ values(): IterableIterator<V> **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let iter = lightWeightMap.values(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value:" + temp.value); + temp = iter.next(); } ``` @@ -744,11 +744,11 @@ callbackfn的参数说明: **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("sparrow", 123); lightWeightMap.set("gull", 357); -lightWeightMap.forEach((value, key) => { - console.log("value:" + value, "key:" + key); +lightWeightMap.forEach((value: number, key: string) => { + console.log("value:" + value, "key:" + key); }); ``` @@ -778,15 +778,15 @@ entries(): IterableIterator<[K, V]> **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let iter = lightWeightMap.entries(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("key:" + temp[0]); - console.log("value:" + temp[1]); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("key:" + temp.value[0]); + console.log("value:" + temp.value[1]); + temp = iter.next(); } ``` @@ -815,7 +815,7 @@ toString(): String **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.toString(); @@ -846,22 +846,27 @@ let result = lightWeightMap.toString(); **示例:** ```ts -let lightWeightMap = new LightWeightMap(); +let lightWeightMap: LightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); // 使用方法一: -for (let item of lightWeightMap) { - console.log("key:" + item[0]); - console.log("value:" + item[1]); +let nums = Array.from(lightWeightMap.values()); +for (let item1 of nums) { + console.log("value:" + item1); +} + +let key = Array.from(lightWeightMap.keys()); +for (let item2 of key) { + console.log("key:" + item2); } // 使用方法二: let iter = lightWeightMap[Symbol.iterator](); -let temp = iter.next().value; -while(temp != undefined) { - console.log("key:" + temp[0]); - console.log("value:" + temp[1]); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("key:" + temp.value[0]); + console.log("value:" + temp.value[1]); + temp = iter.next(); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md index 06c0427308311578d17711cd69368634aa4e73e2..a17e0d730b7f1908159818ce6aa73cdd19fdfabf 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @@ -54,7 +54,7 @@ LightWeightSet的构造函数。 **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); ``` @@ -83,7 +83,7 @@ isEmpty(): boolean **示例:** ```ts -const lightWeightSet = new LightWeightSet(); +const lightWeightSet: LightWeightSet = new LightWeightSet(); let result = lightWeightSet.isEmpty(); ``` @@ -118,7 +118,7 @@ add(obj: T): boolean **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); let result = lightWeightSet.add("squirrel"); ``` @@ -148,10 +148,10 @@ addAll(set: LightWeightSet<T>): boolean **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); -let set = new LightWeightSet(); +let set: LightWeightSet = new LightWeightSet(); set.add("gull"); let result = lightWeightSet.addAll(set); ``` @@ -188,10 +188,10 @@ hasAll(set: LightWeightSet<T>): boolean **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); -let set = new LightWeightSet(); +let set: LightWeightSet = new LightWeightSet(); set.add("sparrow"); let result = lightWeightSet.hasAll(set); ``` @@ -228,7 +228,7 @@ has(key: T): boolean **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add(123); let result = lightWeightSet.has(123); ``` @@ -265,7 +265,7 @@ equal(obj: Object): boolean **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let obj = ["sparrow", "squirrel"]; @@ -299,7 +299,7 @@ increaseCapacityTo(minimumCapacity: number): void **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.increaseCapacityTo(10); ``` @@ -335,7 +335,7 @@ getIndexOf(key: T): number **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getIndexOf("sparrow"); @@ -373,7 +373,7 @@ remove(key: T): T **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.remove("sparrow"); @@ -411,7 +411,7 @@ removeAt(index: number): boolean **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.removeAt(1); @@ -449,7 +449,7 @@ getValueAt(index: number): T **参数:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getValueAt(1); @@ -475,7 +475,7 @@ clear(): void **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); lightWeightSet.clear(); @@ -499,7 +499,7 @@ toString(): String **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toString(); @@ -531,7 +531,7 @@ toArray(): Array<T> **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toArray(); @@ -563,7 +563,7 @@ values(): IterableIterator<T> **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let iter = lightWeightSet.values(); @@ -608,11 +608,11 @@ callbackfn的参数说明: **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("sparrow"); lightWeightSet.add("gull"); -lightWeightSet.forEach((value, key) => { - console.log("value:" + value, "key:" + key); +lightWeightSet.forEach((value:string, key:string) => { + console.log("value:" + value, "key:" + key); }); ``` @@ -642,7 +642,7 @@ entries(): IterableIterator<[T, T]> **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let iter = lightWeightSet.entries(); @@ -679,20 +679,21 @@ while(index < lightWeightSet.length) { **示例:** ```ts -let lightWeightSet = new LightWeightSet(); +let lightWeightSet: LightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); // 使用方法一: -for (let item of lightWeightSet) { +let nums: Array = lightWeightSet.toArray() +for (let item of nums) { console.log("value:" + item); } // 使用方法二: let iter = lightWeightSet[Symbol.iterator](); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value:" + temp.value); + temp = iter.next(); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md index dc0d848352076ab4df82048977535f6a808191ce..366052f94e8c9a8356bc50a6fdbf34d58d92869d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -19,7 +19,7 @@ LinkedList和[ArrayList](js-apis-arraylist.md)相比,插入数据效率LinkedL ## 导入模块 ```ts -import LinkedList from '@ohos.util.LinkedList'; +import LinkedList from '@ohos.util.LinkedList'; ``` ## LinkedList @@ -53,7 +53,7 @@ LinkedList的构造函数。 **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); ``` @@ -88,12 +88,16 @@ add(element: T): boolean **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); let result = linkedList.add("a"); let result1 = linkedList.add(1); let b = [1, 2, 3]; let result2 = linkedList.add(b); -let c = {name : "Dylon", age : "13"}; +class C { + name: string = '' + age: string = '' +} +let c: C = {name : "Dylon", age : "13"}; let result3 = linkedList.add(c); let result4 = linkedList.add(false); ``` @@ -123,12 +127,16 @@ addFirst(element: T): void **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.addFirst("a"); linkedList.addFirst(1); let b = [1, 2, 3]; linkedList.addFirst(b); -let c = {name : "Dylon", age : "13"}; +class C { + name: string = '' + age: string = '' +} +let c: C = {name : "Dylon", age : "13"}; linkedList.addFirst(c); linkedList.addFirst(false); ``` @@ -160,7 +168,7 @@ insert(index: number, element: T): void **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.insert(0, "A"); linkedList.insert(1, 0); linkedList.insert(2, true); @@ -197,7 +205,7 @@ has(element: T): boolean **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add("squirrel"); let result = linkedList.has("squirrel"); ``` @@ -233,7 +241,7 @@ get(index: number): T **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -275,7 +283,7 @@ getLastIndexOf(element: T): number **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -317,7 +325,7 @@ getIndexOf(element: T): number **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -360,7 +368,7 @@ removeByIndex(index: number): T **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -395,7 +403,7 @@ removeFirst(): T **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -430,7 +438,7 @@ removeLast(): T **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -470,7 +478,7 @@ remove(element: T): boolean **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -511,7 +519,7 @@ removeFirstFound(element: T): boolean **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -552,7 +560,7 @@ removeLastFound(element: T): boolean **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -585,7 +593,7 @@ clone(): LinkedList<T> **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -628,13 +636,13 @@ callbackfn的参数说明: **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); -linkedList.forEach((value, index) => { - console.log("value:" + value, "index:" + index); +linkedList.forEach((value:number, index: number) => { + console.log("value:" + value, "index:" + index); }); ``` @@ -657,7 +665,7 @@ clear(): void **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -698,7 +706,7 @@ set(index: number, element: T): T **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -730,7 +738,7 @@ convertToArray(): Array<T> **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -763,7 +771,7 @@ getFirst(): T **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -796,7 +804,7 @@ getLast(): T **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); @@ -829,22 +837,23 @@ let result = linkedList.getLast(); **示例:** ```ts -let linkedList = new LinkedList(); +let linkedList: LinkedList = new LinkedList(); linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); // 使用方法一: -for (let item of linkedList) { +let items = Array.from(linkedList) +for (let item of items) { console.log("value:" + item); } // 使用方法二: let iter = linkedList[Symbol.iterator](); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value:" + temp.value); + temp = iter.next(); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-list.md b/zh-cn/application-dev/reference/apis/js-apis-list.md index 8da997e8fcfbcf075f87948f29f89001f62d46a0..f151ac9e52a76cf398aecc1252e471c35bc54b43 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-list.md +++ b/zh-cn/application-dev/reference/apis/js-apis-list.md @@ -51,7 +51,7 @@ List的构造函数。 **示例:** ```ts -let list = new List(); +let list: List = new List(); ``` @@ -86,12 +86,16 @@ add(element: T): boolean **示例:** ```ts -let list = new List(); +let list: List = new List(); let result1 = list.add("a"); let result2 = list.add(1); let b = [1, 2, 3]; let result3 = list.add(b); -let c = {name : "Dylon", age : "13"}; +class C { + name: string = '' + age: string = '' +} +let c: C = {name : "Dylon", age : "13"}; let result4 = list.add(c); let result5 = list.add(false); ``` @@ -123,7 +127,7 @@ insert(element: T, index: number): void **示例:** ```ts -let list = new List(); +let list: List = new List(); list.insert("A", 0); list.insert(0, 1); list.insert(true, 2); @@ -160,7 +164,7 @@ has(element: T): boolean **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add("squirrel"); let result = list.has("squirrel"); ``` @@ -196,7 +200,7 @@ get(index: number): T **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -238,7 +242,7 @@ getLastIndexOf(element: T): number **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -280,7 +284,7 @@ getIndexOf(element: T): number **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -322,11 +326,11 @@ equal(obj: Object): boolean **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); -let obj = new List(); +let obj: List = new List(); obj.add(2); obj.add(4); obj.add(5); @@ -365,7 +369,7 @@ removeByIndex(index: number): T **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -405,7 +409,7 @@ remove(element: T): boolean **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -448,12 +452,12 @@ callbackfn的参数说明: **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); list.add(4); -list.replaceAllElements((value) => { +list.replaceAllElements((value: number) => { // 用户操作逻辑根据实际场景进行添加。 return value; }); @@ -494,13 +498,13 @@ callbackfn的参数说明: **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); list.add(4); -list.forEach((value, index) => { - console.log("value:" + value, "index:" + index); +list.forEach((value:number, index:number) => { + console.log("value:" + value, "index:" + index); }); ``` @@ -536,7 +540,7 @@ comparator的参数说明: **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -578,7 +582,7 @@ getSubList(fromIndex: number, toIndex: number): List<T> **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -605,7 +609,7 @@ clear(): void **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -646,7 +650,7 @@ set(index: number, element: T): T **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -679,7 +683,7 @@ convertToArray(): Array<T> **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -712,7 +716,7 @@ isEmpty(): boolean **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -745,7 +749,7 @@ getFirst(): T **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -778,7 +782,7 @@ getLast(): T **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); @@ -811,22 +815,23 @@ let result = list.getLast(); **示例:** ```ts -let list = new List(); +let list: List = new List(); list.add(2); list.add(4); list.add(5); list.add(4); // 使用方法一: -for (let item of list) { - console.log("value: " + item); +let items = Array.from(list) +for (let item of items) { + console.log("value: " + item); } // 使用方法二: let iter = list[Symbol.iterator](); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value: " + temp); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("value: " + temp.value); + temp = iter.next(); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md b/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md index 074fd7095e50b760f98b4a10668b27190da8043f..157ac4bc1d2de44afc9b996baf77aad1461d5311 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @@ -28,7 +28,6 @@ import { Action, Button, Axis, AxisValue, MouseEvent } from '@ohos.multimodalInp | AXIS_UPDATE | 5 | 鼠标轴事件更新 | | AXIS_END | 6 | 鼠标轴事件结束 | - ## Button 鼠标按键。 @@ -79,22 +78,22 @@ import { Action, Button, Axis, AxisValue, MouseEvent } from '@ohos.multimodalInp | 名称 | 类型 | 可读 | 可写 | 说明 | | -------------- | ----------- | ---- | ---- | ---------------------------------------- | -| action | Action | 是 | 否 | 鼠标事件动作 | +| action | [Action](#action) | 是 | 否 | 鼠标事件动作 | | screenX | number | 是 | 否 | 鼠标光标在屏幕中的横坐标 | | screenY | number | 是 | 否 | 鼠标光标在屏幕中的纵坐标 | | windowX | number | 是 | 否 | 鼠标所在窗口的横坐标 | | windowY | number | 是 | 否 | 鼠标所在窗口的纵坐标 | | rawDeltaX | number | 是 | 否 | 鼠标本次操作横坐标偏移值 | | rawDeltaY | number | 是 | 否 | 鼠标本次操作纵坐标偏移值 | -| button | Button | 是 | 否 | 鼠标按钮 +| button | [Button](#button) | 是 | 否 | 鼠标按钮 | pressedButtons | Button[] | 是 | 否 | 当前处于按下状态的鼠标按钮 | | axes | AxisValue[] | 是 | 否 | 事件包含的所有轴数据 | | pressedKeys | KeyCode[] | 是 | 否 | 当前处于按下状态的按键列表 | -| ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态 | +| ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态
ture表示处于按下状态,false表示处于抬起状态 | | altKey | boolean | 是 | 否 | 当前altKey是否处于按下状态 | | shiftKey | boolean | 是 | 否 | 当前shiftKey是否处于按下状态 | | logoKey | boolean | 是 | 否 | 当前logoKey是否处于按下状态 | | fnKey | boolean | 是 | 否 | 当前fnKey是否处于按下状态 | -| capsLock | boolean | 是 | 否 | 当前capsLock是否处于激活状态 | +| capsLock | boolean | 是 | 否 | 当前capsLock是否处于激活状态
ture表示激活状态,false表示处于未激活状态 | | numLock | boolean | 是 | 否 | 当前numLock是否处于激活状态 | | scrollLock | boolean | 是 | 否 | 当前scrollLock是否处于激活状态 | 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..9b7bfba8e211e12b1884991b9dbaaa08749b224a 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 @@ -720,7 +720,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,7 +731,7 @@ 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服务的信息和事件错误信息。 | **示例:** @@ -786,7 +786,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,7 +797,7 @@ 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服务的信息和事件错误信息。 | **示例:** @@ -852,7 +852,7 @@ discoveryService.stopSearchingMDNS(); ### off('serviceFound')10+ -off(type: 'serviceFound', callback: Callback\): void +off(type: 'serviceFound', callback?: Callback\): void 取消订阅发现mDNS服务的通知。 @@ -863,7 +863,7 @@ off(type: 'serviceFound', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | 是 |取消订阅的事件,固定为'serviceFound'。
serviceFound:发现mDNS服务事件。 | -| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 是 | mDNS服务的信息。 | +| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 否 | mDNS服务的信息。 | **示例:** @@ -918,7 +918,7 @@ discoveryService.stopSearchingMDNS(); ### off('serviceLost')10+ -off(type: 'serviceLost', callback: Callback\): void +off(type: 'serviceLost', callback?: Callback\): void 取消订阅移除mDNS服务的通知。 @@ -929,7 +929,7 @@ off(type: 'serviceLost', callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | |-------------|--------------|-----------|-----------------------------------------------------| | type | string | 是 |取消订阅的事件,固定为'serviceLost'。
serviceLost:移除mDNS服务事件。 | -| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 是 | mDNS服务的信息。 | +| callback | Callback<[LocalServiceInfo](#localserviceinfo)> | 否 | mDNS服务的信息。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index 1cd072550c68993fef0603a419280d6eec78bc19..f2af2382a636d5b19460d089d60322573eb9b56a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -1249,7 +1249,7 @@ getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo, callback: AsyncCallb ```js import { BusinessError } from '@ohos.base'; - let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + let domainInfo: account_osAccount.DomainAccountInfo = {domain: 'testDomain', accountName: 'testAccountName'}; let accountManager = account_osAccount.getAccountManager(); try { accountManager.getOsAccountLocalIdForDomain(domainInfo, (err: BusinessError, localId: number) => { @@ -1298,7 +1298,7 @@ getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo): Promise<number&g ```js import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + let domainInfo: account_osAccount.DomainAccountInfo = {domain: 'testDomain', accountName: 'testAccountName'}; try { accountManager.getOsAccountLocalIdForDomain(domainInfo).then((localId: number) => { console.log('getOsAccountLocalIdForDomain successfully, localId: ' + localId); @@ -1765,7 +1765,8 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, cal ```js import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + let domainInfo: account_osAccount.DomainAccountInfo = + {domain: 'testDomain', accountName: 'testAccountName'}; try { accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo, (err: BusinessError, osAccountInfo: account_osAccount.OsAccountInfo)=>{ @@ -1817,7 +1818,8 @@ createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Pr ```js import { BusinessError } from '@ohos.base'; let accountManager = account_osAccount.getAccountManager(); - let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'}; + let domainInfo: account_osAccount.DomainAccountInfo = + {domain: 'testDomain', accountName: 'testAccountName'}; try { accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo).then( (accountInfo: account_osAccount.OsAccountInfo) => { @@ -4084,7 +4086,7 @@ getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProp account_osAccount.GetPropertyType.REMAIN_TIMES, account_osAccount.GetPropertyType.FREEZING_TIME ]; - let request = { + let request: account_osAccount.GetPropertyRequest = { authType: account_osAccount.AuthType.PIN, keys: keys }; @@ -4138,7 +4140,7 @@ getProperty(request: GetPropertyRequest): Promise<ExecutorProperty>; account_osAccount.GetPropertyType.REMAIN_TIMES, account_osAccount.GetPropertyType.FREEZING_TIME ]; - let request = { + let request: account_osAccount.GetPropertyRequest = { authType: account_osAccount.AuthType.PIN, keys: keys }; @@ -4183,7 +4185,7 @@ setProperty(request: SetPropertyRequest, callback: AsyncCallback<void>): v ```js import { BusinessError } from '@ohos.base'; let userAuth = new account_osAccount.UserAuth(); - let request = { + let request: account_osAccount.SetPropertyRequest = { authType: account_osAccount.AuthType.PIN, key: account_osAccount.SetPropertyType.INIT_ALGORITHM, setInfo: new Uint8Array([0]) @@ -4236,7 +4238,7 @@ setProperty(request: SetPropertyRequest): Promise<void>; ```js import { BusinessError } from '@ohos.base'; let userAuth = new account_osAccount.UserAuth(); - let request2 = { + let request2: account_osAccount.SetPropertyRequest = { authType: account_osAccount.AuthType.PIN, key: account_osAccount.SetPropertyType.INIT_ALGORITHM, setInfo: new Uint8Array([0]) @@ -4608,16 +4610,17 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs **示例:** ```js import { AsyncCallback } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => { // mock authentication // notify authentication result - callback.onResult(0, { + let result: account_osAccount.AuthResult = { token: new Uint8Array([0]), remainTimes: 5, freezingTime: 0 - }); + }; + callback.onResult(0, result); }, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: account_osAccount.IUserAuthCallback) => {}, @@ -4671,18 +4674,19 @@ authWithPopup(domainAccountInfo: DomainAccountInfo, callback: IUserAuthCallback) **示例:** ```js import { AsyncCallback } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: account_osAccount.IUserAuthCallback) => { // mock authentication // notify authentication result - callback.onResult(0, { + let result: account_osAccount.AuthResult = { token: new Uint8Array([0]), remainTimes: 5, freezingTime: 0 - }); + }; + callback.onResult(0, result); }, authWithToken: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, @@ -4721,7 +4725,7 @@ authWithToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, callback: **示例:** ```js import { AsyncCallback } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -4730,11 +4734,12 @@ authWithToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, callback: callback: account_osAccount.IUserAuthCallback) => { // mock authentication // notify authentication result - callback.onResult(0, { + let result: account_osAccount.AuthResult = { token: new Uint8Array([0]), remainTimes: 5, freezingTime: 0 - }); + }; + callback.onResult(0, result); }, getAccountInfo: (domain: string, accountName: string, callback: AsyncCallback) => {}, @@ -4771,7 +4776,7 @@ getAccountInfo(domain: string, accountName: string, callback: AsyncCallback<D **示例:** ```js import { AsyncCallback, BusinessError } from '@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -4782,12 +4787,17 @@ getAccountInfo(domain: string, accountName: string, callback: AsyncCallback<D callback: AsyncCallback) => { // mock getting account information // notify result - let code: BusinessError - callback(code, { + let code: BusinessError = { + code: 0, + name: "", + message: "" + }; + let accountInfo: account_osAccount.DomainAccountInfo = { domain: domain, accountName: accountName, accountId: 'xxxx' - }) + }; + callback(code, accountInfo); }, getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, @@ -4821,7 +4831,7 @@ getAuthStatusInfo(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback& **示例:** ```js import { AsyncCallback, BusinessError } from '@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -4832,11 +4842,16 @@ getAuthStatusInfo(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback& callback: AsyncCallback) => {}, getAuthStatusInfo: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => { - let code: BusinessError; - callback(code, { + let code: BusinessError = { + code: 0, + name: "", + message: "" + }; + let statusInfo: account_osAccount.AuthStatusInfo = { remainTimes: 5, freezingTime: 0 - }) + }; + callback(code, statusInfo); }, bindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, localId: number, callback: AsyncCallback) => {}, @@ -4868,7 +4883,7 @@ bindAccount(domainAccountInfo: DomainAccountInfo, localId: number, callback: Asy **示例:** ```js import { AsyncCallback, BusinessError } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -4883,8 +4898,12 @@ bindAccount(domainAccountInfo: DomainAccountInfo, localId: number, callback: Asy callback: AsyncCallback) => { // mock unbinding operation // notify binding result - let code: BusinessError; - callback(code) + let code: BusinessError = { + code: 0, + name: "", + message: "" + }; + callback(code); }, unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => {}, isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, @@ -4914,7 +4933,7 @@ unbindAccount(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback<v **示例:** ```js import { AsyncCallback, BusinessError } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -4930,8 +4949,12 @@ unbindAccount(domainAccountInfo: DomainAccountInfo, callback: AsyncCallback<v unbindAccount: (domainAccountInfo: account_osAccount.DomainAccountInfo, callback: AsyncCallback) => { // mock unbinding operation // notify unbinding result - let code: BusinessError; - callback(code) + let code: BusinessError = { + code: 0, + name: "", + message: "" + }; + callback(code); }, isAccountTokenValid: (domainAccountInfo: account_osAccount.DomainAccountInfo, token: Uint8Array, callback: AsyncCallback) => {}, @@ -4961,7 +4984,7 @@ isAccountTokenValid(domainAccountInfo: DomainAccountInfo, token: Uint8Array, cal **示例:** ```js import { AsyncCallback, BusinessError } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -4979,7 +5002,11 @@ isAccountTokenValid(domainAccountInfo: DomainAccountInfo, token: Uint8Array, cal callback: AsyncCallback) => { // mock checking operation // notify checking result - let code: BusinessError + let code: BusinessError = { + code: 0, + name: "", + message: "" + }; callback(code, true); }, getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => {} @@ -5007,7 +5034,7 @@ getAccessToken(options: GetDomainAccessTokenOptions, callback: AsyncCallback< **示例:** ```js import { AsyncCallback, BusinessError } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -5025,9 +5052,13 @@ getAccessToken(options: GetDomainAccessTokenOptions, callback: AsyncCallback< callback: AsyncCallback) => {}, getAccessToken: (options: account_osAccount.GetDomainAccessTokenOptions, callback: AsyncCallback) => { // mock getting operation - //let token = new Uint8Array([0]); // notify result - let code: BusinessError + let code: BusinessError = { + code: 0, + name: "", + message: "" + }; + let token: Uint8Array = new Uint8Array([0]); callback(code, token); } } @@ -5064,7 +5095,7 @@ static registerPlugin(plugin: DomainPlugin): void **示例:** ```js import { AsyncCallback } from './@ohos.base'; - let plugin = { + let plugin: account_osAccount.DomainPlugin = { auth: (domainAccountInfo: account_osAccount.DomainAccountInfo, credential: Uint8Array, callback: account_osAccount.IUserAuthCallback) => {}, authWithPopup: (domainAccountInfo: account_osAccount.DomainAccountInfo, @@ -5150,7 +5181,7 @@ auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUs **示例:** ```js - let domainAccountInfo = { + let domainAccountInfo: account_osAccount.DomainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan' } @@ -5347,7 +5378,7 @@ hasAccount(domainAccountInfo: DomainAccountInfo): Promise<boolean> **示例:** ```js import { BusinessError } from '@ohos.base'; - let domainAccountInfo = { + let domainAccountInfo: account_osAccount.DomainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan' } @@ -5393,7 +5424,7 @@ updateAccountToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array, call **示例:** ```js import { BusinessError } from '@ohos.base'; - let domainAccountInfo = { + let domainAccountInfo: account_osAccount.DomainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan', accountId: '123456' @@ -5448,7 +5479,7 @@ updateAccountToken(domainAccountInfo: DomainAccountInfo, token: Uint8Array): Pro **示例:** ```js import { BusinessError } from '@ohos.base'; - let domainAccountInfo = { + let domainAccountInfo: account_osAccount.DomainAccountInfo = { domain: 'CHINA', accountName: 'zhangsan', accountId: '123456' @@ -5662,10 +5693,10 @@ updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; let userAuth: account_osAccount.UserAuth = new account_osAccount.UserAuth(); let pinAuth: account_osAccount.PINAuth = new account_osAccount.PINAuth(); let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0, 0]); - let credentialInfo = { + let credentialInfo: account_osAccount.CredentialInfo = { credType: account_osAccount.AuthType.PIN, credSubType: account_osAccount.AuthSubType.PIN_SIX, - token: null + token: new Uint8Array([]), }; pinAuth.registerInputer({ onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { @@ -5678,7 +5709,9 @@ updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; if (result != account_osAccount.ResultCode.SUCCESS) { return; } - credentialInfo.token = extraInfo.token; + if (extraInfo.token != null) { + credentialInfo.token = extraInfo.token; + } try { userIDM.updateCredential(credentialInfo, { onResult: (result: number, extraInfo: account_osAccount.RequestResult) => { @@ -5997,7 +6030,7 @@ onSetData: (authSubType: AuthSubType, data: Uint8Array) => void; ```js let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber: Uint8Array = new Uint8Array([1, 2, 3, 4]); - let inputer = { + let inputer: account_osAccount.IInputer = { onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { callback.onSetData(authSubType, passwordNumber); @@ -6034,7 +6067,7 @@ onGetData: (authSubType: AuthSubType, callback: IInputData) => void; ```js let password: Uint8Array = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber: Uint8Array = new Uint8Array([1, 2, 3, 4]); - let inputer = { + let inputer: account_osAccount.IInputer = { onGetData: (authSubType: account_osAccount.AuthSubType, callback: account_osAccount.IInputData) => { if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { callback.onSetData(authSubType, passwordNumber); @@ -6073,8 +6106,8 @@ onResult: (result: number, extraInfo: AuthResult) => void; **示例:** ```js - let authCallback = { - onResult: (result: account_osAccount.AuthSubType, extraInfo: account_osAccount.IInputData) => { + let authCallback: account_osAccount.IUserAuthCallback = { + onResult: (result: number, extraInfo: account_osAccount.AuthResult) => { console.log('auth result = ' + result); console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); } @@ -6101,8 +6134,8 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; **示例:** ```js - let authCallback = { - onResult: (result: account_osAccount.AuthSubType, extraInfo: account_osAccount.IInputData) => { + let authCallback: account_osAccount.IUserAuthCallback = { + onResult: (result: number, extraInfo: account_osAccount.AuthResult) => { console.log('auth result = ' + result) console.log('auth extraInfo = ' + JSON.stringify(extraInfo)); }, @@ -6139,7 +6172,7 @@ onResult: (result: number, extraInfo: RequestResult) => void; **示例:** ```js - let idmCallback = { + let idmCallback: account_osAccount.IIdmCallback = { onResult: (result: number, extraInfo: account_osAccount.RequestResult) => { console.log('callback result = ' + result) console.info('callback extraInfo = ' + JSON.stringify(extraInfo)); @@ -6167,7 +6200,7 @@ onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; **示例:** ```js - let idmCallback = { + let idmCallback: account_osAccount.IIdmCallback = { onResult: (result: number, extraInfo: Object) => { console.log('callback result = ' + result) console.log('callback onResult = ' + JSON.stringify(extraInfo)); 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 443442ccd92a8c956cd49ae197425e8ea9aa804e..30d31c0e22a1856fcedff4ce04165ee7083f923d 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-overlay.md +++ b/zh-cn/application-dev/reference/apis/js-apis-overlay.md @@ -45,8 +45,8 @@ setOverlayEnabled(moduleName:string, isEnabled: boolean): Promise\; **示例:** ```ts -var moduleName = "feature"; -var isEnabled = false; +let moduleName = "feature"; +let isEnabled = false; try { overlay.setOverlayEnabled(moduleName, isEnabled) @@ -88,8 +88,8 @@ setOverlayEnabled(moduleName:string, isEnabled: boolean, callback: AsyncCallback **示例:** ```ts -var moduleName = "feature"; -var isEnabled = false; +let moduleName = "feature"; +let isEnabled = false; try { overlay.setOverlayEnabled(moduleName, isEnabled, (err, data) => { @@ -144,9 +144,9 @@ setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: b **示例:** ```ts -var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature"; -var isEnabled = false; +let bundleName = "com.example.myapplication_xxxxx"; +let moduleName = "feature"; +let isEnabled = false; try { overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled) @@ -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为null,data为获取到的处置状态;否则为错误对象。 | +| callback | AsyncCallback\ | 是 | 回调函数。当设置指定应用的overlay module的禁用使能状态成功时,err为null,否则为错误对象。 | **错误码:** @@ -195,9 +195,9 @@ setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: b **示例:** ```ts -var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature"; -var isEnabled = false; +let bundleName = "com.example.myapplication_xxxxx"; +let moduleName = "feature"; +let isEnabled = false; try { overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (err, data) => { @@ -245,7 +245,7 @@ getOverlayModuleInfo(moduleName: string): Promise\; **示例:** ```ts -var moduleName = "feature"; +let moduleName = "feature"; (async() => { try { @@ -285,7 +285,7 @@ getOverlayModuleInfo(moduleName: string, callback: AsyncCallback\ { if (err) { @@ -331,7 +331,7 @@ getTargetOverlayModuleInfos(targetModuleName: string): Promise\ { try { @@ -370,7 +370,7 @@ getTargetOverlayModuleInfos(targetModuleName: string, callback: AsyncCallback\ { if (err) { @@ -423,8 +423,8 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName?: string): Promi **示例:** ```ts -var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature"; +let bundleName = "com.example.myapplication_xxxxx"; +let moduleName = "feature"; (async() => { try { @@ -470,8 +470,8 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName: string, callbac **示例:** ```ts -var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature"; +let bundleName = "com.example.myapplication_xxxxx"; +let moduleName = "feature"; try { overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (err, data) => { @@ -517,7 +517,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\ { @@ -571,8 +571,8 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName?: s **示例:** ```ts -var targetBundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature"; +let targetBundleName = "com.example.myapplication_xxxxx"; +let moduleName = "feature"; (async() => { try { @@ -618,8 +618,8 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: st **示例:** ```ts -var targetBundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature"; +let targetBundleName = "com.example.myapplication_xxxxx"; +let moduleName = "feature"; try { overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (err, data) => { @@ -665,7 +665,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: Asyn **示例:** ```ts -var targetBundleName = "com.example.myapplication_xxxxx"; +let targetBundleName = "com.example.myapplication_xxxxx"; try { overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (err, data) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md index 311953979e0faefd1d41b3f360cb62dc55f57a4a..654ca7fffe9973041f3e25973505e5edc5165f38 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -53,7 +53,7 @@ PlainArray的构造函数。 **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); ``` @@ -82,7 +82,7 @@ isEmpty(): boolean **示例:** ```ts -const plainArray = new PlainArray(); +const plainArray: PlainArray = new PlainArray(); let result = plainArray.isEmpty(); ``` @@ -118,7 +118,7 @@ has(key: number): boolean **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); let result = plainArray.has(1); ``` @@ -155,7 +155,7 @@ get(key: number): T **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.get(1); @@ -193,7 +193,7 @@ getIndexOfKey(key: number): number **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfKey(2); @@ -231,7 +231,7 @@ getIndexOfValue(value: T): number **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfValue("squirrel"); @@ -269,7 +269,7 @@ getKeyAt(index: number): number **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getKeyAt(1); @@ -307,7 +307,7 @@ getValueAt(index: number): T **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getValueAt(1); @@ -338,7 +338,7 @@ clone(): PlainArray<T> **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let newPlainArray = plainArray.clone(); @@ -371,7 +371,7 @@ add(key: number, value: T): void **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); ``` @@ -407,7 +407,7 @@ remove(key: number): T **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.remove(2); @@ -445,7 +445,7 @@ removeAt(index: number): T **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeAt(1); @@ -485,7 +485,7 @@ removeRangeFrom(index: number, size: number): number **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeRangeFrom(1, 3); @@ -519,7 +519,7 @@ setValueAt(index: number, value: T): void **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.setValueAt(1, 3546); @@ -551,7 +551,7 @@ toString(): String **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.toString(); @@ -577,7 +577,7 @@ clear(): void **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.clear(); @@ -617,10 +617,10 @@ callbackfn的参数说明: **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); -plainArray.forEach((value, index) => { +plainArray.forEach((value:string, index: number) => { console.log("value:" + value, "index:" + index); }); ``` @@ -651,22 +651,15 @@ plainArray.forEach((value, index) => { **示例:** ```ts -let plainArray = new PlainArray(); +let plainArray: PlainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); -// 使用方法一: -for (let item of plainArray) { - console.log("key:" + item[0]); - console.log("value:" + item[1]); -} - -// 使用方法二: let iter = plainArray[Symbol.iterator](); -let temp = iter.next().value; -while(temp != undefined) { - console.log("key:" + temp[0]); - console.log("value:" + temp[1]); - temp = iter.next().value; +let temp = iter.next(); +while(!temp.done) { + console.log("key:" + temp.value[0]); + console.log("value:" + temp.value[1]); + temp = iter.next(); } ``` \ No newline at end of file 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..6b52eb41ddaa284b64988d7d8e5adaeeed56662e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @@ -449,6 +449,10 @@ on(type: 'activeStateChange', permissionList: Array<Permissions>, callback 订阅指定权限列表的权限使用状态变更事件。 +允许相同permissionList订阅多个callback。 + +不允许存在交集的permissionList订阅相同callback。 + **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -494,6 +498,8 @@ off(type: 'activeStateChange', permissionList: Array<Permissions>, callbac 取消订阅指定权限列表的权限使用状态变更事件。 +取消订阅不传callback时,批量删除permissionList下面的所有callback。 + **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken diff --git a/zh-cn/application-dev/reference/apis/js-apis-queue.md b/zh-cn/application-dev/reference/apis/js-apis-queue.md index 2e395bfba07d63f94606b295d5920d2c30a80965..4d5d035a775eeb6645af22f5ece39aedaed1f955 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-queue.md +++ b/zh-cn/application-dev/reference/apis/js-apis-queue.md @@ -51,7 +51,7 @@ Queue的构造函数。 **示例:** ```ts -let queue = new Queue(); +let queue : Queue = new Queue(); ``` @@ -86,12 +86,16 @@ add(element: T): boolean **示例:** ```ts -let queue = new Queue(); +class C1 { + name: string = "" + age: string = "" +} +let queue : Queue = new Queue(); let result = queue.add("a"); let result1 = queue.add(1); let b = [1, 2, 3]; let result2 = queue.add(b); -let c = {name : "Dylon", age : "13"}; +let c : C1 = {name : "Dylon", age : "13"}; let result3 = queue.add(c); ``` @@ -120,7 +124,7 @@ pop(): T **示例:** ```ts -let queue = new Queue(); +let queue : Queue = new Queue(); queue.add(2); queue.add(4); queue.add(5); @@ -154,7 +158,7 @@ getFirst(): T **示例:** ```ts -let queue = new Queue(); +let queue : Queue = new Queue(); queue.add(2); queue.add(4); queue.add(5); @@ -197,13 +201,13 @@ callbackfn的参数说明: **示例:** ```ts -let queue = new Queue(); +let queue : Queue = new Queue(); queue.add(2); queue.add(4); queue.add(5); queue.add(4); -queue.forEach((value, index) => { - console.log("value:" + value, "index:" + index); +queue.forEach((value : number, index : number) : void => { + console.log("value:" + value, "index:" + index); }); ``` @@ -231,15 +235,16 @@ queue.forEach((value, index) => { **示例:** ```ts -let queue = new Queue(); +let queue : Queue = new Queue(); queue.add(2); queue.add(4); queue.add(5); queue.add(4); // 使用方法一: -for (let item of queue) { - console.log("value:" + item); +while(queue.length) { + let item = queue.pop() + console.log("value:" + item); } // 使用方法二: diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md index 28ed005288246e57e76b77785a0a1e917314acbe..0c990ad6ab720c0f68020696d9d87604d16a2d18 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -63,7 +63,7 @@ reminderAgentManager.publishReminder(timer, (err: BusinessError, reminderId: num publishReminder(reminderReq: ReminderRequest): Promise\ -发布后台代理提醒。使用promisek异步回调。 +发布后台代理提醒。使用promise异步回调。 > **说明:** > diff --git a/zh-cn/application-dev/reference/apis/js-apis-shortKey.md b/zh-cn/application-dev/reference/apis/js-apis-shortKey.md index d75d180a12efdc91e279ed38b661658ce3a98c70..4225eb9afb57898b800a012599475b2ce49ac575 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-shortKey.md +++ b/zh-cn/application-dev/reference/apis/js-apis-shortKey.md @@ -1,10 +1,11 @@ # @ohos.multimodalInput.shortKey(快捷键) -通过本模块接口,可以设置快捷键拉起Ability的延迟时间,如设置长按快捷键3s后进行截屏等。 +通过本模块接口,可以设置快捷键拉起Ability的延迟时间,如设置长按快捷键3s后再截屏等。 > **说明:** > > - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> > - 本模块接口为系统接口。 ## 导入模块 @@ -17,7 +18,7 @@ import shortKey from '@ohos.multimodalInput.shortKey'; setKeyDownDuration(businessKey: string, delay: number, callback: AsyncCallback<void>): void -设置快捷键拉起Ability的延迟时间,使用AsyncCallback异步方式返回结果。 +设置快捷键拉起Ability的延迟时间,使用Callback异步回调。 **系统能力**:SystemCapability.MultimodalInput.Input.ShortKey @@ -25,9 +26,9 @@ setKeyDownDuration(businessKey: string, delay: number, callback: AsyncCallback&l | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------- | ---- | ------------------------------------------------------------ | -| businessKey| string | 是 | 业务在多模侧注册的唯一标识,与ability_launch_config.json中的businessId对应 | -| delay | number | 是 | 该值仅支持快捷键按下触发,表示按下快捷键多长时间后拉起Ability,单位是毫秒(ms) | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| businessKey| string | 是 | 业务在多模侧注册的唯一标识,与ability_launch_config.json中的businessId对应。 | +| delay | number | 是 | 按下快捷键多长时间后拉起Ability,单位是毫秒(ms),仅支持快捷键按下触发。 | +| callback | AsyncCallback<void> | 是 | 回调函数,设置成功时,err为undefined,否则为错误对象。 | **示例**: @@ -45,13 +46,11 @@ try { } ``` - - ## shortKey.setKeyDownDuration setKeyDownDuration(businessKey: string, delay: number): Promise<void> -设置快捷键拉起Ability的延迟时间,使用Promise异步方式返回结果。 +设置快捷键拉起Ability的延迟时间,使用Promise异步回调。 **系统能力**:SystemCapability.MultimodalInput.Input.ShortKey @@ -59,14 +58,14 @@ setKeyDownDuration(businessKey: string, delay: number): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | ------------------------------------------------------------ | -| businessKey| string | 是 | 业务在多模侧注册的唯一标识,与ability_launch_config.json中的businessId对应 | -| delay | number | 是 | 该值仅支持快捷键按下触发,表示按下快捷键多长时间后拉起Ability,单位是毫秒(ms) | +| businessKey| string | 是 | 业务在多模侧注册的唯一标识,与ability_launch_config.json中的businessId对应。 | +| delay | number | 是 | 按下快捷键多长时间后拉起Ability,单位是毫秒(ms),仅支持快捷键按下触发。 | **返回值**: | 参数 | 说明 | | ------------- | ------------- | -| Promise<void> | Promise对象。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-stack.md b/zh-cn/application-dev/reference/apis/js-apis-stack.md index 6569b0eb4ee259dc817cef8f394d84be878802ee..f8f3db16bc3f2d205c94c0aaca34ae13247e30df 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-stack.md +++ b/zh-cn/application-dev/reference/apis/js-apis-stack.md @@ -50,7 +50,7 @@ Stack的构造函数。 **示例:** ```ts -let stack = new Stack(); +let stack : Stack = new Stack(); ``` @@ -84,13 +84,17 @@ push(item: T): T **示例:** -```ts -let stack = new Stack(); +``` +class C1 { + name: string = "" + age: string = "" +} +let stack : Stack = new Stack(); let result = stack.push("a"); let result1 = stack.push(1); let b = [1, 2, 3]; let result2 = stack.push(b); -let c = {name : "Dylon", age : "13"}; +let c : C1 = {name : "Dylon", age : "13"}; let result3 = stack.push(c); ``` @@ -119,7 +123,7 @@ pop(): T **示例:** ```ts -let stack = new Stack(); +let stack : Stack = new Stack(); stack.push(2); stack.push(4); stack.push(5); @@ -153,7 +157,7 @@ peek(): T **示例:** ```ts -let stack = new Stack(); +let stack : Stack = new Stack(); stack.push(2); stack.push(4); stack.push(5); @@ -192,7 +196,7 @@ locate(element: T): number **示例:** ```ts -let stack = new Stack(); +let stack : Stack = new Stack(); stack.push(2); stack.push(4); stack.push(5); @@ -235,13 +239,13 @@ callbackfn的参数说明: **示例:** ```ts -let stack = new Stack(); +let stack : Stack = new Stack(); stack.push(2); stack.push(4); stack.push(5); stack.push(4); -stack.forEach((value, index) => { - console.log("value:" + value, "index:" + index); +stack.forEach((value : number, index : number) :void => { + console.log("value:" + value, "index:" + index); }); ``` @@ -270,7 +274,7 @@ isEmpty(): boolean **示例:** ```ts -let stack = new Stack(); +let stack : Stack = new Stack(); stack.push(2); stack.push(4); stack.push(5); @@ -302,15 +306,17 @@ let result = stack.isEmpty(); **示例:** ```ts -let stack = new Stack(); +let stack : Stack = new Stack(); stack.push(2); stack.push(4); stack.push(5); stack.push(4); // 使用方法一: -for (let item of stack) { - console.log("value:" + item); +while(!stack.isEmpty()) { + // 业务逻辑 + let item = stack.pop() + console.log("value:" + item); } // 使用方法二: diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md b/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md index 4425da3b8297899f2e2bcf8ef5a311c6b4893d57..9a2e0ed473c8eedb9e6c77189363b9f5709f625b 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @@ -12,6 +12,17 @@ import systemDateTime from '@ohos.systemDateTime'; ``` +## TimeType10+ + +定义获取时间的枚举类型。 + +**系统能力**: SystemCapability.MiscServices.Time + +| 名称 | 值 | 说明 | +| ------- | ---- | ------------------------------------------------ | +| STARTUP | 0 | 自系统启动以来经过的毫秒数,包括深度睡眠时间。 | +| ACTIVE | 1 | 自系统启动以来经过的毫秒数,不包括深度睡眠时间。 | + ## systemDateTime.setTime setTime(time : number, callback : AsyncCallback<void>) : void @@ -374,12 +385,75 @@ try { } ``` -## systemDateTime.setDate +## systemDateTime.getTime10+ + +getTime(isNanoseconds?: boolean): number + + 使用同步方式获取自Unix纪元以来经过的时间。 + +**系统能力:** SystemCapability.MiscServices.Time + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | ------- | ---- | ------------------------------------------------------------ | +| isNanoseconds | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。
默认值为false。 | + +**返回值**: + +| 类型 | 说明 | +| ------ | -------------------------- | +| number | 自Unix纪元以来经过的时间。 | + +**示例:** + +```js +try { + let time = systemDateTime.getTime(true) +} catch(e) { + console.info(`Failed to get time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getUptime10+ + +getUptime(timeType: TimeType, isNanoseconds?: boolean): number + + 使用同步方式获取自系统启动以来经过的时间。 + +**系统能力:** SystemCapability.MiscServices.Time + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | ----------------------- | ---- | ------------------------------------------------------------ | +| timeType | [TimeType](#timetype10) | 是 | 获取时间的类型。 | +| isNanoseconds | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。
默认值为false。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------------- | +| number | 自系统启动以来经过的时间。 | + +**示例:** + +```js +try { + let time = systemDateTime.getUpime(systemDate.TimeType.ACTIVE, false); +} catch(e) { + console.info(`Failed to get uptime. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.setDate(deprecated) setDate(date: Date, callback: AsyncCallback<void>): void 设置系统日期,使用callback异步回调。 +> **说明:** 从API version 9开始支持,从API 10开始废弃。建议使用[systemDateTime.setTime](#systemdatetimesettime)替代。 + **系统接口:** 此接口为系统接口 **系统能力:** SystemCapability.MiscServices.Time @@ -410,12 +484,14 @@ try { } ``` -## systemDateTime.setDate +## systemDateTime.setDate(deprecated) setDate(date: Date): Promise<void> 设置系统日期,使用Promise异步回调。 +> **说明:** 从API version 9开始支持,从API 10开始废弃。建议使用[systemDateTime.setTime](#systemdatetimesettime)替代。 + **系统接口:** 此接口为系统接口 **系统能力:** SystemCapability.MiscServices.Time @@ -449,12 +525,14 @@ try { } ``` -## systemDateTime.getDate +## systemDateTime.getDate(deprecated) getDate(callback: AsyncCallback<Date>): void 获取当前系统日期,使用callback异步回调。 +> **说明:** 从API version 9开始支持,从API 10开始废弃。建议使用new Date()替代,new Date()返回Date实例对象。 + **系统能力:** SystemCapability.MiscServices.Time **参数:** @@ -479,12 +557,14 @@ try { } ``` -## systemDateTime.getDate +## systemDateTime.getDate(deprecated) getDate(): Promise<Date> 获取当前系统日期,使用Promise异步回调。 +> **说明:** 从API version 9开始支持,从API 10开始废弃。建议使用new Date()替代,new Date()返回Date实例对象。 + **系统能力:** SystemCapability.MiscServices.Time **返回值:** @@ -638,6 +718,30 @@ try { } ``` +## systemDateTime.getTimezoneSync10+ + +getTimezoneSync(): string + +获取系统时区,使用同步方式。 + +**系统能力:** SystemCapability.MiscServices.Time + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------------------------------------- | +| string | 返回系统时区。具体可见[支持的系统时区](#支持的系统时区) 。 | + +**示例:** + +```js +try { + let timezone = systemDateTime.getTimezoneSync(); +} catch(e) { + console.info(`Failed to get timezone. message: ${e.message}, code: ${e.code}`); +} +``` + ## 支持的系统时区 支持的系统时区及各时区与0时区相比的偏移量(单位:h)可见下表。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md b/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md index 813277d8d46ad7f24e20b6e87a5abf3eda0c41ce..ebf5e3263cbe4ba170ec5b789a6c5ce40b6235d6 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @@ -14,7 +14,8 @@ ## 导入模块 ```ts -import systemparameter from '@ohos.systemparameter' +import systemparameter from '@ohos.systemparameter'; +import { BusinessError } from '@ohos.base'; ``` ## systemparameter.getSync(deprecated) @@ -42,7 +43,7 @@ getSync(key: string, def?: string): string ```ts try { - var info = systemparameter.getSync("const.ohos.apiversion"); + let info = systemparameter.getSync("const.ohos.apiversion"); console.log(JSON.stringify(info)); } catch(e) { console.log("getSync unexpected error: " + e); @@ -68,7 +69,7 @@ get(key: string, callback: AsyncCallback<string>): void ```ts try { - systemparameter.get("const.ohos.apiversion", function (err, data) { + systemparameter.get("const.ohos.apiversion", (err:BusinessError, data:string) => { if (err == undefined) { console.log("get test.parameter.key value success:" + data) } else { @@ -99,7 +100,7 @@ get(key: string, def: string, callback: AsyncCallback<string>): void ```ts try { - systemparameter.get("const.ohos.apiversion", "default", function (err, data) { + systemparameter.get("const.ohos.apiversion", "default", (err:BusinessError, data:string) => { if (err == undefined) { console.log("get test.parameter.key value success:" + data) } else { @@ -136,10 +137,10 @@ get(key: string, def?: string): Promise<string> ```ts try { - var p = systemparameter.get("const.ohos.apiversion"); - p.then(function (value) { + let p = systemparameter.get("const.ohos.apiversion"); + p.then((value:string) => { console.log("get test.parameter.key success: " + value); - }).catch(function (err) { + }).catch((err:BusinessError) => { console.log("get test.parameter.key error: " + err.code); }); } catch(e) { @@ -201,7 +202,7 @@ set(key: string, value: string, callback: AsyncCallback<void>): void ```ts try { - systemparameter.set("test.parameter.key", "testValue", function (err, data) { + systemparameter.set("test.parameter.key", "testValue", (err:BusinessError, data:string) =>{ if (err == undefined) { console.log("set test.parameter.key value success :" + data) } else { @@ -241,10 +242,10 @@ set(key: string, value: string): Promise<void> ```ts try { - var p = systemparameter.set("test.parameter.key", "testValue"); - p.then(function (value) { + let p = systemparameter.set("test.parameter.key", "testValue"); + p.then((value:string) => { console.log("set test.parameter.key success: " + value); - }).catch(function (err) { + }).catch((err:BusinessError) => { console.log(" set test.parameter.key error: " + err.code); }); } catch(e) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-parameterEnhance.md b/zh-cn/application-dev/reference/apis/js-apis-system-parameterEnhance.md index deb3aa478fd82c340b70cc088dda988e38ef1075..446d10c87d594a47bee6db382ac098d0ce46ac86 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-system-parameterEnhance.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-parameterEnhance.md @@ -13,7 +13,8 @@ ## 导入模块 ```ts -import systemparameter from '@ohos.systemParameterEnhance' +import systemparameter from '@ohos.systemParameterEnhance'; +import { BusinessError } from '@ohos.base'; ``` ## systemparameter.getSync @@ -41,7 +42,7 @@ getSync(key: string, def?: string): string ```ts try { - var info = systemparameter.getSync("const.ohos.apiversion"); + let info = systemparameter.getSync("const.ohos.apiversion"); console.log(JSON.stringify(info)); } catch(e) { console.log("getSync unexpected error: " + e); @@ -67,7 +68,7 @@ get(key: string, callback: AsyncCallback<string>): void ```ts try { - systemparameter.get("const.ohos.apiversion", function (err, data) { + systemparameter.get("const.ohos.apiversion", (err:BusinessError, data:string) => { if (err == undefined) { console.log("get test.parameter.key value success:" + data) } else { @@ -98,7 +99,7 @@ get(key: string, def: string, callback: AsyncCallback<string>): void ```ts try { - systemparameter.get("const.ohos.apiversion", "default", function (err, data) { + systemparameter.get("const.ohos.apiversion", "default", (err:BusinessError, data:string) => { if (err == undefined) { console.log("get test.parameter.key value success:" + data) } else { @@ -135,10 +136,10 @@ get(key: string, def?: string): Promise<string> ```ts try { - var p = systemparameter.get("const.ohos.apiversion"); - p.then(function (value) { + let p = systemparameter.get("const.ohos.apiversion"); + p.then((value:string) => { console.log("get test.parameter.key success: " + value); - }).catch(function (err) { + }).catch((err:BusinessError) => { console.log("get test.parameter.key error: " + err.code); }); } catch(e) { @@ -191,7 +192,7 @@ set(key: string, value: string, callback: AsyncCallback<void>): void ```ts try { - systemparameter.set("test.parameter.key", "testValue", function (err, data) { + systemparameter.set("test.parameter.key", "testValue", (err:BusinessError, data:string) => { if (err == undefined) { console.log("set test.parameter.key value success :" + data) } else { @@ -227,10 +228,10 @@ set(key: string, value: string): Promise<void> ```ts try { - var p = systemparameter.set("test.parameter.key", "testValue"); - p.then(function (value) { + let p = systemparameter.set("test.parameter.key", "testValue"); + p.then((value:string) => { console.log("set test.parameter.key success: " + value); - }).catch(function (err) { + }).catch((err:BusinessError) => { console.log(" set test.parameter.key error: " + err.code); }); } catch(e) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md index 02fc84bc6e34d9bc7d7a0efea7d96abf12669d57..ece8779b4bc2df81d18867824d7f3bbd694bcde0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-taskpool.md +++ b/zh-cn/application-dev/reference/apis/js-apis-taskpool.md @@ -51,12 +51,12 @@ execute(func: Function, ...args: unknown[]): Promise\ ```ts @Concurrent -function printArgs(args) { +function printArgs(args: number): number { console.log("printArgs: " + args); return args; } -taskpool.execute(printArgs, 100).then((value) => { // 100: test number +taskpool.execute(printArgs, 100).then((value: number) => { // 100: test number console.log("taskpool result: " + value); }); ``` @@ -96,13 +96,13 @@ execute(task: Task, priority?: Priority): Promise\ ```ts @Concurrent -function printArgs(args) { +function printArgs(args: number): number { console.log("printArgs: " + args); return args; } -let task = new taskpool.Task(printArgs, 100); // 100: test number -taskpool.execute(task).then((value) => { +let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number +taskpool.execute(task).then((value: number) => { console.log("taskpool result: " + value); }); ``` @@ -140,32 +140,28 @@ execute(group: TaskGroup, priority?: Priority): Promise ```ts @Concurrent -function printArgs(args) { +function printArgs(args: number): number { console.log("printArgs: " + args); return args; } -let taskGroup1 = new taskpool.TaskGroup(); +let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup1.addTask(printArgs, 10); // 10: test number taskGroup1.addTask(printArgs, 20); // 20: test number taskGroup1.addTask(printArgs, 30); // 30: test number -let taskGroup2 = new taskpool.TaskGroup(); -let task1 = new taskpool.Task(printArgs, 100); // 100: test number -let task2 = new taskpool.Task(printArgs, 200); // 200: test number -let task3 = new taskpool.Task(printArgs, 300); // 300: test number +let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); +let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number +let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number +let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number taskGroup2.addTask(task1); taskGroup2.addTask(task2); taskGroup2.addTask(task3); -taskpool.execute(taskGroup1).then((res) => { +taskpool.execute(taskGroup1).then((res: Array) => { console.info("taskpool execute res is:" + res); -}).catch((e) => { - console.error("taskpool execute error is:" + e); }); -taskpool.execute(taskGroup2).then((res) => { +taskpool.execute(taskGroup2).then((res: Array) => { console.info("taskpool execute res is:" + res); -}).catch((e) => { - console.error("taskpool execute error is:" + e); }); ``` @@ -198,41 +194,39 @@ cancel(task: Task): void ```ts @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled before 2s sleep."); - return arg + 2; - } - // 2s sleep - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled after 2s sleep."); - return arg + 3; - } - return arg + 1; +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 2s sleep + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; } -let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number -let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number -let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number -let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number -let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number -let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number -taskpool.execute(task1).then((res)=>{ +let task1: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number +let task2: taskpool.Task = new taskpool.Task(inspectStatus, 200); // 200: test number +let task3: taskpool.Task = new taskpool.Task(inspectStatus, 300); // 300: test number +let task4: taskpool.Task = new taskpool.Task(inspectStatus, 400); // 400: test number +let task5: taskpool.Task = new taskpool.Task(inspectStatus, 500); // 500: test number +let task6: taskpool.Task = new taskpool.Task(inspectStatus, 600); // 600: test number +taskpool.execute(task1).then((res: number)=>{ console.log("taskpool test result: " + res); -}).catch((err) => { - console.log("taskpool test occur error: " + err); }); -let res2 = taskpool.execute(task2); -let res3 = taskpool.execute(task3); -let res4 = taskpool.execute(task4); -let res5 = taskpool.execute(task5); -let res6 = taskpool.execute(task6); +taskpool.execute(task2); +taskpool.execute(task3); +taskpool.execute(task4); +taskpool.execute(task5); +taskpool.execute(task6); // 1s后取消task setTimeout(()=>{ taskpool.cancel(task1);}, 1000); @@ -264,23 +258,23 @@ cancel(group: TaskGroup): void ```ts @Concurrent -function printArgs(args) { - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + console.log("printArgs: " + args); + return args; } -let taskGroup1 = new taskpool.TaskGroup(); +let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup1.addTask(printArgs, 10); // 10: test number -let taskGroup2 = new taskpool.TaskGroup(); +let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup2.addTask(printArgs, 100); // 100: test number -taskpool.execute(taskGroup1).then((res)=>{ +taskpool.execute(taskGroup1).then((res: Array)=>{ console.info("taskGroup1 res is:" + res) }); -taskpool.execute(taskGroup2).then((res)=>{ +taskpool.execute(taskGroup2).then((res: Array)=>{ console.info("taskGroup2 res is:" + res) }); setTimeout(()=>{ @@ -310,7 +304,7 @@ getTaskPoolInfo(): TaskPoolInfo **示例:** ```ts -let taskpoolInfo = taskpool.getTaskPoolInfo(); +let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo(); ``` ## Priority @@ -329,35 +323,29 @@ let taskpoolInfo = taskpool.getTaskPoolInfo(); ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let task = new taskpool.Task(printArgs, 100); // 100: test number +let task: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number let highCount = 0; let mediumCount = 0; let lowCount = 0; let allCount = 100; -for (let i = 0; i < allCount; i++) { +for (let i: number = 0; i < allCount; i++) { taskpool.execute(task, taskpool.Priority.LOW).then((res: number) => { lowCount++; console.log("taskpool lowCount is :" + lowCount); - }).catch((e) => { - console.error("low task error: " + e); - }) + }); taskpool.execute(task, taskpool.Priority.MEDIUM).then((res: number) => { mediumCount++; console.log("taskpool mediumCount is :" + mediumCount); - }).catch((e) => { - console.error("medium task error: " + e); - }) + }); taskpool.execute(task, taskpool.Priority.HIGH).then((res: number) => { highCount++; console.log("taskpool highCount is :" + highCount); - }).catch((e) => { - console.error("high task error: " + e); - }) + }); } ``` @@ -392,12 +380,12 @@ Task的构造函数。 ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let task = new taskpool.Task(printArgs, "this is my first Task"); +let task: taskpool.Task = new taskpool.Task(printArgs, "this is my first Task"); ``` ### isCanceled10+ @@ -418,7 +406,7 @@ static isCanceled(): boolean ```ts @Concurrent -function inspectStatus(arg) { +function inspectStatus(arg: number): number { // do something if (taskpool.Task.isCanceled()) { console.log("task has been canceled."); @@ -437,29 +425,29 @@ function inspectStatus(arg) { ```ts @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled before 2s sleep."); - return arg + 2; - } - // 延时2s - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled after 2s sleep."); - return arg + 3; - } +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 延时2s + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } return arg + 1; } -let task = new taskpool.Task(inspectStatus, 100); // 100: test number -taskpool.execute(task).then((res)=>{ +let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number +taskpool.execute(task).then((res: number)=>{ console.log("taskpool test result: " + res); -}).catch((err) => { +}).catch((err: string) => { console.log("taskpool test occur error: " + err); }); // 不调用cancel,isCanceled()默认返回false,task执行的结果为101 @@ -485,24 +473,24 @@ setTransferList(transfer?: ArrayBuffer[]): void **示例:** ```ts -let buffer = new ArrayBuffer(8); -let view = new Uint8Array(buffer); -let buffer1 = new ArrayBuffer(16); -let view1 = new Uint8Array(buffer1); +let buffer: ArrayBuffer = new ArrayBuffer(8); +let view: Uint8Array = new Uint8Array(buffer); +let buffer1: ArrayBuffer = new ArrayBuffer(16); +let view1: Uint8Array = new Uint8Array(buffer1); console.info("testTransfer view byteLength: " + view.byteLength); console.info("testTransfer view1 byteLength: " + view1.byteLength); @Concurrent -function testTransfer(arg1, arg2) { +function testTransfer(arg1: ArrayBuffer, arg2: ArrayBuffer): number { console.info("testTransfer arg1 byteLength: " + arg1.byteLength); console.info("testTransfer arg2 byteLength: " + arg2.byteLength); return 100; } -let task = new taskpool.Task(testTransfer, view, view1); +let task: taskpool.Task = new taskpool.Task(testTransfer, view, view1); task.setTransferList([view.buffer, view1.buffer]); -taskpool.execute(task).then((res)=>{ +taskpool.execute(task).then((res: number)=>{ console.info("test result: " + res); -}).catch((e)=>{ +}).catch((e: string)=>{ console.error("test catch: " + e); }) console.info("testTransfer view byteLength: " + view.byteLength); @@ -563,12 +551,12 @@ addTask(func: Function, ...args: unknown[]): void ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let taskGroup = new taskpool.TaskGroup(); +let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup.addTask(printArgs, 100); // 100: test number ``` @@ -598,13 +586,13 @@ addTask(task: Task): void ```ts @Concurrent -function printArgs(args) { - console.log("printArgs: " + args); - return args; +function printArgs(args: number): number { + console.log("printArgs: " + args); + return args; } -let taskGroup = new taskpool.TaskGroup(); -let task = new taskpool.Task(printArgs, 200); // 200: test number +let taskGroup: taskpool.TaskGroup = new taskpool.TaskGroup(); +let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number taskGroup.addTask(task); ``` @@ -675,12 +663,6 @@ taskGroup.addTask(task); ### 序列化支持类型 序列化支持类型包括:All Primitive Type(不包括symbol)、Date、String、RegExp、Array、Map、Set、Object、ArrayBuffer、TypedArray。 -### 注意事项 -- 仅支持在Stage模型且module的compileMode为esmodule的project中使用taskpool api。确认module的compileMode方法:查看当前module的build-profile.json5,在buildOption中补充"compileMode": "esmodule"。 -- taskpool任务只支持引用入参传递或者import的变量,不支持使用闭包变量,使用装饰器@Concurrent进行拦截。 -- taskpool任务只支持普通函数或者async函数,不支持类成员函数或者匿名函数,使用装饰器@Concurrent进行拦截。 -- 装饰器@Concurrent仅支持在ets文件使用。 - ### 简单使用 **示例一** @@ -688,22 +670,17 @@ taskGroup.addTask(task); ```ts // 支持普通函数、引用入参传递 @Concurrent -function printArgs(args) { - console.log("func: " + args); - return args; +function printArgs(args: number): number { + console.log("func: " + args); + return args; } - -async function taskpoolExecute() { +async function taskpoolExecute(): Promise { // taskpool.execute(task) - let task = new taskpool.Task(printArgs, "create task, then execute"); - let val1 = await taskpool.execute(task); - console.log("taskpool.execute(task) result: " + val1); - + let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute"); + console.log("taskpool.execute(task) result: " + await taskpool.execute(task)); // taskpool.execute(function) - let val2 = await taskpool.execute(printArgs, "execute task by func"); - console.log("taskpool.execute(function) result: " + val2); + console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func")); } - taskpoolExecute(); ``` @@ -711,7 +688,7 @@ taskpoolExecute(); ```ts // b.ets -export let c = 2000; +export let c: number = 2000; ``` ```ts // 引用import变量 @@ -719,7 +696,7 @@ export let c = 2000; import { c } from "./b"; @Concurrent -function printArgs(a) { +function printArgs(a: number): number { console.log(a); console.log(c); return a; @@ -727,13 +704,11 @@ function printArgs(a) { async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(printArgs, "create task, then execute"); - let val1 = await taskpool.execute(task); - console.log("taskpool.execute(task) result: " + val1); + let task: taskpool.Task = new taskpool.Task(printArgs, "create task, then execute"); + console.log("taskpool.execute(task) result: " + await taskpool.execute(task)); // taskpool.execute(function) - let val2 = await taskpool.execute(printArgs, "execute task by func"); - console.log("taskpool.execute(function) result: " + val2); + console.log("taskpool.execute(function) result: " + await taskpool.execute(printArgs, "execute task by func")); } taskpoolExecute(); @@ -752,8 +727,10 @@ async function delayExcute() { } async function taskpoolExecute() { - taskpool.execute(delayExcute).then((result) => { - console.log("TaskPoolTest task result: " + result); + taskpool.execute(delayExcute).then((result: string) => { + console.log("taskPoolTest task result: " + result); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); }); } @@ -765,24 +742,25 @@ taskpoolExecute(); ```ts // c.ets @Concurrent -function strSort(inPutArr) { +function strSort(inPutArr: Array): Array { let newArr = inPutArr.sort(); return newArr; } export async function func1() { - console.log("taskpoolTest start"); - let strArray = ['c test string', 'b test string', 'a test string']; - let task = new taskpool.Task(strSort, strArray); - let result = await taskpool.execute(task); - console.log("func1 result:" + result); + console.log("taskpoolTest start"); + let strArray: Array = ['c test string', 'b test string', 'a test string']; + let task: taskpool.Task = new taskpool.Task(strSort, strArray); + console.log("func1 result:" + await taskpool.execute(task)); } export async function func2() { - console.log("taskpoolTest2 start"); - let strArray = ['c test string', 'b test string', 'a test string']; - taskpool.execute(strSort, strArray).then((result) => { - console.log("func2 result: " + result); - }); + console.log("taskpoolTest2 start"); + let strArray: Array = ['c test string', 'b test string', 'a test string']; + taskpool.execute(strSort, strArray).then((result: Array) => { + console.log("func2 result: " + result); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); + }); } ``` @@ -799,35 +777,35 @@ func2(); ```ts // 任务取消成功 @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled before 2s sleep."); - return arg + 2; - } - // 2s sleep - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - console.log("task has been canceled after 2s sleep."); - return arg + 3; - } - return arg + 1; +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled before 2s sleep."); + return arg + 2; + } + // 2s sleep + let t: number = Date.now(); + while (Date.now() - t < 2000) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + console.log("task has been canceled after 2s sleep."); + return arg + 3; + } + return arg + 1; } -async function taskpoolCancel() { - let task = new taskpool.Task(inspectStatus, 100); // 100: test number - taskpool.execute(task).then((res)=>{ - console.log("taskpool test result: " + res); - }).catch((err) => { - console.log("taskpool test occur error: " + err); - }); - // 1s后取消task - setTimeout(()=>{ - taskpool.cancel(task);}, 1000); +async function taskpoolCancel(): Promise { + let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res: number)=>{ + console.log("taskpool test result: " + res); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); + }); + // 1s后取消task + setTimeout(()=>{ + taskpool.cancel(task);}, 1000); } taskpoolCancel(); @@ -838,37 +816,38 @@ taskpoolCancel(); ```ts // 已执行的任务取消失败 @Concurrent -function inspectStatus(arg) { - // 第一时间检查取消并回复 - if (taskpool.Task.isCanceled()) { - return arg + 2; - } - // 延时2s - let t = Date.now(); - while (Date.now() - t < 2000) { - continue; - } - // 第二次检查取消并作出响应 - if (taskpool.Task.isCanceled()) { - return arg + 3; - } - return arg + 1; +function inspectStatus(arg: number): number { + // 第一时间检查取消并回复 + if (taskpool.Task.isCanceled()) { + return arg + 2; + } + // 延时2s + let t: number = Date.now(); + while (Date.now() - t < 500) { + continue; + } + // 第二次检查取消并作出响应 + if (taskpool.Task.isCanceled()) { + return arg + 3; + } + return arg + 1; } -async function taskpoolCancel() { - let task = new taskpool.Task(inspectStatus, 100); // 100: test number - taskpool.execute(task).then((res)=>{ - console.log("taskpool test result: " + res); - }).catch((err) => { - console.log("taskpool test occur error: " + err); - }); - setTimeout(()=>{ - try { - taskpool.cancel(task); // 任务已执行,取消失败 - } catch (e) { - console.log("taskpool.cancel occur error:" + e); - } - }, 3000); // 延时3s,确保任务已执行 +async function taskpoolCancel(): Promise { + let task: taskpool.Task = new taskpool.Task(inspectStatus, 100); // 100: test number + taskpool.execute(task).then((res: number)=>{ + console.log("taskpool test result: " + res); + }).catch((err: string) => { + console.log("taskpool test occur error: " + err); + }); + + setTimeout(()=>{ + try { + taskpool.cancel(task); // 任务已执行,取消失败 + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } + }, 3000); // 延时3s,确保任务已执行 } taskpoolCancel(); @@ -879,8 +858,8 @@ taskpoolCancel(); ```ts // 待执行的任务组取消成功 @Concurrent -function printArgs(args) { - let t = Date.now(); +function printArgs(args: number): number { + let t: number = Date.now(); while (Date.now() - t < 1000) { continue; } @@ -888,26 +867,26 @@ function printArgs(args) { return args; } -async function taskpoolGroupCancelTest() { - let taskGroup1 = new taskpool.TaskGroup(); +async function taskpoolGroupCancelTest(): Promise { + let taskGroup1: taskpool.TaskGroup = new taskpool.TaskGroup(); taskGroup1.addTask(printArgs, 10); // 10: test number taskGroup1.addTask(printArgs, 20); // 20: test number taskGroup1.addTask(printArgs, 30); // 30: test number - let taskGroup2 = new taskpool.TaskGroup(); - let task1 = new taskpool.Task(printArgs, 100); // 100: test number - let task2 = new taskpool.Task(printArgs, 200); // 200: test number - let task3 = new taskpool.Task(printArgs, 300); // 300: test number + let taskGroup2: taskpool.TaskGroup = new taskpool.TaskGroup(); + let task1: taskpool.Task = new taskpool.Task(printArgs, 100); // 100: test number + let task2: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number + let task3: taskpool.Task = new taskpool.Task(printArgs, 300); // 300: test number taskGroup2.addTask(task1); taskGroup2.addTask(task2); taskGroup2.addTask(task3); - taskpool.execute(taskGroup1).then((res) => { + taskpool.execute(taskGroup1).then((res: Array) => { console.info("taskpool execute res is:" + res); - }).catch((e) => { + }).catch((e: string) => { console.error("taskpool execute error is:" + e); }); - taskpool.execute(taskGroup2).then((res) => { + taskpool.execute(taskGroup2).then((res: Array) => { console.info("taskpool execute res is:" + res); - }).catch((e) => { + }).catch((e: string) => { console.error("taskpool execute error is:" + e); }); @@ -922,48 +901,48 @@ taskpoolGroupCancelTest() ```ts // 分别创建执行100个高、中、低优先级的任务,查看其各项信息 @Concurrent -function delay() { - let start = new Date().getTime(); +function delay(): void { + let start: number = new Date().getTime(); while (new Date().getTime() - start < 500) { continue; } } -let highCount = 0; -let mediumCount = 0; -let lowCount = 0; -let allCount = 100; +let highCount: number = 0; +let mediumCount: number = 0; +let lowCount: number = 0; +let allCount: number = 100; for (let i = 0; i < allCount; i++) { - let task1 = new taskpool.Task(delay); - let task2 = new taskpool.Task(delay); - let task3 = new taskpool.Task(delay); + let task1: taskpool.Task = new taskpool.Task(delay); + let task2: taskpool.Task = new taskpool.Task(delay); + let task3: taskpool.Task = new taskpool.Task(delay); taskpool.execute(task1, taskpool.Priority.LOW).then(() => { lowCount++; - }).catch((e) => { + }).catch((e: string) => { console.error("low task error: " + e); }) taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => { mediumCount++; - }).catch((e) => { + }).catch((e: string) => { console.error("medium task error: " + e); }) taskpool.execute(task3, taskpool.Priority.HIGH).then(() => { highCount++; - }).catch((e) => { + }).catch((e: string) => { console.error("high task error: " + e); }) } -let start = new Date().getTime(); +let start: number = new Date().getTime(); while (new Date().getTime() - start < 1000) { - continue; -} -let taskpoolInfo = taskpool.getTaskPoolInfo(); -let tid = 0; -let taskIds = []; -let priority = 0; -let taskId = 0; -let state = 0; -let duration = 0; + continue; +} +let taskpoolInfo: taskpool.TaskPoolInfo = taskpool.getTaskPoolInfo(); +let tid: number = 0; +let taskIds: Array = []; +let priority: number = 0; +let taskId: number = 0; +let state: number = 0; +let duration: number = 0; for(let threadInfo of taskpoolInfo.threadInfos) { tid = threadInfo.tid; taskIds.length = threadInfo.taskIds.length; diff --git a/zh-cn/application-dev/reference/apis/js-apis-touchevent.md b/zh-cn/application-dev/reference/apis/js-apis-touchevent.md index 4bc994191c9cbf6f09c7cf1820e9b28ca5b71a82..2a42be88e309ea3f69f5f0b448d89cd00683b657 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-touchevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-touchevent.md @@ -1,6 +1,6 @@ # @ohos.multimodalInput.touchEvent (触摸输入事件) -设备上报的触屏事件。 +设备上报的触摸(触屏)事件。 > **说明:** > @@ -14,7 +14,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ## Action -触屏事件类型。 +触摸事件类型。 **系统能力**:SystemCapability.MultimodalInput.Input.Core @@ -27,7 +27,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ## ToolType -操作触屏的工具类型。 +操作触摸的工具类型。 **系统能力**:SystemCapability.MultimodalInput.Input.Core @@ -52,7 +52,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | ------------ | ------ | ---- | | TOUCH_SCREEN | 0 | 触摸屏 | | PEN | 1 | 手写笔 | -| TOUCH_PAD | 2 | 触摸板 | +| TOUCH_PAD | 2 | 触控板 | ## Touch @@ -63,7 +63,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------- | ------ | ---- | ---- | ----------------------------------- | | id | number | 是 | 否 | 触摸事件标识 | -| pressedTime | number | 是 | 否 | 按下时间戳 | +| pressedTime | number | 是 | 否 | 按下时间戳,单位为微秒(μs) | | screenX | number | 是 | 否 | 触摸位置所属的屏幕x坐标 | | screenY | number | 是 | 否 | 触摸位置所属的屏幕y坐标 | | windowX | number | 是 | 否 | 触摸位置在窗口中的x坐标 | @@ -71,15 +71,15 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | pressure | number | 是 | 否 | 压力值,取值范围是[0.0, 1.0], 0.0表示不支持 | | width | number | 是 | 否 | 触摸区域的宽度 | | height | number | 是 | 否 | 触摸区域的高度 | -| tiltX | number | 是 | 否 | 相对YZ平面的角度,取值的范围[-90, 90],其中正值是向右倾斜。 | -| tiltY | number | 是 | 否 | 相对XZ平面的角度,值的范围[-90, 90],其中正值是向下倾斜。 | +| tiltX | number | 是 | 否 | 相对YZ平面的角度,取值的范围[-90, 90],其中正值是向右倾斜 | +| tiltY | number | 是 | 否 | 相对XZ平面的角度,值的范围[-90, 90],其中正值是向下倾斜 | | toolX | number | 是 | 否 | 工具区域的中心点x坐标 | | toolY | number | 是 | 否 | 工具区域的中心点y坐标 | | toolWidth | number | 是 | 否 | 工具区域宽度 | | toolHeight | number | 是 | 否 | 工具区域高度 | | rawX | number | 是 | 否 | 输入设备上的x坐标 | | rawY | number | 是 | 否 | 输入设备上的y坐标 | -| toolType | ToolType | 是 | 否 | 工具类型 | +| toolType | [ToolType](#tooltype) | 是 | 否 | 工具类型 | ## TouchEvent @@ -89,7 +89,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------- | ---------- | ---- | ---- | --------- | -| action | Action | 是 | 否 | 触摸动作 | -| touch | Touch | 是 | 否 | 当前触摸点 | +| action | [Action](#action) | 是 | 否 | 触屏事件类型 | +| touch | [Touch](#touch) | 是 | 否 | 当前触摸点信息 | | touches | Touch[] | 是 | 否 | 所有触摸点 | -| sourceType | SourceType | 是 | 否 | 触摸来源的设备类型 | +| sourceType | [SourceType](#sourcetype) | 是 | 否 | 触摸来源的设备类型 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-treemap.md b/zh-cn/application-dev/reference/apis/js-apis-treemap.md index 439e6c1d006929a558b1becb2ff8591cf2161282..b8ebb8f4696687555f293e8e8d2b02660a582d28 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treemap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treemap.md @@ -61,7 +61,7 @@ TreeMap的构造函数。 **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); ``` @@ -90,7 +90,7 @@ isEmpty(): boolean **示例:** ```ts -const treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); let result = treeMap.isEmpty(); ``` @@ -126,7 +126,7 @@ hasKey(key: K): boolean **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); let result = treeMap.hasKey("squirrel"); ``` @@ -163,7 +163,7 @@ hasValue(value: V): boolean **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); let result = treeMap.hasValue(123); ``` @@ -200,7 +200,7 @@ get(key: K): V **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.get("sparrow"); @@ -232,7 +232,7 @@ getFirstKey(): K **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getFirstKey(); @@ -264,7 +264,7 @@ getLastKey(): K **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getLastKey(); @@ -296,13 +296,13 @@ setAll(map: TreeMap): void **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); -let map = new TreeMap(); +let map : TreeMap = new TreeMap(); map.set("demo", 12); map.setAll(treeMap); // 将treeMap中的所有元素添加到map中 -map.forEach((value, key) => { +map.forEach((value : number, key : string) : void => { console.log("value" + value, "key" + key); // 打印结果 12 demo、356 sparrow、123 squirrel }) ``` @@ -340,7 +340,7 @@ set(key: K, value: V): Object **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); ``` @@ -376,7 +376,7 @@ remove(key: K): V **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.remove("sparrow"); @@ -414,7 +414,7 @@ getLowerKey(key: K): K **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); @@ -453,7 +453,7 @@ getHigherKey(key: K): K **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); @@ -492,7 +492,7 @@ replace(key: K, newValue: V): boolean **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("sparrow", 123); let result = treeMap.replace("sparrow", 357); ``` @@ -517,7 +517,7 @@ clear(): void **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.clear(); @@ -549,14 +549,14 @@ keys(): IterableIterator<K> **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); -let iter = treeMap.keys(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let it = treeMap.values(); +let t = it.next(); +while(!t.done) { + console.log(t.value); + t = it.next() } ``` @@ -586,14 +586,14 @@ values(): IterableIterator<V> **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); -let iter = treeMap.values(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let it = treeMap.values(); +let t = it.next(); +while(!t.done) { + console.log(t.value); + t = it.next() } ``` @@ -631,11 +631,11 @@ callbackFn的参数说明: **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("sparrow", 123); treeMap.set("gull", 357); -treeMap.forEach((value, key) => { - console.log("value:" + value, "key:" + key); +treeMap.forEach((value : number, key : string) : void => { + console.log("value:" + value, "key:" + key); }); ``` @@ -665,15 +665,14 @@ entries(): IterableIterator<[K, V]> **示例:** ```ts -let treeMap = new TreeMap(); +let treeMap : TreeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); -let iter = treeMap.entries(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("key:" + temp[0]); - console.log("value:" + temp[1]); - temp = iter.next().value; +let it = treeMap.entries(); +let t = it.next(); +while(!t.done) { + console.log(t.value); + t = it.next() } ``` @@ -707,10 +706,11 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); // 使用方法一: -for (let item of treeMap) { - console.log("key:" + item[0]); - console.log("value:" + item[1]); -} +let it = treeMap.entries(); +let t = it.next(); +while(!t.done) { + console.log(t.value); + t = it.next() // 使用方法二: let iter = treeMap[Symbol.iterator](); diff --git a/zh-cn/application-dev/reference/apis/js-apis-treeset.md b/zh-cn/application-dev/reference/apis/js-apis-treeset.md index 5bec11a44f1f995c287f3261e827ebc3a8b38a92..15d2f21484e732428c828e95925b925929f5231c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treeset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treeset.md @@ -57,7 +57,7 @@ TreeSet的构造函数。 **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); ``` @@ -86,7 +86,7 @@ isEmpty(): boolean **示例:** ```ts -const treeSet = new TreeSet(); +const treeSet : TreeSet = new TreeSet(); let result = treeSet.isEmpty(); ``` @@ -122,12 +122,11 @@ has(value: T): boolean **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add(123); let result = treeSet.has(123); ``` - ### getFirstValue getFirstValue(): T @@ -153,7 +152,7 @@ getFirstValue(): T **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getFirstValue(); @@ -185,7 +184,7 @@ getLastValue(): T **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getLastValue(); @@ -223,7 +222,7 @@ add(value: T): boolean **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); let result = treeSet.add("squirrel"); ``` @@ -259,7 +258,7 @@ remove(value: T): boolean **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.remove("sparrow"); @@ -297,7 +296,7 @@ getLowerValue(key: T): T **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); @@ -336,7 +335,7 @@ getHigherValue(key: T): T **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); @@ -369,7 +368,7 @@ popFirst(): T **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popFirst(); @@ -401,7 +400,7 @@ popLast(): T **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popLast(); @@ -427,7 +426,7 @@ clear(): void **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.clear(); @@ -459,14 +458,14 @@ values(): IterableIterator<T> **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); -let iter = treeSet.values(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("value:" + temp); - temp = iter.next().value; +let it = treeSet.values(); +let t = it.next(); +while(!t.done) { + console.log(t.value); + t = it.next() } ``` @@ -504,11 +503,11 @@ callbackFn的参数说明: **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("sparrow"); treeSet.add("gull"); -treeSet.forEach((value, key) => { - console.log("value:" + value, "key:" + key); +treeSet.forEach((value : string, key : string) :void => { + console.log("value:" + value, "key:" + key); }); ``` @@ -538,15 +537,14 @@ entries(): IterableIterator<[T, T]> **示例:** ```ts -let treeSet = new TreeSet(); +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); -let iter = treeSet.entries(); -let temp = iter.next().value; -while(temp != undefined) { - console.log("key:" + temp[0]); - console.log("value:" + temp[1]); - temp = iter.next().value; +let it = treeSet.entries(); +let t = it.next(); +while(!t.done) { + console.log(t.value); + t = it.next() } ``` @@ -576,15 +574,15 @@ while(temp != undefined) { **示例:** ```ts -let treeSet = new TreeSet(); + +let treeSet : TreeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); - +let numbers = Array.from(treeSet.values()) // 使用方法一: -for (let item of treeSet) { +for (let item of numbers) { console.log("value:" + item); } - // 使用方法二: let iter = treeSet[Symbol.iterator](); let temp = iter.next().value; diff --git a/zh-cn/application-dev/reference/apis/js-apis-vector.md b/zh-cn/application-dev/reference/apis/js-apis-vector.md index c497f8b3afccefe75d5c97855c1cdf026d7beac7..a01b694cf650e4f7b57f7b33d549ae00f44975fd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vector.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vector.md @@ -44,7 +44,7 @@ Vector的构造函数。 **示例:** ```ts -let vector = new Vector(); +let vector : Vector> = new Vector(); ``` @@ -71,12 +71,16 @@ add(element: T): boolean **示例:** ```ts -let vector = new Vector(); +class C1 { + name: string = "" + age: string = "" +} +let vector : Vector> = new Vector(); let result = vector.add("a"); let result1 = vector.add(1); let b = [1, 2, 3]; let result2 = vector.add(b); -let c = {name : "Dylon", age : "13"}; +let c: C1 = {name : "Dylon", age : "13"}; let result3 = vector.add(c); ``` @@ -98,7 +102,7 @@ insert(element: T, index: number): void **示例:** ```ts -let vector = new Vector(); +let vector : Vector> = new Vector(); vector.insert("A", 0); vector.insert(0, 1); vector.insert(true, 2); @@ -127,7 +131,7 @@ has(element: T): boolean **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); let result = vector.has("squirrel"); vector.add("squirrel"); let result1 = vector.has("squirrel"); @@ -156,7 +160,7 @@ getIndexOf(element: T): number **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -190,7 +194,7 @@ getLastIndexOf(element: T): number **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -224,7 +228,7 @@ removeByIndex(index: number): T **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -256,7 +260,7 @@ remove(element: T): boolean **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -282,7 +286,7 @@ removeByRange(fromIndex: number, toIndex: number): void **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -317,14 +321,14 @@ callbackfn的参数说明: **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); vector.add(4); -vector.replaceAllElements((value) => { - // 用户操作逻辑根据实际场景进行添加。 - return value; +vector.replaceAllElements((value : number) : number => { + // 用户操作逻辑根据实际场景进行添加。 + return value; }); ``` @@ -355,15 +359,14 @@ callbackfn的参数说明: **示例:** ```ts -let vector = new Vector(); +let vector : Vector> = new Vector(); vector.add(2); vector.add(4); vector.add(5); vector.add(4); -vector.forEach((value, index) => { - console.log("value:" + value, "index:" + index); +vector.forEach((value : Vector> , index : number) : void => { + console.log("value:" + value, "index:" + index); }); - ``` ### sort @@ -390,7 +393,7 @@ comparator的参数说明: **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -424,7 +427,7 @@ subVector(fromIndex: number, toIndex: number): Vector<T> **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -447,7 +450,7 @@ clear(): void **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -472,7 +475,7 @@ clone(): Vector<T> **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -497,7 +500,7 @@ getCapacity(): number **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -522,7 +525,7 @@ convertToArray(): Array<T> **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -547,7 +550,7 @@ isEmpty(): boolean **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -572,7 +575,7 @@ increaseCapacityTo(newCapacity: number): void **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -592,7 +595,7 @@ trimToCurrentLength(): void **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -617,7 +620,7 @@ toString(): string **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -656,7 +659,7 @@ getFirstElement(): T **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -681,7 +684,7 @@ getLastElement(): T **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -713,7 +716,7 @@ getLastIndexFrom(element: T, index: number): number **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -746,7 +749,7 @@ getIndexFrom(element: T, index: number): number **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -772,7 +775,7 @@ setLength(newSize: number): void **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); @@ -803,14 +806,14 @@ get(index: number): T **示例:** - ```ts - let vector = new Vector(); - vector.add(2); - vector.add(4); - vector.add(5); - vector.add(4); - let result = vector.get(2); - ``` +```ts +let vector : Vector = new Vector(); +vector.add(2); +vector.add(4); +vector.add(5); +vector.add(4); +let result = vector.get(2); +``` ### set set(index: number, element: T): T @@ -848,16 +851,16 @@ set(index: number, element: T): T **示例:** ```ts -let vector = new Vector(); +let vector : Vector = new Vector(); vector.add(2); vector.add(4); vector.add(5); vector.add(4); - // 使用方法一: -for (let item of vector) { - console.log("value:" + item); -} +let nums: Array = vector.convertToArray() +for (let item of nums) { + console.log("value:" + item); +} // 使用方法二: let iter = vector[Symbol.iterator](); diff --git a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md index 4b07abbbc692bfff851eab2f465e1bbc425ac726..247291bf59a7e2e236a2789c7d1f209e69b8fac8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md @@ -17,7 +17,7 @@ import vibrator from '@ohos.vibrator'; startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void -根据指定振动效果和振动属性触发马达振动。 +根据指定的振动效果和振动属性触发马达振动。使用callback异步回调。 **需要权限**:ohos.permission.VIBRATE @@ -67,7 +67,7 @@ try { startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> -根据指定振动效果和振动属性触发马达振动。 +根据指定的振动效果和振动属性触发马达振动。使用promise异步回调。 **需要权限**:ohos.permission.VIBRATE @@ -84,7 +84,7 @@ startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<v | 类型 | 说明 | | ------------------- | -------------------------------------- | -| Promise<void> | Promise对象。 | +| Promise<void> | 无返回结果的Promise对象。 | **错误码**: @@ -120,7 +120,7 @@ try { stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void -按照指定模式停止马达的振动。 +按照指定模式停止马达振动。使用callback异步回调。 **需要权限**:ohos.permission.VIBRATE @@ -175,7 +175,7 @@ try { stopVibration(stopMode: VibratorStopMode): Promise<void> -按照指定模式停止马达的振动。 +按照指定模式停止马达的振动。使用promise异步回调。 **需要权限**:ohos.permission.VIBRATE @@ -185,7 +185,7 @@ stopVibration(stopMode: VibratorStopMode): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------ | -| stopMode | [VibratorStopMode](#vibratorstopmode) | 是 | 马达停止指定的振动模式。 | +| stopMode | [VibratorStopMode](#vibratorstopmode) | 是 | 指定的停止振动模式。 | **返回值:** @@ -231,7 +231,7 @@ try { stopVibration(callback: AsyncCallback<void>): void -停止所有模式的马达振动。 +停止所有模式的马达振动。使用callback异步回调。 **需要权限**:ohos.permission.VIBRATE @@ -285,7 +285,7 @@ try { stopVibration(): Promise<void> -停止所有模式的马达振动。 +停止所有模式的马达振动。使用promise异步回调。 **需要权限**:ohos.permission.VIBRATE @@ -335,7 +335,7 @@ try { isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void -查询是否支持传入的参数effectId。 +查询是否支持传入参数effectId。使用callback异步回调。 **系统能力**:SystemCapability.Sensors.MiscDevice @@ -343,7 +343,7 @@ isSupportEffect(effectId: string, callback: AsyncCallback<boolean>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | ------------------------------------------------------ | -| effectId | string | 是 | 振动效果id | +| effectId | string | 是 | 预置的振动效果。 | | callback | AsyncCallback<boolean> | 是 | 回调函数,当返回true则表示支持该effectId,否则不支持。 | **示例:** @@ -388,7 +388,7 @@ try { isSupportEffect(effectId: string): Promise<boolean> -查询是否支持传入的参数effectId。 +查询是否支持传入参数effectId。使用promise异步回调。 **系统能力**:SystemCapability.Sensors.MiscDevice @@ -396,7 +396,7 @@ isSupportEffect(effectId: string): Promise<boolean> | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------ | -| effectId | string | 是 | 振动效果id。 | +| effectId | string | 是 | 预置的振动效果。 | **返回值:** @@ -446,19 +446,19 @@ try { | 名称 | 值 | 说明 | | ------------------ | -------------------- | -------------------------------- | -| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | 描述用户调整计时器时的振动效果。 | +| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | 描述用户调整计时器时的振动效果。| ## VibratorStopMode -停止的振动模式。 +停止振动的模式。 **系统能力**:SystemCapability.Sensors.MiscDevice | 名称 | 值 | 说明 | | ------------------------- | -------- | ------------------------------ | -| VIBRATOR_STOP_MODE_TIME | "time" | 停止模式为duration模式的振动。 | -| VIBRATOR_STOP_MODE_PRESET | "preset" | 停止模式为预置EffectId的振动。 | +| VIBRATOR_STOP_MODE_TIME | "time" | 停止duration模式的振动。 | +| VIBRATOR_STOP_MODE_PRESET | "preset" | 停止预置EffectId的振动。| ## VibrateEffect9+ @@ -526,7 +526,7 @@ try { | 名称 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | -------------- | -| id | number | 否 | 默认值为0,振动器id。 | +| id | number | 否 | 振动器id, 默认值为0。 | | usage | [Usage](#usage9) | 是 | 马达振动的使用场景。 | ## Usage9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-webview.md b/zh-cn/application-dev/reference/apis/js-apis-webview.md index a00afebb8b707f7caefd3b861f21f4daebe938c9..7943f9e0ebca639027b8e006fead1d80ec3f8a20 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webview.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webview.md @@ -518,7 +518,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log("EntryAbility onCreate") try { - web_webview.WebviewController.setHttpDns(web_webview.SecureDnsMode.Auto, "https://example1.test") + web_webview.WebviewController.setHttpDns(web_webview.SecureDnsMode.AUTO, "https://example1.test") } catch(error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -6493,9 +6493,6 @@ Web組件使用HTTPDNS的模式。 | 名称 | 值 | 说明 | | ------------- | -- |----------------------------------------- | -| Off(deprecated) | 0 |不使用HTTPDNS, 可以用于撤销之前使用的HTTPDNS配置。
从API version 10开始不再维护,建议使用OFF代替。| -| Auto(deprecated) | 1 |自动模式,用于解析的设定dns服务器不可用时,可自动回落至系统DNS。
从API version 10开始不再维护,建议使用AUTO代替。| -| SecureOnly(deprecated) | 2 |强制使用设定的HTTPDNS服务器进行域名解析。
从API version 10开始不再维护,建议使用SECURE_ONLY代替。| | OFF | 0 |不使用HTTPDNS, 可以用于撤销之前使用的HTTPDNS配置。| | AUTO | 1 |自动模式,用于解析的设定dns服务器不可用时,可自动回落至系统DNS。| | SECURE_ONLY | 2 |强制使用设定的HTTPDNS服务器进行域名解析。| \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifi.md b/zh-cn/application-dev/reference/apis/js-apis-wifi.md index d1c1cd4080bbeb6168055b5be52b95c1ea21dbed..faf695a3f88d29754c2c95d76d5ee0bd7ba58d5a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifi.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifi.md @@ -2256,12 +2256,14 @@ wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); ``` -## wifi.on('streamChange')7+ +## wifi.on('streamChange')9+ on(type: "streamChange", callback: Callback<number>): void 注册WIFI流更改事件。 +**系统接口:** 此接口为系统接口。 + **需要权限:** ohos.permission.MANAGE_WIFI_CONNECTION **系统能力:** SystemCapability.Communication.WiFi.STA @@ -2273,22 +2275,24 @@ on(type: "streamChange", callback: Callback<number>): void | type | string | 是 | 固定填"streamChange"字符串。 | | callback | Callback<number> | 是 | 状态改变回调函数,返回0:无,1:向下,2:向上,3:双向。 | -## wifi.off('streamChange')7+ +## wifi.off('streamChange')9+ -off(type: "streamChange", callback: Callback<number>): void +off(type: "streamChange", callback?: Callback<number>): void 取消注册WIFI流更改事件。 +**系统接口:** 此接口为系统接口。 + **需要权限:** ohos.permission.MANAGE_WIFI_CONNECTION **系统能力:** SystemCapability.Communication.WiFi.STA **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"streamChange"字符串。 | - | callback | Callback<number> | 是 | 状态改变回调函数,返回0:无,1:向下,2:向上,3:双向。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"streamChange"字符串。 | +| callback | Callback<number> | 否| 状态改变回调函数,返回0:无,1:向下,2:向上,3:双向。 | **示例:** ```js @@ -2364,7 +2368,7 @@ off(type: "hotspotStateChange", callback?: Callback<number>): void | type | string | 是 | 固定填"hotspotStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | -## wifi.on('hotspotStaJoin')7+ +## wifi.on('hotspotStaJoin')9+ on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void @@ -2372,6 +2376,8 @@ on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void **需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Communication.WiFi.AP.Core **参数:** @@ -2381,14 +2387,16 @@ on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void | type | string | 是 | 固定填"hotspotStaJoin"字符串。 | | callback | Callback<StationInfo> | 是 | 状态改变回调函数。 | -## wifi.off('hotspotStaJoin')7+ +## wifi.off('hotspotStaJoin')9+ -off(type: "hotspotStaJoin", callback: Callback<StationInfo>): void +off(type: "hotspotStaJoin", callback?: Callback<StationInfo>): void 取消注册wifi热点sta加入事件。 **需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Communication.WiFi.AP.Core **参数:** @@ -2396,7 +2404,7 @@ off(type: "hotspotStaJoin", callback: Callback<StationInfo>): void | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"hotspotStaJoin"字符串。 | - | callback | Callback<StationInfo> | 是 | 状态改变回调函数。 | + | callback | Callback<StationInfo> | 否 | 状态改变回调函数。 | **示例:** ```js @@ -2414,7 +2422,7 @@ wifi.off("hotspotStaJoin", recvHotspotStaJoinFunc); ``` -## wifi.on('hotspotStaLeave')7+ +## wifi.on('hotspotStaLeave')9+ on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void @@ -2422,6 +2430,8 @@ on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void **需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Communication.WiFi.AP.Core **参数:** @@ -2431,14 +2441,16 @@ on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void | type | string | 是 | 固定填"hotspotStaLeave"字符串。 | | callback | Callback<StationInf]> | 是 | 状态改变回调函数。 | -## wifi.off('hotspotStaLeave')7+ +## wifi.off('hotspotStaLeave')9+ -off(type: "hotspotStaLeave", callback: Callback<StationInfo>): void +off(type: "hotspotStaLeave", callback?: Callback<StationInfo>): void 取消注册wifi热点sta离开事件。 **需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT +**系统接口:** 此接口为系统接口。 + **系统能力:** SystemCapability.Communication.WiFi.AP.Core **参数:** @@ -2446,7 +2458,7 @@ off(type: "hotspotStaLeave", callback: Callback<StationInfo>): void | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"hotspotStaLeave"字符串。 | - | callback | Callback<StationInf]> | 是 | 状态改变回调函数。 | + | callback | Callback<StationInf]> | 否 | 状态改变回调函数。 | **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md index e274ddc2599b46de66a41631f4bdc6791f729e34..f77a6d032d61f8160ee938e64735eeeb206deec6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiManager.md @@ -173,7 +173,7 @@ startScan(): void console.error("failed:" + JSON.stringify(error)); } ``` -## wifiManager.getScanResults10+ +## wifiManager.getScanResults9+ getScanResults(): Promise<Array<WifiScanInfo>> @@ -197,7 +197,7 @@ getScanResults(): Promise<Array<WifiScanInfo>> | -------- | -------- | | 2501000 | Operation failed.| -## wifiManager.getScanResults10+ +## wifiManager.getScanResults9+ getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void @@ -263,7 +263,7 @@ getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void }); ``` -## wifiManager.getScanResultsSync10+ +## wifiManager.getScanResultsSync9+ getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> @@ -328,9 +328,9 @@ getScanInfoList(): Array<WifiScanInfo>; **返回值:** - | **类型** | **说明** | - | -------- | -------- | - | Array<[WifiScanInfo](#wifiscaninfo)> | 返回扫描到的热点列表。 | +| **类型** | **说明** | +| -------- | -------- | +| Array<[WifiScanInfo](#wifiscaninfo)> | 返回扫描到的热点列表。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的bssid为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -516,7 +516,6 @@ setScanAlwaysAllowed(isScanAlwaysAllowed: boolean): void try { let isScanAlwaysAllowed = true; wifiManager.setScanAlwaysAllowed(isScanAlwaysAllowed); - }); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -530,7 +529,7 @@ getScanAlwaysAllowed(): boolean **系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.SET_WIFI_INFO 和 ohos.permission.SET_WIFI_CONFIG +**需要权限:** ohos.permission.GET_WIFI_INFO 和 ohos.permission.GET_WIFI_CONFIG **系统能力:** SystemCapability.Communication.WiFi.STA @@ -555,7 +554,7 @@ getScanAlwaysAllowed(): boolean try { let isScanAlwaysAllowed = wifiManager.getScanAlwaysAllowed(); - console.info("isScanAlwaysAllowed:" + ret); + console.info("isScanAlwaysAllowed:" + isScanAlwaysAllowed); }catch(error){ console.error("failed:" + JSON.stringify(error)); } @@ -575,9 +574,9 @@ addDeviceConfig(config: WifiDeviceConfig): Promise<number> **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。如果bssidType未指定值,则bssidType默认为随机设备地址类型。 | **返回值:** @@ -683,9 +682,9 @@ IP配置信息。 | identity | string | 是 | 否 | 身份信息。 | | anonymousIdentity | string | 是 | 否 | 匿名身份。 | | password | string | 是 | 否 | 密码。 | -| caCertAliases | string | 是 | 否 | CA 证书别名。 | +| caCertAlias | string | 是 | 否 | CA 证书别名。 | | caPath | string | 是 | 否 | CA 证书路径。 | -| clientCertAliases | string | 是 | 否 | 客户端证书别名。 | +| clientCertAlias | string | 是 | 否 | 客户端证书别名。 | | certEntry | Uint8Array | 是 | 是 | CA 证书内容。 | | certPassword | string | 是 | 是 | CA证书密码。 | | altSubjectMatch | string | 是 | 否 | 替代主题匹配。 | @@ -776,10 +775,10 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>) **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | - | callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。当error为非0,表示处理出现错误。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。如果bssidType未指定值,则bssidType默认为随机设备地址类型。 | +| callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。当error为非0,表示处理出现错误。 | **错误码:** @@ -820,9 +819,9 @@ addCandidateConfig(config: WifiDeviceConfig): Promise<number> **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。如果bssidType未指定值,则bssidType默认为随机设备地址类型。 | **返回值:** @@ -868,10 +867,10 @@ addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number&g **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | - | callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。如果操作出现错误,err为非0值。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。如果bssidType未指定值,则bssidType默认为随机设备地址类型。 | +| callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。如果操作出现错误,err为非0值。 | **错误码:** @@ -1123,9 +1122,9 @@ connectToDevice(config: WifiDeviceConfig): void **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。如果bssidType未指定值,则bssidType默认为随机设备地址类型。 | **错误码:** @@ -1841,7 +1840,7 @@ updateNetwork(config: WifiDeviceConfig): number ## wifiManager.disableNetwork9+ -disableNetwork(networkId: number): void +disableNetwork(netId: number): void 去使能网络配置。 @@ -1855,7 +1854,7 @@ disableNetwork(networkId: number): void | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | networkId | number | 是 | 网络配置ID。 | + | netId | number | 是 | 网络配置ID。 | **错误码:** @@ -1910,7 +1909,7 @@ removeAllNetwork(): void ## wifiManager.removeDevice9+ -removeDevice(networkId: number): void +removeDevice(id: number): void 移除指定的网络配置。 @@ -1924,7 +1923,7 @@ removeDevice(networkId: number): void | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | networkId | number | 是 | 网络配置ID。 | + | id | number | 是 | 网络配置ID。 | **错误码:** @@ -2331,9 +2330,9 @@ getStations():  Array<[StationInfo](#stationinfo9)> **返回值:** - | **类型** | **说明** | - | -------- | -------- | - |  Array<[StationInfo](#stationinfo9)> | 连接的设备数组。 | +| **类型** | **说明** | +| -------- | -------- | +|  Array<[StationInfo](#stationinfo9)> | 连接的设备数组。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的macAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -2467,9 +2466,9 @@ getCurrentP2pGroup(): Promise<WifiP2pGroupInfo> **返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise对象。表示当前组信息。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise对象。表示当前组信息。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -2491,9 +2490,9 @@ getCurrentP2pGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -2532,9 +2531,9 @@ getP2pPeerDevices(): Promise<WifiP2pDevice[]> **返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise对象。表示对端设备列表信息。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise对象。表示对端设备列表信息。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -2556,9 +2555,9 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -2691,9 +2690,9 @@ createGroup(config: WifiP2PConfig): void **参数:** - | **参数名** | **类型** | 必填 | **说明** | - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#wifip2pconfig9) | 是 | 群组配置信息。 | +| **参数名** | **类型** | 必填 | **说明** | +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#wifip2pconfig9) | 是 | 群组配置信息。如果DeviceAddressType未指定值,则DeviceAddressType默认为随机设备地址类型。 | **错误码:** @@ -2792,9 +2791,9 @@ p2pConnect(config: WifiP2PConfig): void **参数:** - | **参数名** | **类型** | 必填 | **说明** | - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#wifip2pconfig9) | 是 | 连接配置信息。 | +| **参数名** | **类型** | 必填 | **说明** | +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#wifip2pconfig9) | 是 | 连接配置信息。如果DeviceAddressType未指定值,则DeviceAddressType默认为随机设备地址类型。 | **错误码:** @@ -2868,7 +2867,7 @@ p2pConnect(config: WifiP2PConfig): void setTimeout(function() {wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); setTimeout(function() {wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); setTimeout(function() {wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); - console.info("start discover devices -> " + wifiManager.startDiscoverP2pDevices()); + console.info("start discover devices -> " + wifiManager.startDiscoverDevices()); ``` ## wifiManager.p2pCancelConnect9+ @@ -2899,13 +2898,30 @@ p2pCancelConnect(): void console.error("failed:" + JSON.stringify(error)); } ``` - ## wifiManager.startDiscoverDevices10+ startDiscoverDevices(): void 开始发现设备。 +**需要权限:** ohos.permission.GET_WIFI_INFO + +**系统能力:** SystemCapability.Communication.WiFi.P2P + +**错误码:** + +以下错误码的详细介绍请参见[WIFI错误码](../errorcodes/errorcode-wifi.md)。 + +| **错误码ID** | **错误信息** | + | -------- | -------- | +| 2801000 | Operation failed.| + +## wifiManager.startDiscoverDevices9+ + +startDiscoverDevices(): void + +开始发现设备。 + **需要权限:** ohos.permission.GET_WIFI_INFO 和 ohos.permission.LOCATION 和 ohos.permission.APPROXIMATELY_LOCATION **系统能力:** SystemCapability.Communication.WiFi.P2P @@ -2929,7 +2945,7 @@ startDiscoverDevices(): void } ``` -## wifiManager.stopDiscoverDevices10+ +## wifiManager.stopDiscoverDevices9+ stopDiscoverDevices(): void @@ -3011,9 +3027,9 @@ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> **返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise对象。表示所有群组信息。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise对象。表示所有群组信息。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -3074,9 +3090,9 @@ getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | 是 | 回调函数。当操作成功时,err为0,data表示所有群组信息。如果error为非0,表示处理出现错误。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | 是 | 回调函数。当操作成功时,err为0,data表示所有群组信息。如果error为非0,表示处理出现错误。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -3381,10 +3397,10 @@ off(type: "wifiRssiChange", callback?: Callback<number>): void **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"wifiRssiChange"字符串。 | - | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"wifiRssiChange"字符串。 | +| callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **错误码:** @@ -3407,6 +3423,108 @@ off(type: "wifiRssiChange", callback?: Callback<number>): void // Unregister event wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc); +``` + ## wifiManager.on('streamChange')9+ + +on(type: "streamChange", callback: Callback<number>): void + +注册WIFI流更改事件。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.MANAGE_WIFI_CONNECTION + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"streamChange"字符串。 | +| callback | Callback<number> | 是 | 状态改变回调函数,返回0:无,1:向下,2:向上,3:双向。 | + +## wifiManager.off('streamChange')9+ + +off(type: "streamChange", callback?: Callback<number>): void + +取消注册WIFI流更改事件。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.MANAGE_WIFI_CONNECTION + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"streamChange"字符串。 | +| callback | Callback<number> | 否 | 状态改变回调函数,返回0:无,1:向下,2:向上,3:双向。 | + +**示例:** +```js +import wifi from '@ohos.wifi'; + +var recvStreamChangeFunc = result => { + console.info("Receive stream change event: " + result); +} + +// Register event +wifi.on("streamChange", recvStreamChangeFunc); + +// Unregister event +wifi.off("streamChange", recvStreamChangeFunc); + +``` +## wifiManager.on('deviceConfigChange')9+ + +on(type: "deviceConfigChange", callback: Callback<number>): void + +注册WIFI设备配置更改事件。 + +**需要权限:** ohos.permission.GET_WIFI_INFO + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"streamChange"字符串。 | +| callback | Callback<number> | 是 | 状态改变回调函数,返回0: 添加配置, 1: 更改配置, 2: 删除配置. | + +## wifiManager.off('deviceConfigChange')9+ + +off(type: "deviceConfigChange", callback: Callback<number>): void + +取消注册WIFI设备配置更改事件。 + +**需要权限:** ohos.permission.MANAGE_WIFI_CONNECTION + +**系统能力:** SystemCapability.Communication.WiFi.STA + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"streamChange"字符串。 | +| callback | Callback<number> | 是 | 状态改变回调函数,返回0: 添加配置, 1: 更改配置, 2: 删除配置.| + +**示例:** +```js +import wifi from '@ohos.wifi'; + +var recvDeviceConfigChangeFunc = result => { + console.info("Receive device config change event: " + result); +} + +// Register event +wifi.on("deviceConfigChange", recvDeviceConfigChangeFunc); + +// Unregister event +wifi.off("deviceConfigChange", recvDeviceConfigChangeFunc); + ``` ## wifiManager.on('hotspotStateChange')9+ @@ -3421,10 +3539,10 @@ on(type: "hotspotStateChange", callback: Callback<number>): void **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"hotspotStateChange"字符串。 | - | callback | Callback<number> | 是 | 状态改变回调函数。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"hotspotStateChange"字符串。 | +| callback | Callback<number> | 是 | 状态改变回调函数。 | **热点状态改变事件的枚举:** @@ -3455,10 +3573,10 @@ off(type: "hotspotStateChange", callback?: Callback<number>): void **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"hotspotStateChange"字符串。 | - | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"hotspotStateChange"字符串。 | +| callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **错误码:** @@ -3483,6 +3601,114 @@ off(type: "hotspotStateChange", callback?: Callback<number>): void wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc); ``` +## wifiManager.on('hotspotStaJoin')9+ + +on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void + +注册wifi热点sta加入事件。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"hotspotStaJoin"字符串。 | +| callback | Callback<StationInfo> | 是 | 状态改变回调函数。 | + +## wifiManager.off('hotspotStaJoin')9+ + +off(type: "hotspotStaJoin", callback?: Callback<StationInfo>): void + +取消注册wifi热点sta加入事件。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"hotspotStaJoin"字符串。 | +| callback | Callback<StationInfo> | 否 | 状态改变回调函数。 | + +**示例:** +```js +import wifi from '@ohos.wifi'; + +var recvHotspotStaJoinFunc = result => { + console.info("Receive hotspot sta join event: " + result); +} + +// Register event +wifi.on("hotspotStaJoin", recvHotspotStaJoinFunc); + +// Unregister event +wifi.off("hotspotStaJoin", recvHotspotStaJoinFunc); + +``` + +## wifiManager.on('hotspotStaLeave')9+ + +on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void + +注册wifi热点sta离开事件。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + + | **参数名** | **类型** | **必填** | **说明** | + | -------- | -------- | -------- | -------- | + | type | string | 是 | 固定填"hotspotStaLeave"字符串。 | + | callback | Callback<StationInf]> | 是 | 状态改变回调函数。 | + +## wifiManager.off('hotspotStaLeave')9+ + +off(type: "hotspotStaLeave", callback?: Callback<StationInfo>): void + +取消注册wifi热点sta离开事件。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.MANAGE_WIFI_HOTSPOT + +**系统能力:** SystemCapability.Communication.WiFi.AP.Core + +**参数:** + +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"hotspotStaLeave"字符串。 | +| callback | Callback<StationInf]> | 是 | 状态改变回调函数。 | + +**示例:** +```js +import wifi from '@ohos.wifi'; + +var recvHotspotStaLeaveFunc = result => { + console.info("Receive hotspot sta leave event: " + result); +} + +// Register event +wifi.on("hotspotStaLeave", recvHotspotStaLeaveFunc); + +// Unregister event +wifi.off("hotspotStaLeave", recvHotspotStaLeaveFunc); + +``` + ## wifiManager.on('p2pStateChange')9+ on(type: "p2pStateChange", callback: Callback<number>): void @@ -3495,12 +3721,12 @@ on(type: "p2pStateChange", callback: Callback<number>): void **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"p2pStateChange"字符串。 | - | callback | Callback<number> | 是 | 状态改变回调函数。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"p2pStateChange"字符串。 | +| callback | Callback<number> | 是 | 状态改变回调函数。 | -**P2P状态改变事件的枚举:** +** P2P状态改变事件的枚举:** | **枚举值** | **说明** | | -------- | -------- | @@ -3700,10 +3926,10 @@ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | - | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | 是 | 状态改变回调函数。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | 是 | 状态改变回调函数。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -3725,10 +3951,10 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | - | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | +| callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。如果应用申请了ohos.permission.GET_WIFI_PEERS_MAC权限,则返回结果中的deviceAddress为真实设备地址,否则为随机设备地址。 | **错误码:** @@ -3790,10 +4016,10 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void **参数:** - | **参数名** | **类型** | **必填** | **说明** | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 固定填"p2pPersistentGroupChange"字符串。 | - | callback | Callback<void> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 固定填"p2pPersistentGroupChange"字符串。 | +| callback | Callback<void> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index ea665b222c7ef701d70bf67b6270e218f7538494..5f38585a1c35fc7235379801e5b2f9769ca9e28a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -3785,7 +3785,7 @@ setWindowBrightness(brightness: number, callback: AsyncCallback<void>): vo | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | -- |-------------------------------------------| -| brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]。其取1.0时表示最亮。 | +| brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -3828,7 +3828,7 @@ setWindowBrightness(brightness: number): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | -- |----------------------------------------| -| brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]。1.0表示最亮。 | +| brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。 | **返回值:** @@ -6385,7 +6385,7 @@ setBrightness(brightness: number, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- |---------------------------------------| -| brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]。,1表示最亮。 | +| brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **示例:** @@ -6419,7 +6419,7 @@ setBrightness(brightness: number): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- |------------------------------------------| -| brightness | number | 是 | 屏幕亮度值。该参数为浮点数。取值范围为[0.0, 1.0],取1.0时表示最亮。 | +| brightness | number | 是 | 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 2911e4d1019f42ce76efa715c64e8333505b01cd..bdcaa44e328c8786bd74a1d5042db9aebb3b1070 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -2083,17 +2083,6 @@ Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程 Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。 -### 注意事项 -- Worker存在数量限制,当前支持最多同时存在8个Worker。 -- 在API version 8及之前的版本,当Worker数量超出限制时,会抛出错误Error "Too many workers, the number of workers exceeds the maximum."。 -- 从API version 9开始,当Worker数量超出限制时,会抛出错误BusinessError "Worker initialization failure, the number of workers exceeds the maximum."。 -- 主动销毁Worker可以调用新创建Worker对象的terminate()或workerPort.close()方法。 -- 自API version 9版本开始,若Worker处于已经销毁或正在销毁等非运行状态时,调用其功能接口,会抛出相应的BusinessError。 -- Worker的创建和销毁耗费性能,建议管理已创建的Worker并重复使用。 -- 创建Worker工程时,new worker.Worker构造函数和new worker.ThreadWorker构造函数不能同时使用,否则将导致工程中Worker的功能异常。自API version 9版本开始,建议使用[new worker.ThreadWorker](#constructor9)构造函数,在API version 8及之前的版本,建议使用[new worker.Worker](#constructordeprecated)构造函数。 -- 创建Worker工程时,在Worker线程的文件中(比如本文中worker.ts)不能导入任何有关构建UI的方法(比如ets文件等),否则会导致Worker的功能失效。排查方式:解压生成的Hap包,在创建Worker线程的文件目录中找到"worker.js",全局搜索"View"关键字。如果存在该关键字,说明在worker.js中打包进去了构建UI的方法,会导致Worker的功能失效,建议在创建Worker线程的文件中修改 "import “xxx” from src"中src的目录层级。 -- 线程间通信时传递的数据量最大限制为16M。 - ## 完整示例 > **说明:**
> 以API version 9的工程为例。
API version 8及之前的版本仅支持FA模型,如需使用,注意更换构造Worker的接口和创建worker线程中与主线程通信的对象的两个方法。 diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index 1b900e8889e10c75e13a3df45a9bcec49205b2e9..7483e00c88d4d0c6dc1f1a0652b71fea1b5aa70a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -52,6 +52,7 @@ - [文本通用](ts-universal-attributes-text-style.md) - [拖拽控制](ts-universal-attributes-drag-drop.md) - [安全区域](ts-universal-attributes-expand-safe-area.md) + - [特效绘制合并](ts-universal-attributes-use-effect.md) - 手势处理 - [绑定手势方法](ts-gesture-settings.md) - 基础手势 @@ -141,6 +142,7 @@ - [TabContent](ts-container-tabcontent.md) - [UIExtensionComponent](ts-container-ui-extension-component.md) - [WaterFlow](ts-container-waterflow.md) + - [EffectComponent](ts-container-effectcomponent.md) - 媒体组件 - [Video](ts-media-components-video.md) - 绘制组件 @@ -190,7 +192,7 @@ - [枚举说明](ts-appendix-enums.md) - [类型定义](ts-types.md) - 已停止维护的组件 - - [GridContainer](ts-container-gridcontainer.md) - [AbilityComponent](ts-container-ability-component.md) + - [GridContainer](ts-container-gridcontainer.md) - 已停止维护的接口 - [点击控制](ts-universal-attributes-click.md) diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_effectcomponent.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_effectcomponent.png new file mode 100644 index 0000000000000000000000000000000000000000..1a9d87ef2d4dee47d7335eb863ca8a0131ae9721 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_effectcomponent.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md index c0485b25da8e7c866f618286b2c8ac0bec511346..db37dc6089a592b99e716f064ac6d6bdfa33fb8f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-marquee.md @@ -1,6 +1,6 @@ # Marquee -跑马灯组件,用于滚动展示一段单行文本,仅当文本内容宽度超过跑马灯组件宽度时滚动。 +跑马灯组件,用于滚动展示一段单行文本。仅当文本内容宽度超过跑马灯组件宽度时滚动,不超过时不滚动。 > **说明:** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md index 31ae79e889469e220e7e381df209d43fc5b777a8..315444a62133e9399a6c837bc461e5c52cd4ef1b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -61,7 +61,7 @@ Text(content?: string | Resource) ## 示例 ### 示例1 -textAlign,textOverflow,maxLines,lineHeight使用示例。 + ```ts // xxx.ets @Entry @@ -144,7 +144,7 @@ struct TextExample1 { ![textExp1](figures/textExp1.png) ### 示例2 -decoration,baselineOffset,letterSpacing,textCase使用示例: + ```ts @Entry @Component @@ -262,6 +262,7 @@ struct TextExample { build() { Column({ space: 8 }) { Text('textShadow').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') + // 设置文字阴影效果 Text('textShadow') .width('80%') .height(55) @@ -271,6 +272,7 @@ struct TextExample { .textShadow({ radius: 10, color: Color.Black, offsetX: 0, offsetY: 0 }) .borderWidth(1) Divider() + // 设置文本自适应高度的方式 Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') Text('This is the text with the height adaptive policy set') .width('80%') @@ -301,6 +303,7 @@ struct TextExample { .heightAdaptivePolicy(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST) Divider() Text('marquee').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%') + // 设置文本超长时以跑马灯的方式展示 Text('This is the text with the text overflow set marquee') .width(300) .borderWidth(1) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md index e4194eaa42dafbb521d51773797d9ef6aa2f5ae4..3886c73bb412b89ec7cc8b7282104bce617006cd 100755 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -808,12 +808,16 @@ initialScale(percent: number) } ``` -### userAgent +### userAgent(deprecated) userAgent(userAgent: string) 设置用户代理。 +> **说明:** +> +> 从API version 8开始支持,从API version 10开始废弃。建议使用[setCustomUserAgent](../apis/js-apis-webview.md#setcustomuseragent10)10+替代。 + **参数:** | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | @@ -2193,7 +2197,8 @@ onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector ```ts // xxx.ets - import web_webview from '@ohos.web.webview' + import web_webview from '@ohos.web.webview'; + import picker from '@ohos.file.picker'; @Entry @Component @@ -2202,24 +2207,18 @@ onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector build() { Column() { - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) .onShowFileSelector((event) => { - AlertDialog.show({ - title: event.fileSelector.getTitle(), - message: 'isCapture:' + event.fileSelector.isCapture() + " mode:" + event.fileSelector.getMode() + 'acceptType:' + event.fileSelector.getAcceptType(), - confirm: { - value: 'upload', - action: () => { - let fileList: Array = [ - '/data/storage/el2/base/test', - ] - event.result.handleFileList(fileList) - } - }, - cancel: () => { - let fileList: Array = [] - event.result.handleFileList(fileList) - } + console.log('MyFileUploader onShowFileSelector invoked') + const documentSelectOptions = new picker.DocumentSelectOptions(); + let uri = null; + const documentViewPicker = new picker.DocumentViewPicker(); + documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => { + uri = documentSelectResult[0]; + console.info('documentViewPicker.select to file succeed and uri is:' + uri); + event.result.handleFileList([uri]); + }).catch((err) => { + console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`); }) return true }) @@ -2227,6 +2226,19 @@ onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector } } ``` + + 加载的html文件。 + ```html + + + + + + +
+ + + ``` ### onResourceLoad9+ 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-sidebarcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index 72eb33eaa2c724fab078873adb3072c39193213a..0f2a4d1fcd2521731335b220c5c53d2f0e18dbe3 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 @@ -32,7 +32,7 @@ SideBarContainer( type?: SideBarContainerType ) | 名称 | 描述 | | -------- | -------- | -| Embed | 侧边栏嵌入到组件内,和内容区并列显示。 | +| Embed | 侧边栏嵌入到组件内,和内容区并列显示。当前屏幕尺寸大于600vp时,该枚举值生效。小于600vp时,侧边栏会自动隐藏。在自动隐藏后,如果通过点击控制按钮唤出侧边栏,则侧边栏默认通过Overlay方式显示。 | | Overlay | 侧边栏浮在内容区上面。 | | AUTO | 组件尺寸大于等于minSideBarWidth+minContentWidth时,采用Embed模式显示。
组件尺寸小于minSideBarWidth+minContentWidth时,采用Overlay模式显示。
未设置minSideBarWidth或minContentWidth时,会使用未设置接口的默认值进行计算,若计算的值小于600vp,则使用600vp做为模式切换的断点值。| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md index e290bfa70d9f8331786e19926d050317b6714c2d..020c2a964f568babb9bbcb664c375426aa68d4ce 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md @@ -1,6 +1,6 @@ # 页面间转场 -当路由进行切换时,可以通过 在pageTransition函数中自定义页面入场和页面退场的转场动效。 +当路由进行切换时,可以通过在pageTransition函数中自定义页面入场和页面退场的转场动效。详细指导请参考[页面转场动画](../../ui/arkts-page-transition-animation.md)。 > **说明:** > @@ -11,8 +11,8 @@ | 名称 | 参数 | 必填 | 参数描述 | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| PageTransitionEnter | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | 否 | 设置当前页面的自定义入场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线。string类型的取值支持"ease"、"ease-in"、"ease-out"、"ease-in-out"、"extreme-deceleration"、"fast-out-linear-in"、"fast-out-slow-in"、"friction"、"linear"、"linear-out-slow-in"、"rhythm"、"sharp"、"smooth"。
默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | -| PageTransitionExit | {
type?: RouteType,
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | 否 | 设置当前页面的自定义退场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线,string类型取值与PageTransitionEnter相同。
 默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | +| PageTransitionEnter | {
type?: [RouteType](#routetype枚举说明),
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | 否 | 设置当前页面的自定义入场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线。string类型的取值支持"ease"、"ease-in"、"ease-out"、"ease-in-out"、"extreme-deceleration"、"fast-out-linear-in"、"fast-out-slow-in"、"friction"、"linear"、"linear-out-slow-in"、"rhythm"、"sharp"、"smooth"。
默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | +| PageTransitionExit | {
type?: [RouteType](#routetype枚举说明),
duration?: number,
curve?: [Curve](ts-appendix-enums.md#curve) \| string \| [ICurve](../apis/js-apis-curve.md#icurve)10+,
delay?: number
} | 否 | 设置当前页面的自定义退场动效。
- type:页面转场效果生效的路由类型。
默认值:RouteType.None。
- duration:动画的时长。
单位:毫秒
默认值:1000
- curve:动画曲线,string类型取值与PageTransitionEnter相同。
 默认值:Curve.Linear
- delay:动画延迟时长。
单位:毫秒
默认值:0
**说明:**
没有匹配时使用系统默认的页面转场效果(根据设备可能会有差异),如需禁用系统默认页面转场效果,可以指定duration为0。 | ## RouteType枚举说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-drag-drop.md index 0abf748e6ba414fbf4b1e8e8346c5aca2f991102..b6fdbb6102b2f24ea840502baeaaf2c6bb22d471 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-drag-drop.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-drag-drop.md @@ -21,7 +21,7 @@ ArkUI组件默认支持拖拽。 | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| allowDrop | Array\<[UnifiedDataType](../apis/js-apis-data-udmf.md#unifieddatatype)> | 设置该组件上允许落入的数据类型。
默认值:空
| +| allowDrop | Array\<[UniformDataType](../apis/js-apis-data-uniformTypeDescriptor.md#uniformdatatype)> | 设置该组件上允许落入的数据类型。
默认值:空
| | draggable | boolean | 设置该组件是否允许进行拖拽。
默认值:false
| 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 42ff54a2385c6ce3461cb4135fb12ca429d93ea0..2f4c4238dc7abc74fafec4152d66e140a35000a3 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卡片中使用。
**说明:**
该属性在不设置值或者设置非法值时不生效。
例如,Row只设置宽度且没有子组件,aspectRatio不设置值或者设置成负数时,此时Row高度为0。 | +| 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(单行)容器组件中生效。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md index fb7418b17964c9946ce87442c1122eaa7537c276..48c4b8bbfdd6bf31bf4f8eb491fc5d015bcb1013 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md @@ -27,24 +27,24 @@ ## MenuOptions10+ -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string | 否 | 菜单标题。
**说明:**
仅在content设置为Array<[MenuItem](#menuitem)> 时生效。 | -| offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。 | -| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
**说明:**
placement值设置为undefined、null或没有设置此选项时,按默认值[BottomLeft](ts-appendix-enums.md#placement8)处理,相对父组件区域弹出。 | -| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | -| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | +| 名称 | 类型 | 必填 | 描述 | +| ----------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| title | string | 否 | 菜单标题。
**说明:**
仅在content设置为Array<[MenuItem](#menuitem)> 时生效。 | +| offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。
**说明:**
菜单类型为相对⽗组件区域弹出时,⾃动根据菜单位置属性 (placement)将区域的宽或⾼计⼊偏移量中。
当菜单相对父组件出现在上侧时(placement设置为Placement.TopLeft,Placement.Top,Placement.TopRight),x为正值,菜单相对组件向右进行偏移,y为正值,菜单相对组件向上进行偏移。
当菜单相对父组件出现在下侧时(placement设置为Placement.BottomLeft,Placement.Bottom,Placement.BottomRight),x为正值,菜单相对组件向右进行偏移,y为正值,菜单相对组件向下进行偏移。
当菜单相对父组件出现在左侧时(placement设置为Placement.LeftTop,Placement.Left,Placement.LeftBottom),x为正值,菜单相对组件向左进行偏移,y为正值,菜单相对组件向下进行偏移。
当菜单相对父组件出现在右侧时(placement设置为Placement.RightTop,Placement.Right,Placement.RightBottom),x为正值,菜单相对组件向右进行偏移,y为正值,菜单相对组件向下进行偏移。
如果菜单调整了显示位置(与placement初始值主方向不⼀致),则偏移值 (offset) 失效。 | +| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
**说明:**
placement值设置为undefined、null或没有设置此选项时,按默认值[BottomLeft](ts-appendix-enums.md#placement8)处理,相对父组件区域弹出。 | +| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | +| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | ## ContextMenuOptions10+ -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | -| offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。 | -| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
**说明:**
placement值设置为undefined、null或没有设置此选项时,按未设置placement处理,菜单跟随点击位置弹出。 | -| enableArrow | boolean | 否 | 是否显示箭头。如果菜单的大小和位置不足以放置箭头时,不会显示箭头。
默认值:false, 不显示箭头。
**说明:**
箭头显示时,placement未设置或者值为非法值,默认在目标物上方显示,否则按照placement的位置优先显示。当前位置显示不下时,会自动调整位置。 | -| arrowOffset | [Length](ts-types.md#length) | 否 | 箭头在菜单处的偏移。箭头在菜单水平方向时,偏移量为箭头至最左侧的距离,默认居中。箭头在菜单竖直方向时,偏移量为箭头至最上侧的距离,默认居中。偏移量必须合法且转换为具体数值时大于0才会生效,另外该值生效时不会导致箭头超出菜单四周的安全距离。根据配置的placement来计算是在水平还是竖直方向上偏移。 | -| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | -| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | +| 名称 | 类型 | 必填 | 描述 | +| ----------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| offset | [Position](ts-types.md#position8) | 否 | 菜单弹出位置的偏移量,不会导致菜单显示超出屏幕范围。
**说明:**
菜单类型为相对⽗组件区域弹出时,⾃动根据菜单位置属性 (placement)将区域的宽或⾼计⼊偏移量中。
当菜单相对父组件出现在上侧时(placement设置为Placement.TopLeft,Placement.Top,Placement.TopRight),x为正值,菜单相对组件向右进行偏移,y为正值,菜单相对组件向上进行偏移。
当菜单相对父组件出现在下侧时(placement设置为Placement.BottomLeft,Placement.Bottom,Placement.BottomRight),x为正值,菜单相对组件向右进行偏移,y为正值,菜单相对组件向下进行偏移。
当菜单相对父组件出现在左侧时(placement设置为Placement.LeftTop,Placement.Left,Placement.LeftBottom),x为正值,菜单相对组件向左进行偏移,y为正值,菜单相对组件向下进行偏移。
当菜单相对父组件出现在右侧时(placement设置为Placement.RightTop,Placement.Right,Placement.RightBottom),x为正值,菜单相对组件向右进行偏移,y为正值,菜单相对组件向下进行偏移。
如果菜单调整了显示位置(与placement初始值主方向不⼀致),则偏移值 (offset) 失效。 | +| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 菜单组件优先显示的位置,当前位置显示不下时,会自动调整位置。
**说明:**
placement值设置为undefined、null或没有设置此选项时,按未设置placement处理,菜单跟随点击位置弹出。 | +| enableArrow | boolean | 否 | 是否显示箭头。如果菜单的大小和位置不足以放置箭头时,不会显示箭头。
默认值:false, 不显示箭头。
**说明:**
箭头显示时,placement未设置或者值为非法值,默认在目标物上方显示,否则按照placement的位置优先显示。当前位置显示不下时,会自动调整位置。 | +| arrowOffset | [Length](ts-types.md#length) | 否 | 箭头在菜单处的偏移。箭头在菜单水平方向时,偏移量为箭头至最左侧的距离,默认居中。箭头在菜单竖直方向时,偏移量为箭头至最上侧的距离,默认居中。偏移量必须合法且转换为具体数值时大于0才会生效,另外该值生效时不会导致箭头超出菜单四周的安全距离。根据配置的placement来计算是在水平还是竖直方向上偏移。 | +| onAppear | () => void | 否 | 菜单弹出时的事件回调。 | +| onDisappear | () => void | 否 | 菜单消失时的事件回调。 | ## 示例 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-events-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index 2b5d2a9a6f3cb42dd6cead1c76e037b860fe892c..1774141cf6cb4e24ede56c1ef4c87d64565e47b7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -54,9 +54,9 @@ ArkUI组件默认支持拖拽。 | 名称 | 类型 | 描述 | | ------ | ------ | ---------------- | | useCustomDropAnimation10+ | boolean | 当拖拽结束时,是否使用系统默认落入动画。 | -| setData(unifiedData: [UnifiedData](../apis/js-apis-data-udmf.md#unifieddata))10+ | void | 向DragEvent中设置拖拽相关数据。 | -| getData()10+ | [UnifiedData](../apis/js-apis-data-udmf.md#unifieddata) | 从DragEvent中获取拖拽相关数据。 | -| getSummary()10+ | [Summary](../apis/js-apis-data-udmf.md#summary) | 从DragEvent中获取拖拽相关数据的简介。 | +| setData(unifiedData: [UnifiedData](../apis/js-apis-data-unifiedDataChannel.md#unifieddata))10+ | void | 向DragEvent中设置拖拽相关数据。 | +| getData()10+ | [UnifiedData](../apis/js-apis-data-unifiedDataChannel.md#unifieddata) | 从DragEvent中获取拖拽相关数据。 | +| getSummary()10+ | [Summary](../apis/js-apis-data-unifiedDataChannel.md#summary) | 从DragEvent中获取拖拽相关数据的简介。 | | setResult(dragRect: [DragResult](#dragresult10枚举说明))10+ | void | 向DragEvent中设置拖拽结果。 | | getResult()10+ | [DragResult](#dragresult10枚举说明) | 从DragEvent中获取拖拽结果。 | | getPreviewRect()10+ | [Rectangle](ts-universal-attributes-touch-target.md#rectangle对象说明) | 获取预览图所在的Rectangle。 | diff --git a/zh-cn/application-dev/task-management/continuous-task.md b/zh-cn/application-dev/task-management/continuous-task.md index c027b5b4bb68cdb95319c94e54b66058366e8fd3..70cf3617e06d706bf782e1b2db14358b5ce5fb6a 100644 --- a/zh-cn/application-dev/task-management/continuous-task.md +++ b/zh-cn/application-dev/task-management/continuous-task.md @@ -81,8 +81,9 @@ 3. 导入模块。 ```ts - import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - import wantAgent from '@ohos.app.ability.wantAgent'; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; + import { BusinessError } from '@ohos.base'; ``` 4. 申请和取消长时任务。 @@ -99,10 +100,10 @@ struct Index { @State message: string = 'ContinuousTask'; // 通过getContext方法,来获取page所在的UIAbility上下文。 - private context = getContext(this); + private context: Context = getContext(this); startContinuousTask() { - let wantAgentInfo = { + let wantAgentInfo: wantAgent.wantAgentInfo = { // 点击通知后,将要执行的动作列表 wants: [ { @@ -119,30 +120,22 @@ }; // 通过wantAgent模块下getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(this.context, - backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { - console.info(`Succeeded in operationing startBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to start background running. Code is ${error.code} message is ${error.message}`); - } + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); }); } stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { - console.info(`Succeeded in operationing stopBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to stop background running. Code is ${error.code} message is ${error.message}`); - } + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); } build() { @@ -192,131 +185,129 @@ **跨设备或跨应用**申请长时任务示例代码如下: ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - - const MSG_SEND_METHOD: string = 'CallSendMsg' - - let mContext = null; - - function startContinuousTask() { - let wantAgentInfo = { - // 点击通知后,将要执行的动作列表 - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", - } - ], - // 点击通知后,动作类型 - operationType: wantAgent.OperationType.START_ABILITY, - // 使用者自定义的一个私有值 - requestCode: 0, - // 点击通知后,动作执行属性 - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(mContext, - backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { - console.info(`Succeeded in operationing startBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (err) { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - }); - } - - function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { - console.info(`Succeeded in operationing stopBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (err) { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - } - - class MyParcelable { - num: number = 0; - str: String = ''; - - constructor(num, string) { - this.num = num; - this.str = string; - } - - marshalling(messageSequence) { - messageSequence.writeInt(this.num); - messageSequence.writeString(this.str); - return true; - } - - unmarshalling(messageSequence) { - this.num = messageSequence.readInt(); - this.str = messageSequence.readString(); - return true; - } - } - - function sendMsgCallback(data) { - console.info('BgTaskAbility funcCallBack is called ' + data) - let receivedData = new MyParcelable(0, '') - data.readParcelable(receivedData) - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) - // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 - if (receivedData.str === 'start_bgtask') { - startContinuousTask() - } else if (receivedData.str === 'stop_bgtask') { - stopContinuousTask(); - } - return new MyParcelable(10, 'Callee test'); - } - - export default class BgTaskAbility extends UIAbility { - onCreate(want, launchParam) { - console.info("[Demo] BgTaskAbility onCreate") - this.callee.on('test', sendMsgCallback); - - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback) - } catch (error) { - console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) - } - mContext = this.context; - } - - onDestroy() { - console.info('[Demo] BgTaskAbility onDestroy') - } - - onWindowStageCreate(windowStage) { - console.info('[Demo] BgTaskAbility onWindowStageCreate') - - windowStage.loadContent("pages/index").then((data) => { - console.info(`load content succeed with data ${JSON.stringify(data)}`) - }).catch((error) => { - console.error(`load content failed with error ${JSON.stringify(error)}`) - }) - } - - onWindowStageDestroy() { - console.info('[Demo] BgTaskAbility onWindowStageDestroy') - } - - onForeground() { - console.info('[Demo] BgTaskAbility onForeground') - } - - onBackground() { - console.info('[Demo] BgTaskAbility onBackground') - } - }; + import UIAbility from '@ohos.app.ability.UIAbility'; + import window from '@ohos.window'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import Want from '@ohos.app.ability.Want'; + import rpc from '@ohos.rpc'; + + const MSG_SEND_METHOD: string = 'CallSendMsg' + + let mContext: Context; + + function startContinuousTask() { + let wantAgentInfo : wantAgent.WantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { + backgroundTaskManager.startBackgroundRunning(mContext, + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + }); + } + + function stopContinuousTask() { + backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } + + class MyParcelable { + num: number = 0; + str: String = ''; + + constructor(num: number, string: string) { + this.num = num; + this.str = string; + } + + marshalling(messageSequence: rpc.MessageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + + unmarshalling(messageSequence: rpc.MessageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + + function sendMsgCallback(data: rpc.MessageSequence) { + console.info('BgTaskAbility funcCallBack is called ' + data); + let receivedData = new MyParcelable(0, ''); + data.readParcelable(receivedData); + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); + // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 + if (receivedData.str === 'start_bgtask') { + startContinuousTask(); + } else if (receivedData.str === 'stop_bgtask') { + stopContinuousTask(); + } + return new MyParcelable(10, 'Callee test'); + } + + export default class BgTaskAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + console.info("[Demo] BgTaskAbility onCreate"); + this.callee.on('test', sendMsgCallback); + + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); + } + mContext = this.context; + } + + onDestroy() { + console.info('[Demo] BgTaskAbility onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + console.info('[Demo] BgTaskAbility onWindowStageCreate'); + + windowStage.loadContent('pages/Index', (error, data) => { + if (error.code) { + console.error(`load content failed with error ${JSON.stringify(error)}`); + return; + } + console.info(`load content succeed with data ${JSON.stringify(data)}`); + }); + } + + onWindowStageDestroy() { + console.info('[Demo] BgTaskAbility onWindowStageDestroy'); + } + + onForeground() { + console.info('[Demo] BgTaskAbility onForeground'); + } + + onBackground() { + console.info('[Demo] BgTaskAbility onBackground'); + } + }; ``` @@ -355,119 +346,112 @@ 3. 导入模块。 ```js - import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; - import featureAbility from '@ohos.ability.featureAbility'; - import wantAgent from '@ohos.app.ability.wantAgent'; - import rpc from "@ohos.rpc"; + import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; + import rpc from "@ohos.rpc"; + import { BusinessError } from '@ohos.base'; ``` 4. 申请和取消长时任务。在 ServiceAbility 中,调用 startBackgroundRunning() 接口和 startBackgroundRunning() 接口实现长时任务的申请和取消。 ```js - function startContinuousTask() { - let wantAgentInfo = { - // 点击通知后,将要执行的动作列表 - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - // 点击通知后,动作类型 - operationType: wantAgent.OperationType.START_ABILITY, - // 使用者自定义的一个私有值 - requestCode: 0, - // 点击通知后,动作执行属性 - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { - console.info(`Succeeded in operationing startBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - }); - } - - function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info(`Succeeded in operationing stopBackgroundRunning.`); - }).catch((err) => { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - }); - } catch (error) { - console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); - } - } - - async function processAsyncJobs() { - // 此处执行具体的长时任务。 - - // 长时任务执行完,调用取消接口,释放资源。 - stopContinuousTask(); - } - - let mMyStub; - - class MyStub extends rpc.RemoteObject { - constructor(des) { - if (typeof des === 'string') { - super(des); - } else { - return null; - } - } - - onRemoteRequest(code, data, reply, option) { - console.log('ServiceAbility onRemoteRequest called'); - // code 的具体含义用户自定义 - if (code === 1) { - // 接收到申请长时任务的请求码 - startContinuousTask(); - // 此处执行具体长时任务 - } else if (code === 2) { - // 接收到取消长时任务的请求码 - stopContinuousTask(); - } else { - console.log('ServiceAbility unknown request code'); - } - return true; - } - } - - export default { - onStart(want) { - console.info('ServiceAbility onStart'); - mMyStub = new MyStub("ServiceAbility-test"); - // 在执行长时任务前,调用申请接口。 - startContinuousTask(); - processAsyncJobs(); - }, - onStop() { - console.info('ServiceAbility onStop'); - }, - onConnect(want) { - console.info('ServiceAbility onConnect'); - return mMyStub; - }, - onReconnect(want) { - console.info('ServiceAbility onReconnect'); - }, - onDisconnect() { - console.info('ServiceAbility onDisconnect'); - }, - onCommand(want, restart, startId) { - console.info('ServiceAbility onCommand'); - } - }; + function startContinuousTask() { + let wantAgentInfo: wantAgent.WantAgentInfo = { + // 点击通知后,将要执行的动作列表 + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + // 点击通知后,动作类型 + operationType: wantAgent.OperationType.START_ABILITY, + // 使用者自定义的一个私有值 + requestCode: 0, + // 点击通知后,动作执行属性 + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { + console.info(`Succeeded in operationing startBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + }); + } + + function stopContinuousTask() { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info(`Succeeded in operationing stopBackgroundRunning.`); + }).catch((err: BusinessError) => { + console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); + }); + } + + async function processAsyncJobs() { + // 此处执行具体的长时任务。 + + // 长时任务执行完,调用取消接口,释放资源。 + stopContinuousTask(); + } + + let mMyStub: MyStub; + + class MyStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + console.log('ServiceAbility onRemoteRequest called'); + // code 的具体含义用户自定义 + if (code === 1) { + // 接收到申请长时任务的请求码 + startContinuousTask(); + // 此处执行具体长时任务 + } else if (code === 2) { + // 接收到取消长时任务的请求码 + stopContinuousTask(); + } else { + console.log('ServiceAbility unknown request code'); + } + return true; + } + } + + export default { + onStart(want) { + console.info('ServiceAbility onStart'); + mMyStub = new MyStub("ServiceAbility-test"); + // 在执行长时任务前,调用申请接口。 + startContinuousTask(); + processAsyncJobs(); + }, + onStop() { + console.info('ServiceAbility onStop'); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return mMyStub; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, restart, startId) { + console.info('ServiceAbility onCommand'); + } + }; ``` diff --git a/zh-cn/application-dev/task-management/work-scheduler.md b/zh-cn/application-dev/task-management/work-scheduler.md index 484f68b5b93cf0b33a2e8e9cf0f86a2c3181694f..151854ae89fdd2cfe5e25900b33e89ca72b39abe 100644 --- a/zh-cn/application-dev/task-management/work-scheduler.md +++ b/zh-cn/application-dev/task-management/work-scheduler.md @@ -121,6 +121,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: ```ts import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + import workScheduler fron '@ohos.resourceschedule.workScheduler'; ``` 3. 实现WorkSchedulerExtension生命周期接口。 @@ -128,12 +129,12 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: ```ts export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { // 延迟任务开始回调 - onWorkStart(workInfo) { + onWorkStart(workInfo: workScheduler.WorkInfo) { console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`); } // 延迟任务结束回调 - onWorkStop(workInfo) { + onWorkStop(workInfo: workScheduler.WorkInfo) { console.info(`onWorkStop, workInfo is ${JSON.stringify(workInfo)}`); } } @@ -173,7 +174,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: 2. 申请延迟任务。 ```ts - private workInfo = { + private workInfo: workScheduler.WorkInfo = { workId: 1, networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, bundleName: 'com.example.application', @@ -183,7 +184,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: try { workScheduler.startWork(this.workInfo); console.info(`startWork success`); - } catch (error) { + } catch (error: BusinessError) { console.error(`startWork failed. code is ${error.code} message is ${error.message}`); } ``` @@ -191,7 +192,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: 3. 取消延迟任务。 ```ts - private workInfo = { + private workInfo: workScheduler.workInfo = { workId: 1, networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, bundleName: 'com.example.application', @@ -201,7 +202,7 @@ WorkInfo参数用于设置应用条件,参数设置时需遵循以下规则: try { workScheduler.stopWork(this.workInfo); console.info(`stopWork success`); - } catch (error) { + } catch (error: BusinessError) { console.error(`stopWork failed. code is ${error.code} message is ${error.message}`); } ``` diff --git a/zh-cn/application-dev/tools/bm-tool.md b/zh-cn/application-dev/tools/bm-tool.md index f5c4bccb9dc5b39f692d3799822efeac1ee0f3fa..d78804fa5b1fa20a84c603adee000b7a7849cbb0 100644 --- a/zh-cn/application-dev/tools/bm-tool.md +++ b/zh-cn/application-dev/tools/bm-tool.md @@ -415,19 +415,14 @@ bm dump-dependencies -n com.ohos.app -m entry ``` find /system -name install_list_capability.json ``` - HarmonyOS设备上install_list_capability.json的位置通常为以下几种,选取其中一个即可: - ``` - /system/variant/phone/base/etc/app/install_list_capability.json - /system/etc/app/install_list_capability.json - ``` - OpenHarmony设备上install_list_capability.json的位置通常为: + 设备上install_list_capability.json的位置通常为以下目录地址,通过bundleName找到对应的配置文件: ``` /system/etc/app/install_list_capability.json ``` c. 执行如下命令拉取install_list_capability.json。 ``` hdc shell mount -o rw,remount / - hdc file recv /system/variant/phone/base/etc/app/install_list_capability.json + hdc file recv /system/etc/app/install_list_capability.json ``` 3. 将步骤1获取到的签名指纹配置到install_list_capability.json文件的app_signature中,注意要配置到对应的bundleName下。 @@ -436,8 +431,8 @@ bm dump-dependencies -n com.ohos.app -m entry ``` hdc shell mount -o rw,remount / - hdc file send install_list_capability.json /system/variant/phone/base/etc/app/install_list_capability.json - hdc shell chmod 777 /system/variant/phone/base/etc/app/install_list_capability.json + hdc file send install_list_capability.json /system/etc/app/install_list_capability.json + hdc shell chmod 777 /system/etc/app/install_list_capability.json hdc shell reboot ``` 5. 设备重启后,重新安装新的应用即可。 @@ -470,7 +465,7 @@ bm dump-dependencies -n com.ohos.app -m entry 出现该问题的原因是配置文件app.json5和module.json5中必填字段缺失。 -* 方法1:请参考[app.json5配置文件](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/app-configuration-file-0000001558277229-V3)和[module.json5配置文件](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/module-configuration-file-0000001506957668-V3)查看并补充必填字段。 +* 方法1:请参考[app.json5配置文件](../../application-dev/quick-start/app-configuration-file.md)和[module.json5配置文件](../../application-dev/quick-start/module-configuration-file.md)查看并补充必填字段。 * 方法2:通过hilog日志判断缺失字段。 开启落盘命令: @@ -505,7 +500,11 @@ bm dump-dependencies -n com.ohos.app -m entry 该问题是由于签名中未包含该调试设备的UDID,请通过如下步骤进行解决。 * 使用[自动签名](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/signing-0000001587684945-V3#section18815157237)。在连接设备后,重新为应用进行签名。 -* 如果使用的是手动签名,对于HarmonyOS应用,请在AppGallery Connect中先将该调试设备[注册调试设备](https://developer.huawei.com/consumer/cn/doc/distribution/app/agc-help-harmonyos-debugapp-manual-0000001177608893#section7732152932911)并在[申请Profile文件](https://developer.huawei.com/consumer/cn/doc/distribution/app/agc-help-harmonyos-debugapp-manual-0000001177608893?ha_linker=eyJ0cyI6MTY4NzkzNDEzOTk1OSwiaWQiOiJhZjdhYzI0MDlkMGQ5MzQ1MzFlNDE3NDQ5MmY4MjJkMyJ9#section1774717395304)选择设备时添加该调试设备,重新申请Profile证书;对于OpenHarmony应用,请参考[OpenHarmony应用手动签名](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/hapsigntool-guidelines.md),在UnsgnedDebugProfileTemplate.json文件中添加该调试设备的[UDID](https://developer.huawei.com/consumer/cn/doc/distribution/app/agc-help-harmonyos-debugapp-manual-0000001177608893#section1835412326017)。 +* 如果使用的是手动签名,对于OpenHarmony应用,请参考[OpenHarmony应用手动签名](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/hapsigntool-guidelines.md),在UnsgnedDebugProfileTemplate.json文件中添加该调试设备的**UDID** +``` +//UDID获取命令 +hdc shell bm get -u +``` ### 安装HAP时提示“code:9568289 error: install failed due to grant request permissions failed” **问题现象** @@ -518,7 +517,7 @@ bm dump-dependencies -n com.ohos.app -m entry 该问题是由于默认应用等级为normal,只能使用normal等级的权限,如果使用了system_basic或system_core等级的权限,将导致报错。 -对于HarmonyOS应用,请参考[使用ACL签名配置指导](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/signing-0000001587684945-V3?catalogVersion=V3#section157591551175916)完成ACL提权;对于OpenHarmony应用,请参考[修改应用权限等级](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465#section42735161005)修改签名模板。 +在UnsgnedDebugProfileTemplate.json文件中修改apl等级,调整成system_basic或system_core等级,重新签名打包即可。 ### 安装HAP时提示“code:9568297 error: install failed due to older sdk version in the device” **问题现象** @@ -551,18 +550,3 @@ bm dump-dependencies -n com.ohos.app -m entry 该问题是由于设备上已安装的应用与新安装的应用中签名不一致。如果在**Edit Configurations**中勾选了“Keep Application Data”(不卸载应用,覆盖安装),并且重新进行了签名,将导致该报错。 请卸载设备上已安装的应用,或取消勾选“Keep Application Data”后,重新安装新的应用。 - -### 安装HAP时提示“code:9568257 error: fail to verify pkcs7 file” -**问题现象** - -在启动调试或者运行应用/服务时,安装HAP出现错误,提示”error: fail to verify pkcs7 file“错误信息。 - -![示例图](figures/zh-cn_image_00000016359212344.png) - -**解决措施** - -出现该问题的原因是应用当前使用的签名不符合HarmonyOS应用签名的要求。通常是由于当前使用的是OpenHarmony应用的签名,需替换为HarmonyOS应用的签名。 - -请在[为应用/服务签名](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/signing-0000001587684945-V3)时勾选”Support HarmonyOS“,完成HarmonyOS应用签名后再次启动调试或者运行应用。 - -![示例图](figures/zh-cn_image_00000016359212311.png) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/Readme-CN.md b/zh-cn/application-dev/ui/Readme-CN.md index a38ad81aae01995390d1acbaa71d7f14fff17a0f..7fb261470fb29f24c71cf9ee55a03ac9f362230f 100755 --- a/zh-cn/application-dev/ui/Readme-CN.md +++ b/zh-cn/application-dev/ui/Readme-CN.md @@ -51,6 +51,7 @@ - [导航转场](arkts-navigation-transition.md) - [模态转场](arkts-modal-transition.md) - [共享元素转场](arkts-shared-element-transition.md) + - [页面转场动画(不推荐)](arkts-page-transition-animation.md) - [组件动画](arkts-component-animation.md) - 动画曲线 - [动画曲线概述](arkts-curve-overview.md) diff --git a/zh-cn/application-dev/ui/arkts-navigation-transition.md b/zh-cn/application-dev/ui/arkts-navigation-transition.md index 9001828b0b4ba8d14fa1e988c71e5628991dac1d..83301756fcb3ab56d3c62ff04f3596e43362f965 100644 --- a/zh-cn/application-dev/ui/arkts-navigation-transition.md +++ b/zh-cn/application-dev/ui/arkts-navigation-transition.md @@ -4,7 +4,7 @@ 导航转场是页面的路由转场方式,也就是一个界面消失,另外一个界面出现的动画效果。导航转场的动画效果是系统定义的,开发者不能修改。 -导航转场推荐使用[Navigation](../reference/arkui-ts/ts-basic-components-navigation.md)组件实现,可搭配[NavRouter](../reference/arkui-ts/ts-basic-components-navrouter.md)组件和[NavDestination](../reference/arkui-ts/ts-basic-components-navdestination.md)组件实现导航功能。 +导航转场推荐使用[Navigation](arkts-navigation-navigation.md)组件实现,可搭配[NavRouter](../reference/arkui-ts/ts-basic-components-navrouter.md)组件和[NavDestination](../reference/arkui-ts/ts-basic-components-navdestination.md)组件实现导航功能。 完整的代码示例和效果如下。 diff --git a/zh-cn/application-dev/ui/arkts-page-transition-animation.md b/zh-cn/application-dev/ui/arkts-page-transition-animation.md new file mode 100644 index 0000000000000000000000000000000000000000..91b16f044c871184772286662b19d45969d1ca3a --- /dev/null +++ b/zh-cn/application-dev/ui/arkts-page-transition-animation.md @@ -0,0 +1,363 @@ +# 页面转场动画(不推荐) + +为了实现更好的转场效果,推荐使用[导航转场](arkts-navigation-transition.md)和[模态转场](arkts-modal-transition.md)。 + + +两个页面间发生跳转,一个页面消失,另一个页面出现,这时可以配置各自页面的页面转场参数实现自定义的页面转场效果。[页面转场](../reference/arkui-ts/ts-page-transition-animation.md)效果写在pageTransition函数中,通过PageTransitionEnter和PageTransitionExit指定页面进入和退出的动画效果。 + + +PageTransitionEnter的接口为: + + + +```ts +PageTransitionEnter({type?: RouteType,duration?: number,curve?: Curve | string,delay?: number}) +``` + + +PageTransitionExit的接口为: + + + +```ts +PageTransitionExit({type?: RouteType,duration?: number,curve?: Curve | string,delay?: number}) +``` + + +上述接口定义了PageTransitionEnter和PageTransitionExit组件,可通过slide、translate、scale、opacity属性定义不同的页面转场效果。对于PageTransitionEnter而言,这些效果表示入场时起点值,对于PageTransitionExit而言,这些效果表示退场的终点值,这一点与组件转场transition配置方法类似。此外,PageTransitionEnter提供了onEnter接口进行自定义页面入场动画的回调,PageTransitionExit提供了onExit接口进行自定义页面退场动画的回调。 + + +上述接口中的参数type,表示路由生效的类型,这一点开发者容易混淆其含义。页面转场的两个页面,必定有一个页面退出,一个页面进入。如果通过router.pushUrl操作从页面A跳转到页面B,则页面A退出,做页面退场动画,页面B进入,做页面入场动画。如果通过router.back操作从页面B返回到页面A,则页面B退出,做页面退场动画,页面A进入,做页面入场动画。即页面的PageTransitionEnter既可能是由于新增页面(push,入栈)引起的新页面的入场动画,也可能是由于页面返回(back,或pop,出栈)引起的页面栈中老页面的入场动画,为了能区分这两种形式的入场动画,提供了type参数,这样开发者能完全定义所有类型的页面转场效果。 + + +## type配置为RouteType.None + +type为RouteType.None表示对页面栈的push、pop操作均生效,type的默认值为RouteType.None。 + + +```ts +// page A +pageTransition() { + // 定义页面进入时的效果,从左侧滑入,时长为1200ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionEnter({ type: RouteType.None, duration: 1200 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向左侧滑出,时长为1000ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionExit({ type: RouteType.None, duration: 1000 }) + .slide(SlideEffect.Left) +} +``` + + + +```ts +// page B +pageTransition() { + // 定义页面进入时的效果,从右侧滑入,时长为1000ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionEnter({ type: RouteType.None, duration: 1000 }) + .slide(SlideEffect.Right) + // 定义页面退出时的效果,向右侧滑出,时长为1200ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionExit({ type: RouteType.None, duration: 1200 }) + .slide(SlideEffect.Right) +} +``` + + +假设页面跳转配置为多实例模式,即页面栈中允许存在重复的页面。可能会有4种场景,对应的页面转场效果如下表。 + + +| 路由操作 | 页面A转场效果 | 页面B转场效果 | +| ---------------------------- | ---------------------------------- | ---------------------------------- | +| router.pushUrl,从页面A跳转到新增的页面B | 页面退出,PageTransitionExit生效,向左侧滑出屏幕 | 页面进入,PageTransitionEnter生效,从右侧滑入屏幕 | +| router.back,从页面B返回到页面A | 页面进入,PageTransitionEnter生效,从左侧滑入屏幕 | 页面退出,PageTransitionExit生效,向右侧滑出屏幕 | +| router.pushUrl,从页面B跳转到新增的页面A | 页面进入,PageTransitionEnter生效,从左侧滑入屏幕 | 页面退出,PageTransitionExit生效,向右侧滑出屏幕 | +| router.back,从页面A返回到页面B | 页面退出,PageTransitionExit生效,向左侧滑出屏幕 | 页面进入,PageTransitionEnter生效,从右侧滑入屏幕 | + + +如果希望pushUrl进入的页面总是从右侧滑入,back时退出的页面总是从右侧滑出,则上表中的第3、4种情况不满足要求,那么需要完整的定义4个页面转场效果。 + + +## type配置为RouteType.Push或RouteType.Pop + +type为RouteType.Push表示仅对页面栈的push操作生效,type为RouteType.Pop表示仅对页面栈的pop操作生效。 + + +```ts +// page A +pageTransition() { + // 定义页面进入时的效果,从右侧滑入,时长为1200ms,页面栈发生push操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Push, duration: 1200 }) + .slide(SlideEffect.Right) + // 定义页面进入时的效果,从左侧滑入,时长为1200ms,页面栈发生pop操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Pop, duration: 1200 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向左侧滑出,时长为1000ms,页面栈发生push操作时该效果才生效 + PageTransitionExit({ type: RouteType.Push, duration: 1000 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向右侧滑出,时长为1000ms,页面栈发生pop操作时该效果才生效 + PageTransitionExit({ type: RouteType.Pop, duration: 1000 }) + .slide(SlideEffect.Right) +} +``` + + + +```ts +// page B +pageTransition() { + // 定义页面进入时的效果,从右侧滑入,时长为1000ms,页面栈发生push操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Push, duration: 1000 }) + .slide(SlideEffect.Right) + // 定义页面进入时的效果,从左侧滑入,时长为1000ms,页面栈发生pop操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Pop, duration: 1000 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向左侧滑出,时长为1200ms,页面栈发生push操作时该效果才生效 + PageTransitionExit({ type: RouteType.Push, duration: 1200 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向右侧滑出,时长为1200ms,页面栈发生pop操作时该效果才生效 + PageTransitionExit({ type: RouteType.Pop, duration: 1200 }) + .slide(SlideEffect.Right) +} +``` + + +以上代码则完整的定义了所有可能的页面转场样式。假设页面跳转配置为多实例模式,即页面栈中允许存在重复的页面。可能会有4种场景,对应的页面转场效果如下表。 + + +| 路由操作 | 页面A转场效果 | 页面B转场效果 | +| ---------------------------- | ---------------------------------------- | ---------------------------------------- | +| router.pushUrl,从页面A跳转到新增的页面B | 页面退出,PageTransitionExit且type为RouteType.Push的转场样式生效,向左侧滑出屏幕 | 页面进入,PageTransitionEnter且type为RouteType.Push的转场样式生效,从右侧滑入屏幕 | +| router.back,从页面B返回到页面A | 页面进入,PageTransitionEnter且type为RouteType.Pop的转场样式生效,从左侧滑入屏幕 | 页面退出,PageTransitionExit且type为RouteType.Pop的转场样式生效,向右侧滑出屏幕 | +| router.pushUrl,从页面B跳转到新增的页面A | 页面进入,PageTransitionEnter且type为RouteType.Push的转场样式生效,从右侧滑入屏幕 | 页面退出,PageTransitionExit且type为RouteType.Push的转场样式生效,向左侧滑出屏幕 | +| router.back,从页面A返回到页面B | 页面退出,PageTransitionExit且type为RouteType.Pop的转场样式生效,向右侧滑出屏幕 | 页面进入,PageTransitionEnter且type为RouteType.Pop的转场样式生效,从左侧滑入屏幕 | + + +>**说明:** +> +> 1. 由于每个页面的页面转场样式都可由开发者独立配置,而页面转场涉及到两个页面,开发者应考虑两个页面的页面转场效果的衔接,如时长尽量保持一致。 +> +> 2. 如果没有定义匹配的页面转场样式,则该页面使用系统默认的页面转场样式。 + + +## 禁用某页面的页面转场 + + +```ts +pageTransition() { + PageTransitionEnter({ type: RouteType.None, duration: 0 }) + PageTransitionExit({ type: RouteType.None, duration: 0 }) +} +``` + + +通过设置页面转场的时长为0,可使该页面无页面转场动画。 + + +## 场景示例 + +下面介绍定义了所有的四种页面转场样式的页面转场动画示例。 + + + +```ts +// PageTransitionSrc1 +import router from '@ohos.router'; +@Entry +@Component +struct PageTransitionSrc1 { + build() { + Column() { + Image($r('app.media.mountain')) + .width('90%') + .height('80%') + .objectFit(ImageFit.Fill) + .syncLoad(true) // 同步加载图片,使页面出现时图片已经加载完成 + .margin(30) + + Row({ space: 10 }) { + Button("pushUrl") + .onClick(() => { + // 路由到下一个页面,push操作 + router.pushUrl({ url: 'pages/myTest/pageTransitionDst1' }); + }) + Button("back") + .onClick(() => { + // 返回到上一页面,相当于pop操作 + router.back(); + }) + }.justifyContent(FlexAlign.Center) + } + .width("100%").height("100%") + .alignItems(HorizontalAlign.Center) + } + + pageTransition() { + // 定义页面进入时的效果,从右侧滑入,时长为1000ms,页面栈发生push操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Push, duration: 1000 }) + .slide(SlideEffect.Right) + // 定义页面进入时的效果,从左侧滑入,时长为1000ms,页面栈发生pop操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Pop, duration: 1000 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向左侧滑出,时长为1000ms,页面栈发生push操作时该效果才生效 + PageTransitionExit({ type: RouteType.Push, duration: 1000 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向右侧滑出,时长为1000ms,页面栈发生pop操作时该效果才生效 + PageTransitionExit({ type: RouteType.Pop, duration: 1000 }) + .slide(SlideEffect.Right) + } +} +``` + + + + +```ts +// PageTransitionDst1 +import router from '@ohos.router'; +@Entry +@Component +struct PageTransitionDst1 { + build() { + Column() { + Image($r('app.media.forest')) + .width('90%') + .height('80%') + .objectFit(ImageFit.Fill) + .syncLoad(true) // 同步加载图片,使页面出现时图片已经加载完成 + .margin(30) + + Row({ space: 10 }) { + Button("pushUrl") + .onClick(() => { + // 路由到下一页面,push操作 + router.pushUrl({ url: 'pages/myTest/pageTransitionSrc1' }); + }) + Button("back") + .onClick(() => { + // 返回到上一页面,相当于pop操作 + router.back(); + }) + }.justifyContent(FlexAlign.Center) + } + .width("100%").height("100%") + .alignItems(HorizontalAlign.Center) + } + + pageTransition() { + // 定义页面进入时的效果,从右侧滑入,时长为1000ms,页面栈发生push操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Push, duration: 1000 }) + .slide(SlideEffect.Right) + // 定义页面进入时的效果,从左侧滑入,时长为1000ms,页面栈发生pop操作时该效果才生效 + PageTransitionEnter({ type: RouteType.Pop, duration: 1000 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向左侧滑出,时长为1000ms,页面栈发生push操作时该效果才生效 + PageTransitionExit({ type: RouteType.Push, duration: 1000 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,向右侧滑出,时长为1000ms,页面栈发生pop操作时该效果才生效 + PageTransitionExit({ type: RouteType.Pop, duration: 1000 }) + .slide(SlideEffect.Right) + } +} +``` + + + +![pageTransition_PushPop](figures/pageTransition_PushPop.gif) + + +下面介绍使用了type为None的页面转场动画示例。 + + + +```ts +// PageTransitionSrc2 +import router from '@ohos.router'; +@Entry +@Component +struct PageTransitionSrc2 { + build() { + Column() { + Image($r('app.media.mountain')) + .width('90%') + .height('80%') + .objectFit(ImageFit.Fill) + .syncLoad(true) // 同步加载图片,使页面出现时图片已经加载完成 + .margin(30) + + Row({ space: 10 }) { + Button("pushUrl") + .onClick(() => { + // 路由到下一页面,push操作 + router.pushUrl({ url: 'pages/myTest/pageTransitionDst2' }); + }) + Button("back") + .onClick(() => { + // 返回到上一页面,相当于pop操作 + router.back(); + }) + }.justifyContent(FlexAlign.Center) + } + .width("100%").height("100%") + .alignItems(HorizontalAlign.Center) + } + + pageTransition() { + // 定义页面进入时的效果,从左侧滑入,时长为1000ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionEnter({ duration: 1000 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,相对于正常页面位置x方向平移100vp,y方向平移100vp,透明度变为0,时长为1200ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionExit({ duration: 1200 }) + .translate({ x: 100.0, y: 100.0 }) + .opacity(0) + } +} +``` + + + +```ts +// PageTransitionDst2 +import router from '@ohos.router'; +@Entry +@Component +struct PageTransitionDst2 { + build() { + Column() { + Image($r('app.media.forest')) + .width('90%') + .height('80%') + .objectFit(ImageFit.Fill) + .syncLoad(true) // 同步加载图片,使页面出现时图片已经加载完成 + .margin(30) + + Row({ space: 10 }) { + Button("pushUrl") + .onClick(() => { + // 路由到下一页面,push操作 + router.pushUrl({ url: 'pages/myTest/pageTransitionSrc2' }); + }) + Button("back") + .onClick(() => { + // 返回到上一页面,相当于pop操作 + router.back(); + }) + }.justifyContent(FlexAlign.Center) + } + .width("100%").height("100%") + .alignItems(HorizontalAlign.Center) + } + + pageTransition() { + // 定义页面进入时的效果,从左侧滑入,时长为1200ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionEnter({ duration: 1200 }) + .slide(SlideEffect.Left) + // 定义页面退出时的效果,相对于正常页面位置x方向平移100vp,y方向平移100vp,透明度变为0,时长为1000ms,无论页面栈发生push还是pop操作均可生效 + PageTransitionExit({ duration: 1000 }) + .translate({ x: 100.0, y: 100.0 }) + .opacity(0) + } +} +``` + + + +![pageTransition_None](figures/pageTransition_None.gif) diff --git a/zh-cn/application-dev/ui/arkts-transition-overview.md b/zh-cn/application-dev/ui/arkts-transition-overview.md index ef85c09096048c9fad674e225b9c321468072970..a62ef5ffaa473f6fab6e4736ad19f12e20cbfc5e 100644 --- a/zh-cn/application-dev/ui/arkts-transition-overview.md +++ b/zh-cn/application-dev/ui/arkts-transition-overview.md @@ -15,6 +15,8 @@ - [共享元素转场](arkts-shared-element-transition.md):共享元素转场是一种界面切换时对相同或者相似的元素做的一种位置和大小匹配的过渡动画效果。 +- [页面转场动画(不推荐)](arkts-page-transition-animation.md):页面的路由转场方式,可以通过在pageTransition函数中自定义页面入场和页面退场的转场动效。为了实现更好的转场效果,推荐使用[导航转场](arkts-navigation-transition.md)和[模态转场](arkts-modal-transition.md)。 + ## 相关实例 针对转场动画开发,有以下相关实例可供参考“ diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index 32145eeea5d434e0cf6e7e9dc2a9ff9644514914..b263ba355afbad6969d9e45ae2142a8082c3a88b 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -25,9 +25,6 @@ - HSP - [应用内HSP开发指导](quick-start/in-app-hsp.md) - [应用间HSP开发指导](quick-start/cross-app-hsp.md) - - 原子化服务 - - [原子化服务开发指导](quick-start/atomicService.md) - - [原子化服务空间管理(仅对系统应用开放)](quick-start/atomicService-aging.md) - 应用程序包快速修复 - [快速修复概述](quick-start/quickfix-principles.md) - [快速修复命令行调试开发指导](quick-start/quickfix-debug.md) @@ -302,8 +299,10 @@ - [导航转场](ui/arkts-navigation-transition.md) - [模态转场](ui/arkts-modal-transition.md) - [共享元素转场](ui/arkts-shared-element-transition.md) + - [页面转场动画(不推荐)](ui/arkts-page-transition-animation.md) - [组件动画](ui/arkts-component-animation.md) - 动画曲线 + - [动画曲线概述](ui/arkts-curve-overview.md) - [传统曲线](ui/arkts-traditional-curve.md) - [弹簧曲线](ui/arkts-spring-curve.md) - [动画衔接](ui/arkts-animation-smoothing.md) @@ -481,6 +480,7 @@ - [开发音频通话功能](media/audio-call-development.md) - [视频播放](media/video-playback.md) - [视频录制](media/video-recording.md) + - [屏幕录制](media/avscreen-capture.md) - 音视频编解码 - [获取支持的编解码能力](media/obtain-supported-codecs.md) - [音频编码](media/audio-encoding.md) @@ -633,7 +633,7 @@ - [短时任务](task-management/transient-task.md) - [长时任务](task-management/continuous-task.md) - [延迟任务](task-management/work-scheduler.md) - - [代理提醒](task-management/agent-powered-reminder.md) + - [代理提醒](task-management/agent-powered-reminder.md) - [能效资源申请(仅对系统特权应用开放)](task-management/efficiency-resource-request.md) - 设备管理 - USB服务 @@ -749,6 +749,8 @@ - [Purgeable memory开发指导](napi/purgeable-memory-guidelines.md) - 设备管理 - [USB DDK开发指导](napi/usb-ddk-guidelines.md) + - 数据管理 + - [RelationalStore开发指导](napi/native-relational-store-guidelines.md) - 工具 - [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md) - 调试工具 @@ -777,14 +779,18 @@ - [@ohos.app.ability.AbilityConstant (AbilityConstant)](reference/apis/js-apis-app-ability-abilityConstant.md) - [@ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback)](reference/apis/js-apis-app-ability-abilityLifecycleCallback.md) - [@ohos.app.ability.AbilityStage (AbilityStage)](reference/apis/js-apis-app-ability-abilityStage.md) + - [@ohos.app.ability.ActionExtensionAbility (自定义服务扩展能力)](reference/apis/js-apis-app-ability-actionExtensionAbility.md) - [@ohos.app.ability.ApplicationStateChangeCallback (ApplicationStateChangeCallback)](reference/apis/js-apis-app-ability-applicationStateChangeCallback.md) - [@ohos.app.ability.common (应用上下文Context)](reference/apis/js-apis-app-ability-common.md) - [@ohos.app.ability.contextConstant (ContextConstant)](reference/apis/js-apis-app-ability-contextConstant.md) - [@ohos.app.ability.EnvironmentCallback (EnvironmentCallback)](reference/apis/js-apis-app-ability-environmentCallback.md) - [@ohos.app.ability.ExtensionAbility (扩展能力基类)](reference/apis/js-apis-app-ability-extensionAbility.md) - [@ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility)](reference/apis/js-apis-app-ability-serviceExtensionAbility.md) + - [@ohos.app.ability.ShareExtensionAbility (分享模板服务扩展能力)](reference/apis/js-apis-app-ability-shareExtensionAbility.md) - [@ohos.app.ability.StartOptions (StartOptions)](reference/apis/js-apis-app-ability-startOptions.md) - [@ohos.app.ability.UIAbility (UIAbility)](reference/apis/js-apis-app-ability-uiAbility.md) + - [@ohos.app.ability.UIExtensionAbility (带界面扩展能力基类)](reference/apis/js-apis-app-ability-uiExtensionAbility.md) + - [@ohos.app.ability.UIExtensionContentSession (带界面扩展能力界面操作类)](reference/apis/js-apis-app-ability-uiExtensionContentSession.md) - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](reference/apis/js-apis-app-form-formExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (数据共享扩展能力)](reference/apis/js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](reference/apis/js-apis-application-staticSubscriberExtensionAbility.md) @@ -811,8 +817,9 @@ - [@ohos.app.form.formBindingData (卡片数据绑定类)](reference/apis/js-apis-app-form-formBindingData.md) - [@ohos.app.form.formHost (FormHost)](reference/apis/js-apis-app-form-formHost.md) - [@ohos.app.form.formInfo (FormInfo)](reference/apis/js-apis-app-form-formInfo.md) + - [@ohos.app.form.formObserver (formObserver)](reference/apis/js-apis-app-form-formObserver.md) - [@ohos.app.form.formProvider (FormProvider)](reference/apis/js-apis-app-form-formProvider.md) - - [@ohos.application.uriPermissionManager(URI权限管理)](reference/apis/js-apis-uripermissionmanager.md) + - [@ohos.application.uriPermissionManager (URI权限管理)](reference/apis/js-apis-uripermissionmanager.md) - 通用能力的接口(待停用) - [@ohos.ability.dataUriUtils (DataUriUtils模块)](reference/apis/js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode (ErrorCode)](reference/apis/js-apis-ability-errorCode.md) @@ -875,6 +882,7 @@ - [ProcessInformation](reference/apis/js-apis-inner-application-processInformation.md) - [ServiceExtensionContext](reference/apis/js-apis-inner-application-serviceExtensionContext.md) - [UIAbilityContext](reference/apis/js-apis-inner-application-uiAbilityContext.md) + - [UIExtensionContext](reference/apis/js-apis-inner-application-uiExtensionContext.md) - [shellCmdResult](reference/apis/js-apis-inner-application-shellCmdResult.md) - [WindowExtensionContext](reference/apis/js-apis-inner-application-windowExtensionContext.md) - wantAgent @@ -968,7 +976,7 @@ - [@ohos.arkui.dragController (DragController)](reference/apis/js-apis-arkui-dragController.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](reference/apis/js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.inspector (布局回调)](reference/apis/js-apis-arkui-inspector.md) - - [ @ohos.arkui.performanceMonitor (性能监测)](reference/apis/js-apis-arkui-performancemonitor.md) + - [@ohos.arkui.performanceMonitor (性能监测)](reference/apis/js-apis-arkui-performancemonitor.md) - [@ohos.arkui.UIContext (UIContext)](reference/apis/js-apis-arkui-UIContext.md) - [@ohos.curves (插值计算)](reference/apis/js-apis-curve.md) - [@ohos.font (注册自定义字体)](reference/apis/js-apis-font.md) @@ -1036,7 +1044,8 @@ - [@ohos.data.distributedKVStore (分布式键值数据库)](reference/apis/js-apis-distributedKVStore.md) - [@ohos.data.preferences (用户首选项)](reference/apis/js-apis-data-preferences.md) - [@ohos.data.relationalStore (关系型数据库)](reference/apis/js-apis-data-relationalStore.md) - - [@ohos.data.UDMF (统一数据管理框架)](reference/apis/js-apis-data-udmf.md) + - [@ohos.data.unifiedDataChannel (标准化数据通路)](reference/apis/js-apis-data-unifiedDataChannel.md) + - [@ohos.data.uniformTypeDescriptor (标准化数据定义与描述)](reference/apis/js-apis-data-uniformTypeDescriptor.md) - [@ohos.data.ValuesBucket (数据集)](reference/apis/js-apis-data-valuesBucket.md) - 文件管理 - [@ohos.file.backup (备份恢复)](reference/apis/js-apis-file-backup.md) @@ -1058,6 +1067,7 @@ - [@ohos.fileshare (文件分享)](reference/apis/js-apis-fileShare.md) - AI - [@ohos.ai.mindSporeLite (推理能力)](reference/apis/js-apis-mindSporeLite.md) + - [@ohos.ai.intelligentVoice (智能语音)](reference/apis/js-apis-intelligentVoice.md) - 电话服务 - [@ohos.contact (联系人)](reference/apis/js-apis-contact.md) - [@ohos.telephony.call (拨打电话)](reference/apis/js-apis-call.md) @@ -1145,10 +1155,10 @@ - [@ohos.charger (充电类型)](reference/apis/js-apis-charger.md) - [@ohos.cooperate (键鼠穿越)](reference/apis/js-apis-devicestatus-cooperate.md) - [@ohos.deviceAttest (设备证明)](reference/apis/js-apis-deviceAttest.md) - - [@ohos.deviceStatus.dragInteraction(拖拽)](reference/apis/js-apis-devicestatus-draginteraction.md) + - [@ohos.deviceStatus.dragInteraction (拖拽)](reference/apis/js-apis-devicestatus-draginteraction.md) - [@ohos.deviceInfo (设备信息)](reference/apis/js-apis-device-info.md) - - [@ohos.distributedDeviceManager (设备管理)(推荐)](reference/apis/js-apis-distributedDeviceManager.md) - - [@ohos.distributedHardware.deviceManager (设备管理)(待废弃)](reference/apis/js-apis-device-manager.md) + - [@ohos.distributedDeviceManager (设备管理)](reference/apis/js-apis-distributedDeviceManager.md) + - [@ohos.distributedHardware.deviceManager (设备管理)](reference/apis/js-apis-device-manager.md) - [@ohos.driver.deviceManager (外设管理)](reference/apis/js-apis-driver-deviceManager.md) - [@ohos.geoLocationManager (位置服务)](reference/apis/js-apis-geoLocationManager.md) - [@ohos.multimodalInput.gestureEvent (手势事件)](reference/apis/js-apis-multimodalinput-gestureevent.md) @@ -1166,6 +1176,7 @@ - [@ohos.multimodalInput.touchEvent (触摸输入事件)](reference/apis/js-apis-touchevent.md) - [@ohos.multimodalInput.shortKey(快捷键)](reference/apis/js-apis-shortKey.md) - [@ohos.power (系统电源管理)](reference/apis/js-apis-power.md) + - [@ohos.resourceschedule.deviceStandby (设备待机模块)](reference/apis/js-apis-resourceschedule-deviceStandby.md) - [@ohos.runningLock (Runninglock锁)](reference/apis/js-apis-runninglock.md) - [@ohos.sensor (传感器)](reference/apis/js-apis-sensor.md) - [@ohos.settings (设置数据项名称)](reference/apis/js-apis-settings.md) @@ -1198,6 +1209,7 @@ - [@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.networkManager (网络管理)](reference/apis/js-apis-enterprise-networkManager.md) - [@ohos.enterprise.restrictions (限制类策略)](reference/apis/js-apis-enterprise-restrictions.md) + - [@ohos.enterprise.usbManager (USB管理)](reference/apis/js-apis-enterprise-usbManager.md) - [@ohos.enterprise.wifiManager (WiFi管理)](reference/apis/js-apis-enterprise-wifiManager.md) - 语言基础类库 - [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md) @@ -1396,7 +1408,6 @@ - [Web](reference/arkui-ts/ts-basic-components-web.md) - [XComponent](reference/arkui-ts/ts-basic-components-xcomponent.md) - 容器组件 - - [AbilityComponent](reference/arkui-ts/ts-container-ability-component.md) - [Badge](reference/arkui-ts/ts-container-badge.md) - [Column](reference/arkui-ts/ts-container-column.md) - [ColumnSplit](reference/arkui-ts/ts-container-columnsplit.md) @@ -1475,6 +1486,7 @@ - [枚举说明](reference/arkui-ts/ts-appendix-enums.md) - [类型定义](reference/arkui-ts/ts-types.md) - 已停止维护的组件 + - [AbilityComponent](reference/arkui-ts/ts-container-ability-component.md) - [GridContainer](reference/arkui-ts/ts-container-gridcontainer.md) - 已停止维护的接口 - [点击控制](reference/arkui-ts/ts-universal-attributes-click.md) @@ -1584,6 +1596,8 @@ - [文件组织](reference/arkui-js-lite/js-framework-file.md) - [js标签配置](reference/arkui-js-lite/js-framework-js-tag.md) - [app.js](reference/arkui-js-lite/js-framework-js-file.md) + - [生命周期](reference/arkui-js-lite/js-framework-lifecycle.md) + - [多语言](reference/arkui-js-lite/js-framework-localization.md) - 语法 - [HML语法参考](reference/arkui-js-lite/js-framework-syntax-hml.md) - [CSS语法参考](reference/arkui-js-lite/js-framework-syntax-css.md) @@ -1659,6 +1673,8 @@ - [元能力子系统错误码](reference/errorcodes/errorcode-ability.md) - [DistributedSchedule错误码](reference/errorcodes/errorcode-DistributedSchedule.md) - [卡片错误码](reference/errorcodes/errorcode-form.md) + - AI业务 + - [智能语音错误码](reference/errorcodes/errorcode-intelligentVoice.md) - 包管理 - [包管理子系统通用错误码](reference/errorcodes/errorcode-bundle.md) - [zlib子系统错误码](reference/errorcodes/errorcode-zlib.md) @@ -1670,6 +1686,7 @@ - [动画错误码](reference/errorcodes/errorcode-animator.md) - [弹窗错误码](reference/errorcodes/errorcode-promptAction.md) - [页面路由错误码](reference/errorcodes/errorcode-router.md) + - [用户界面外观服务错误码](reference/errorcodes/errorcode-uiappearance.md) - 图形图像 - [色彩管理错误码](reference/errorcodes/errorcode-colorspace-manager.md) - [屏幕错误码](reference/errorcodes/errorcode-display.md) @@ -1679,6 +1696,7 @@ - [Media错误码](reference/errorcodes/errorcode-media.md) - [媒体会话管理错误码](reference/errorcodes/errorcode-avsession.md) - [Camera错误码](reference/errorcodes/errorcode-camera.md) + - [Image错误码](reference/errorcodes/errorcode-image.md) - 资源管理 - [I18n错误码](reference/errorcodes/errorcode-i18n.md) - [资源管理错误码](reference/errorcodes/errorcode-resource-manager.md) 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/release-notes/changelogs/OpenHarmony_4.0.10.1/changelog-ArkUI.md b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.10.1/changelog-ArkUI.md index 0fdc45cc5433250d9478b120d76969595e1ca577..8b719f5b11039006225aa6f2fd1ab75be386e43d 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_4.0.10.1/changelog-ArkUI.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_4.0.10.1/changelog-ArkUI.md @@ -113,263 +113,3 @@ struct Page3 { } } ``` - -## cl.arkui.2 @StorageLink在页面跳转和页签场景行为优化 - -**变更影响** - -AppStorage是应用全局的UI状态存储,@StorageLink是对AppStorage中对应key的双向同步,即@StorageLink修饰的变量的改变会同步回AppStorage,AppStorage的修改也会同步给@StorageLink。 -当AppStorage某一个key发生改变时,会通知所有绑定该key的@StorageLink,@StorageLink装饰的变量的改变,会触发组件的重新渲染,包括不可见页面或者TabContent组件,这就造成了不必要的更新和性能浪费。 - -本次优化针对两个场景做出了优化: -1. 不可见页面的@StorageLink不会被通知刷新。 -2. 不可见TabContent的@StorageLink不会被通知刷新。 -AppStorage的属性改变,将不立即通知这两个场景下的@StorageLink更新和其@Watch回调,而是当页面或TabContent重新回到激活状态时,即可见状态,再去触发UI更新和其@Watch回调。 - -可见切换不可见状态或不可见切换可见状态流程如下: -1. 页面或TabContent内的自定义组件从可见到不可见,即标记组件为inActive。 -2. 当AppStorage的属性变化时,标记不可见节点的@StorageLink装饰的变量已经变化,但不通知UI刷新。 -3. 当页面或TabContent重新可见,即从inActive回到Active状态,将@StorageLink的dependentElementIds添加到其所属自定义组件的脏节点,调用其@Watch方法,刷新UI。 - -这次优化带来的最重要的应用行为变更是:不可见的页面和TabContent的@StorageLink的watch方法将不被回调。当其回到可见状态时,才会触发@Watch方法回调和UI更新。 - -**适配指导** - -不建议开发者通过借助@StorageLink和@Watch作为事件通知机制,因为@StorageLink是和UI强相关的装饰器,更新成本相较于一般的事件通知机制emit较高。 - -TapImage中的点击事件,会触发AppStorage中tapIndex对应属性的改变。因为@StorageLink是双向同步,修改会同步会AppStorage中,所以,所有绑定AppStorage的tapIndex可见自定义组件都会被通知UI刷新。UI刷新带来的成本是巨大的,因此不建议开发者使用此方式来实现基本的事件通知功能。 - -```ts -// xxx.ets -class ViewData { - title: string; - uri: Resource; - color: Color = Color.Black; - - constructor(title: string, uri: Resource) { - this.title = title; - this.uri = uri - } -} - -@Entry -@Component -struct Gallery2 { - dataList: Array = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))] - scroller: Scroller = new Scroller() - - build() { - Column() { - Grid(this.scroller) { - ForEach(this.dataList, (item: ViewData, index?: number) => { - GridItem() { - TapImage({ - uri: item.uri, - index: index - }) - }.aspectRatio(1) - - }, (item: ViewData, index?: number) => { - return JSON.stringify(item) + index; - }) - }.columnsTemplate('1fr 1fr') - } - - } -} - -@Component -export struct TapImage { - @StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1; - @State tapColor: Color = Color.Black; - private index: number; - private uri: Resource; - - // 判断是否被选中 - onTapIndexChange() { - if (this.tapIndex >= 0 && this.index === this.tapIndex) { - console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`) - this.tapColor = Color.Red; - } else { - console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`) - this.tapColor = Color.Black; - } - } - - build() { - Column() { - Image(this.uri) - .objectFit(ImageFit.Cover) - .onClick(() => { - this.tapIndex = this.index; - }) - .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor }) - } - - } -} -``` - -开发者可以使用emit订阅某个事件并接收事件回调,可以减少开销,增强代码的可读性。 - - -```ts -// xxx.ets -import emitter from '@ohos.events.emitter'; - -let NextID: number = 0; - -class ViewData { - title: string; - uri: Resource; - color: Color = Color.Black; - id: number; - - constructor(title: string, uri: Resource) { - this.title = title; - this.uri = uri - this.id = NextID++; - } -} - -@Entry -@Component -struct Gallery2 { - dataList: Array = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))] - scroller: Scroller = new Scroller() - private preIndex: number = -1 - - build() { - Column() { - Grid(this.scroller) { - ForEach(this.dataList, (item: ViewData) => { - GridItem() { - TapImage({ - uri: item.uri, - index: item.id - }) - }.aspectRatio(1) - .onClick(() => { - if (this.preIndex === item.id) { - return - } - var innerEvent = { eventId: item.id } - // 选中态:黑变红 - var eventData = { - data: { - "colorTag": 1 - } - } - emitter.emit(innerEvent, eventData) - - if (this.preIndex != -1) { - console.info(`preIndex: ${this.preIndex}, index: ${item.id}, black`) - var innerEvent = { eventId: this.preIndex } - // 取消选中态:红变黑 - var eventData = { - data: { - "colorTag": 0 - } - } - emitter.emit(innerEvent, eventData) - } - this.preIndex = item.id - }) - - }, (item: ViewData) => JSON.stringify(item)) - }.columnsTemplate('1fr 1fr') - } - - } -} - -@Component -export struct TapImage { - @State tapColor: Color = Color.Black; - private index: number; - private uri: Resource; - - onTapIndexChange(colorTag: emitter.EventData) { - this.tapColor = colorTag.data.colorTag ? Color.Red : Color.Black - } - - aboutToAppear() { - //定义事件ID - var innerEvent = { eventId: this.index } - emitter.on(innerEvent, this.onTapIndexChange.bind(this)) - } - - build() { - Column() { - Image(this.uri) - .objectFit(ImageFit.Cover) - .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor }) - } - } -} -``` - -以上通知事件逻辑简单,也可以简化成三元表达式。 - -``` -// xxx.ets -class ViewData { - title: string; - uri: Resource; - color: Color = Color.Black; - - constructor(title: string, uri: Resource) { - this.title = title; - this.uri = uri - } -} - -@Entry -@Component -struct Gallery2 { - dataList: Array = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))] - scroller: Scroller = new Scroller() - - build() { - Column() { - Grid(this.scroller) { - ForEach(this.dataList, (item: ViewData, index?: number) => { - GridItem() { - TapImage({ - uri: item.uri, - index: index - }) - }.aspectRatio(1) - - }, (item: ViewData, index?: number) => { - return JSON.stringify(item) + index; - }) - }.columnsTemplate('1fr 1fr') - } - - } -} - -@Component -export struct TapImage { - @StorageLink('tapIndex') tapIndex: number = -1; - @State tapColor: Color = Color.Black; - private index: number; - private uri: Resource; - - build() { - Column() { - Image(this.uri) - .objectFit(ImageFit.Cover) - .onClick(() => { - this.tapIndex = this.index; - }) - .border({ - width: 5, - style: BorderStyle.Dotted, - color: (this.tapIndex >= 0 && this.index === this.tapIndex) ? Color.Red : Color.Black - }) - } - } -} -```