diff --git a/CODEOWNERS b/CODEOWNERS index 23303c92c5a24ed1894449ea30b52c7de2685226..8110a344a6207d0b267e0bd7fd948fb22de01227 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -241,7 +241,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @feng-aiwen @ge zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-udmf.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-cloudData.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-data-relationStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 +zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 @@ -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/application-models/arkts-ui-widget-configuration.md b/en/application-dev/application-models/arkts-ui-widget-configuration.md index ea9832f92d32dfe0c2a4160f3ac6f8e904d323fa..b6caea5a511d16647103d84ef8e184b9f2b2077b 100644 --- a/en/application-dev/application-models/arkts-ui-widget-configuration.md +++ b/en/application-dev/application-models/arkts-ui-widget-configuration.md @@ -54,7 +54,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | 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)| | dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.
- **true**: The widget supports the update-through-proxy feature.
- **false**: The widget does not support the update-through-proxy feature.
If this tag is set to **true**, the settings for the scheduled update time will still take effect, but the settings for the update interval and next update time will not.| Boolean| Yes (initial value: **false**)| - | isDynamic | Whether the widget is a dynamic widget. This tag only applies to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)| + | isDynamic | Whether the widget is a dynamic widget. This tag applies only to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget.
**NOTE**
To reduce unnecessary memory resource overhead, widgets are classified as dynamic or static.
- Dynamic widgets support interaction events, such as **onClick**. They behave and respond differently based on the user's actions, such as tap and swipe.
- Static widgets do not support interaction events. They display static content that does not change and can only be redirected to a specified UIAbility through the [FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md) component.| Boolean| Yes (initial value: **true**)| **Table 2** Internal structure of the window object diff --git a/en/application-dev/application-models/arkts-ui-widget-creation.md b/en/application-dev/application-models/arkts-ui-widget-creation.md index bc571f93c5623a46a1290064d297003fe7e24c29..a99e4e7bf1f512aa6c5bdcb17fe8ef6d902970bb 100644 --- a/en/application-dev/application-models/arkts-ui-widget-creation.md +++ b/en/application-dev/application-models/arkts-ui-widget-creation.md @@ -1,8 +1,15 @@ # Creating an ArkTS Widget -To create an ArkTS widget in an existing application project, perform the following steps: +You can create a widget in either of the following modes: -1. Create a widget. +- When creating a project, select **Application**. The project created this way does not have a widget by default. You can right-click a module folder and choose **New** > **Service Widget** to create a widget. +- When creating a project, select **Atomic Service**. The project created this way has a widget by default. You can right-click a module folder and choose **New** > **Service Widget** to create a widget. + +![WidgetCreateProject](figures/WidgetCreateProject.png) + +To create an ArkTS widget in an existing project, perform the following steps: + +1. Right-click a module folder and choose **New** > **Service Widget**. ![WidgetProjectCreate1](figures/WidgetProjectCreate1.png) @@ -14,6 +21,6 @@ To create an ArkTS widget in an existing application project, perform the follow ![WidgetProjectCreate3](figures/WidgetProjectCreate3.png) -After an ArkTS widget is created, the following widget-related files are automatically added to the project directory: **EntryFormAbility.ts** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file). +After an ArkTS widget is created, the following widget-related files are automatically added to the project directory: **EntryFormAbility.ets** (widget lifecycle management file), **WidgetCard.ets** (widget page file), and **form_config.json** (widget configuration file). ![WidgetProjectView](figures/WidgetProjectView.png) \ No newline at end of file diff --git a/en/application-dev/application-models/arkts-ui-widget-event-call.md b/en/application-dev/application-models/arkts-ui-widget-event-call.md index 69189afb06c941158047462015519499961c9b95..0b947ced5de92636c907eb9bfe6d370dd5dca19d 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-call.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-call.md @@ -3,6 +3,9 @@ There may be cases you want to provide in a widget access to features available in your application running in the foreground, for example, the play, pause, and stop buttons in a music application widget. This is where the **call** capability of the **postCardAction** API comes in handy. This capability, when used in a widget, can start the specified UIAbility of the widget provider in the background. It also allows the widget to call the specified method of the application and transfer data so that the application, while in the background, can behave accordingly in response to touching of the buttons on the widget. +> **NOTE** +> +> This topic describes development for dynamic widgets. For static widgets, see [FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md). Typically, the call event is triggered for touching of buttons. Below is an example. @@ -48,7 +51,7 @@ Typically, the call event is triggered for touching of buttons. Below is an exam } ``` -- The UIAbility receives the call event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained in readString mode. Listen for the method required by the call event in the **onCreate** callback of the UIAbility. +- The UIAbility receives the call event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained through the **[readString](../reference/apis/js-apis-rpc.md#readstring)** method. Listen for the method required by the call event in the **onCreate** callback of the UIAbility. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -65,7 +68,7 @@ Typically, the call event is triggered for touching of buttons. Below is an exam } export default class CameraAbility extends UIAbility { - // If the UIAbility is started for the first time, onCreate is triggered afte the call event is received. + // If the UIAbility is started for the first time, onCreate is triggered after the call event is received. onCreate(want, launchParam) { try { // Listen for the method required by the call event. diff --git a/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md b/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md index be7761d8d78da5102afadd2c37043c228dfcd53e..2487b5c862922af39bc6721e99bb598ab5e10f03 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-formextensionability.md @@ -1,22 +1,32 @@ # Updating Widget Content Through the message Event +> **NOTE** +> +> This topic describes development for dynamic widgets. For static widgets, see [FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md). On the widget page, the **postCardAction** API can be used to trigger a message event to start a FormExtensionAbility, which then updates the widget content. The following is an example of this widget update mode. -- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the FormExtensionAbility. +- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the FormExtensionAbility. Use [LocalStorageProp](../quick-start/arkts-localstorage.md#localstorageprop) to decorate the widget data to be updated. ```ts let storage = new LocalStorage(); @Entry(storage) @Component struct WidgetCard { - @LocalStorageProp('title') title: string = 'init'; - @LocalStorageProp('detail') detail: string = 'init'; + @LocalStorageProp('title') title: string = 'Title default'; + @LocalStorageProp('detail') detail: string = 'Description default'; build() { Column() { - Button ('Update') + Column() { + Text(`${this.title}`) + .margin(5).fontWeight(FontWeight.Medium).fontSize('14fp') + Text(`${this.detail}`) + .margin(5).fontColor(Color.Gray).fontSize('12fp').height('25%') + }.width('100%').alignItems(HorizontalAlign.Start) + Button('UPDATE') + .margin(15).width('90%') .onClick(() => { postCardAction(this, { 'action': 'message', @@ -25,11 +35,7 @@ On the widget page, the **postCardAction** API can be used to trigger a message } }); }) - Text(`${this.title}`) - Text(`${this.detail}`) - } - .width('100%') - .height('100%') + }.width('90%').height('90%').margin('5%') } } ``` @@ -42,25 +48,24 @@ On the widget page, the **postCardAction** API can be used to trigger a message import formProvider from '@ohos.app.form.formProvider'; export default class EntryFormAbility extends FormExtensionAbility { - onFormEvent(formId, message) { + onFormEvent(formId: string, message: string) { // Called when a specified message event defined by the form provider is triggered. console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`); - let formData = { - 'title':'Title Update Success.', // Matches the widget layout. - 'detail':'Detail Update Success.', // Matches the widget layout. - }; + let formData = new Map(); + formData.set('title', 'Title Update.'); // It matches the widget layout. + formData.set('detail', 'Description update success.'); // It matches the widget layout. let formInfo = formBindingData.createFormBindingData(formData) formProvider.updateForm(formId, formInfo).then((data) => { console.info('FormAbility updateForm success.' + JSON.stringify(data)); - }).catch((error) => { - console.error('FormAbility updateForm failed: ' + JSON.stringify(error)); }) } - + ... } ``` The figure below shows the effect. - ![WidgetUpdatePage](figures/WidgetUpdatePage.png) + | Initial State | After Clicking | + | ------------------------------------------------------- | ----------------------------------------------------- | + | ![WidgetUpdateBefore](figures/widget-update-before.PNG) | ![WidgetUpdateAfter](figures/widget-update-after.PNG) | diff --git a/en/application-dev/application-models/arkts-ui-widget-event-overview.md b/en/application-dev/application-models/arkts-ui-widget-event-overview.md index 299a279c9117dad71e6fea658bb8da3298ed8f05..278aa84175c039eadd3b15a869c21a1e6477deab 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-overview.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-overview.md @@ -1,7 +1,10 @@ # Widget Event Capability Overview -The ArkTS widget provides the **postCardAction()** API for interaction between the widget internal and the widget provider. Currently, this API supports the router, message, and call events and can be called only in the widget. +For dynamic ATS widgets, the **postCardAction()** API is provided for interaction between the widget internal and the provider application. Currently, this API supports the router, message, and call events and can be called only in the widget. +For static ATS widgets, the [FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md) component is provided for interaction between the widget internal and the provider application. + +## Dynamic Widget Event Capability ![WidgetPostCardAction](figures/WidgetPostCardAction.png) **Definition**: postCardAction(component: Object, action: Object): void @@ -23,8 +26,11 @@ The ArkTS widget provides the **postCardAction()** API for interaction between t | "bundleName" | string | Name of the target bundle when **action** is **"router"** or **"call"**. This parameter is optional.| | "moduleName" | string | Name of the target module when **action** is **"router"** or **"call"**. This parameter is optional.| | "abilityName" | string | Name of the target UIAbility when **action** is **"router"** or **"call"**. This parameter is mandatory.| -| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. For the **"call"** action type, the **method** parameter (mandatory) must be set and its value type must be string.| +| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. This parameter is mandatory.| +>**NOTE** +> +>When **action** is **"router"** or **"call"**, **'method'** of the string type must be passed to **params** to trigger the corresponding method in the UIAbility. Sample code of the **postCardAction()** API: @@ -59,5 +65,5 @@ Button ('Start in Background') }) ``` - -Read on to learn the typical widget development scenarios that can be implemented through widget events. +## Static Widget Event Capability +See [FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md). diff --git a/en/application-dev/application-models/arkts-ui-widget-event-router.md b/en/application-dev/application-models/arkts-ui-widget-event-router.md index 733ff7f59b57ec4295fa21cb4d83ae8a5b2b8eb4..64e189764536340c3848f8545ea61cd8bbdfa84d 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-router.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-router.md @@ -4,8 +4,11 @@ The **router** capability of the **postCardAction** API can be used in a widget ![WidgerCameraCard](figures/WidgerCameraCard.png) +> **NOTE** +> +> This topic describes development for dynamic widgets. For static widgets, see [FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md). -Generally, a button is used to start a page. +Generally, a button is used to start a page. Below is an example: - Design two buttons on the widget page. When one of the buttons is clicked, **postCardAction** is called to send a router event to the specified UIAbility, with the content to be transferred defined in the event. @@ -57,7 +60,7 @@ Generally, a button is used to start a page. let selectPage = ""; let currentWindowStage = null; - export default class CameraAbility extends UIAbility { + export default class EntryAbility extends UIAbility { // If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the router event is received. onCreate(want, launchParam) { // Obtain the targetPage parameter passed in the router event. diff --git a/en/application-dev/application-models/arkts-ui-widget-event-uiability.md b/en/application-dev/application-models/arkts-ui-widget-event-uiability.md index 17a211188704609e5bc60dcbcf6b058a8a8a0dbe..310828490998a840fe6c88f0409f5e6ca7f47c2a 100644 --- a/en/application-dev/application-models/arkts-ui-widget-event-uiability.md +++ b/en/application-dev/application-models/arkts-ui-widget-event-uiability.md @@ -5,7 +5,11 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ## Updating Widget Content Through the router Event -- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the router event to the FormExtensionAbility. +> **NOTE** +> +> This topic describes development for dynamic widgets. For static widgets, see [FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md). + +- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the router event to start the UIAbility. ```ts let storage = new LocalStorage(); @@ -17,7 +21,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o build() { Column() { Button ('Redirect') - .margin('20%') + .margin(20) .onClick(() => { console.info('postCardAction to EntryAbility'); postCardAction(this, { @@ -28,7 +32,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o } }); }) - Text(`${this.detail}`).margin('20%') + Text(`${this.detail}`) } .width('100%') .height('100%') @@ -47,31 +51,21 @@ On the widget page, the **postCardAction** API can be used to trigger a router o export default class EntryAbility extends UIAbility { // If the UIAbility is started for the first time, onCreate is triggered after the router event is received. onCreate(want, launchParam) { - console.info('Want:' + JSON.stringify(want)); - if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) { - let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY]; - let message = JSON.parse(want.parameters.params).detail; - console.info(`UpdateForm formId: ${curFormId}, message: ${message}`); - let formData = { - "detail": message +': onCreate UIAbility.', // Matches the widget layout. - }; - let formMsg = formBindingData.createFormBindingData(formData) - formProvider.updateForm(curFormId, formMsg).then((data) => { - console.info('updateForm success.' + JSON.stringify(data)); - }).catch((error) => { - console.error('updateForm failed:' + JSON.stringify(error)); - }) - } + this.handleFormRouterEvent(want); } // If the UIAbility is running in the background, onNewWant is triggered after the router event is received. onNewWant(want, launchParam) { - console.info('onNewWant Want:' + JSON.stringify(want)); + this.handleFormRouterEvent(want); + } + + handleFormRouterEvent(want) { + console.info('Want:' + JSON.stringify(want)); if (want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) { let curFormId = want.parameters[formInfo.FormParam.IDENTITY_KEY]; let message = JSON.parse(want.parameters.params).detail; console.info(`UpdateForm formId: ${curFormId}, message: ${message}`); let formData = { - "detail": message +': onNewWant UIAbility.', // Matches the widget layout. + "detail": message + ': UIAbility.', // It matches the widget layout. }; let formMsg = formBindingData.createFormBindingData(formData) formProvider.updateForm(curFormId, formMsg).then((data) => { @@ -81,7 +75,6 @@ On the widget page, the **postCardAction** API can be used to trigger a router o }) } } - ... } ``` @@ -108,7 +101,7 @@ On the widget page, the **postCardAction** API can be used to trigger a router o }; ``` -- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the UIAbility. +- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to start the UIAbility. ```ts let storage = new LocalStorage(); diff --git a/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md b/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md index afd3cfa70b30ca5f5b6a0e4464958175f8e39cc1..56ff32a0981e46e337f73aa3726b53147ff0e4ae 100644 --- a/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md +++ b/en/application-dev/application-models/arkts-ui-widget-interaction-overview.md @@ -1,6 +1,6 @@ # Widget Data Interaction -The ArkTS widget framework provides the **updateForm()** and **requestForm()** APIs to proactively trigger widget updates. +The ArkTS widget framework provides the **updateForm()** and **requestForm()** APIs to proactively trigger widget updates. You can use [LocalStorageProp](../quick-start/arkts-localstorage.md#localstorageprop) to check the widget data to be updated. ![WidgetLocalStorageProp](figures/WidgetLocalStorageProp.png) diff --git a/en/application-dev/application-models/arkts-ui-widget-lifecycle.md b/en/application-dev/application-models/arkts-ui-widget-lifecycle.md index fb25fd362f67646d65853b870a6a9cb518c4d760..7818157e0d84866a52703a9615ffc8014fa61a14 100644 --- a/en/application-dev/application-models/arkts-ui-widget-lifecycle.md +++ b/en/application-dev/application-models/arkts-ui-widget-lifecycle.md @@ -4,7 +4,7 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) lifecycle APIs. -1. Import related modules to **EntryFormAbility.ts**. +1. Import related modules to **EntryFormAbility.ets**. ```ts import formInfo from '@ohos.app.form.formInfo'; @@ -13,7 +13,7 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( import formProvider from '@ohos.app.form.formProvider'; ``` -2. In **EntryFormAbility.ts**, implement the [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) lifecycle APIs, including **onAddForm**, whose **want** parameter can be used to obtain the widget information through [FormParam](../reference/apis/js-apis-app-form-formInfo.md#formparam). +2. In **EntryFormAbility.ets**, implement the [[FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) lifecycle APIs, including **onAddForm**, whose **want** parameter can be used to obtain the widget information through [FormParam](../reference/apis/js-apis-app-form-formInfo.md#formparam). ```typescript import formInfo from '@ohos.app.form.formInfo'; @@ -36,9 +36,8 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onCastToNormalForm(formId) { - // Called when the form provider is notified that a temporary form is successfully - // converted to a normal form. - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + // Called when the widget host converts the temporary widget into a normal one. + // The widget provider should do something to respond to the conversion. console.info(`[EntryFormAbility] onCastToNormalForm, formId: ${formId}`); } @@ -60,20 +59,20 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onChangeFormVisibility(newStatus) { - // Called when the form provider receives form events from the system. - // The callback is performed only when formVisibleNotify is set to true and the application is a system application. + // Called when the widget provider receives form events from the system. + // The callback is triggered only when formVisibleNotify is set to true and the application is a system application. console.info('[EntryFormAbility] onChangeFormVisibility'); } onFormEvent(formId, message) { - // Called when a specified message event defined by the form provider is triggered. + // Called when a specified message event defined by the widget provider is triggered. // If the widget supports event triggering, override this method and implement the trigger. console.info('[EntryFormAbility] onFormEvent'); } onRemoveForm(formId) { - // Called to notify the form provider that a specified form has been destroyed. - // Called when the corresponding widget is deleted. The input parameter is the ID of the deleted card. + // Called to notify the widget provider that a specified widget has been destroyed. + // The input parameter is the ID of the deleted card. console.info('[EntryFormAbility] onRemoveForm'); } @@ -83,8 +82,8 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } onAcquireFormState(want) { - // Called to return a {@link FormState} object. - // Called when the widget provider receives the status query result of a widget. By default, the initial state of the widget is returned. + // Called to return a FormState object upon a status query request + // from the widget. By default, the initial widget state is returned. return formInfo.FormState.READY; } } diff --git a/en/application-dev/application-models/arkts-ui-widget-modules.md b/en/application-dev/application-models/arkts-ui-widget-modules.md index b9a411426db84a4c1af12e70eab956adc8f25806..eb386c4d72cc3e8d36cd1bcd096786eaa685aa92 100644 --- a/en/application-dev/application-models/arkts-ui-widget-modules.md +++ b/en/application-dev/application-models/arkts-ui-widget-modules.md @@ -15,9 +15,9 @@ - [formBindingData](../reference/apis/js-apis-app-form-formBindingData.md): provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. -- [Page layout (Card.ets)](arkts-ui-widget-page-overview.md): provides APIs for a declarative paradigm UI. +- [Page layout (WidgetCard.ets)](arkts-ui-widget-page-overview.md): provides APIs for the declarative UI paradigm. - [Capabilities exclusive to ArkTS widgets](arkts-ui-widget-event-overview.md): include the **postCardAction** API used for interaction between the widget internal and the provider application and can be called only in the widget. - - [ArkTS widget capability list](arkts-ui-widget-page-overview.md#page-capabilities-supported-by-arkts-widgets): contain the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets. + - [ArkTS widget capability list](arkts-ui-widget-page-overview.md): contain the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets. - [Widget configuration](arkts-ui-widget-configuration.md): includes FormExtensionAbility configuration and widget configuration. - Configure the FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md index b7c1c93d21ec24673b3d07c4e971eadd7cd13661..5316b1ec93e2677c416c64cd6cd8c610d7aa5642 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-proxy.md @@ -13,6 +13,10 @@ Compared with the [implementation of the ArkTS widget](../application-models/ark - Data management service: provides a mechanism for data sharing among multiple applications. - Data provider: must be a system application that has data sharing enabled. The shared data is identified through the defined **key** + **subscriberId** combination. +> **NOTE** +> +> This feature can be used when the system provides applications as data providers and publicly available shared data identifiers. + Processing flow of the widget provider (indicated by the blue arrows in the figure): 1. The widget provider sets the **dataProxyEnabled** field to **true** in the **form_config.json** file to enable the update-through-proxy feature. @@ -29,7 +33,7 @@ Processing flow of the widget update proxy (indicated by the red arrows in the f 1. The data provider uses the **key** + **subscriberId** combination as the data ID to store data to the database. 2. The data management service detects the change in the database and publishes the new data to all currently registered subscription instances. 3. The Widget Manager parses data from the subscription instance and sends the data to the widget rendering service. -4. The widget rendering service runs the widget page code **widgets.abc**, renders based on the new data, and sends the rendered data to the widget component (../reference/arkui-ts/ts-basic-components-formcomponent.md) corresponding to the widget host. +4. The widget rendering service runs the widget page code **widgets.abc**, which implements rendering based on the new data and sends the rendered data to the [FormComponent](../reference/arkui-ts/ts-basic-components-formcomponent.md) corresponding to the widget host. There are two types of shared data provided by the data provider: diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-time.md b/en/application-dev/application-models/arkts-ui-widget-update-by-time.md index c3fcf45f3b95e88ca1a0f2bc13aefa94100873c0..d173d0210a2ecce63789a1a5f3de9584a0ec83d8 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-time.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-time.md @@ -1,7 +1,5 @@ # Configuring a Widget to Update Periodically -Before configuring a widget to update periodically, enable the periodic update feature by setting the **updateEnabled** field to **true** in the **form_config.json** file. - The widget framework provides the following modes of updating widgets periodically: @@ -9,6 +7,8 @@ The widget framework provides the following modes of updating widgets periodical > **NOTE** > + > Before configuring a widget to update periodically, enable the periodic update feature by setting the **updateEnabled** field to **true** in the **form_config.json** file. + > > **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used. ```json diff --git a/en/application-dev/application-models/arkts-ui-widget-working-principles.md b/en/application-dev/application-models/arkts-ui-widget-working-principles.md index a8599ca8827c2d41c3ff1be032151c1f6debead9..d9e1b26ddf40654feaa28b26439c401e1551ff64 100644 --- a/en/application-dev/application-models/arkts-ui-widget-working-principles.md +++ b/en/application-dev/application-models/arkts-ui-widget-working-principles.md @@ -13,13 +13,13 @@ - Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as the APIs for widget management, usage, and periodic updates. -- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host. +- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [FormComponent](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding [FormComponent](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host. **Figure 2** Working principles of the ArkTS widget rendering service ![WidgetRender](figures/WidgetRender.png) -Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. +Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same ArkTS virtual machine operating environment, and rendering instances of different widget providers run in different ArkTS virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-for-data-synchronization) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. ## Advantages of ArkTS Widgets diff --git a/en/application-dev/application-models/common-event-subscription.md b/en/application-dev/application-models/common-event-subscription.md index c3e3ebfa52415d5e0ebade26973f78a589fb348f..856b7fc44c624910ab1e8d2cb57f8b1f3a2c5d7d 100644 --- a/en/application-dev/application-models/common-event-subscription.md +++ b/en/application-dev/application-models/common-event-subscription.md @@ -12,7 +12,7 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common | API| Description| | -------- | -------- | -| createSubscriber(subscribeInfo: [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo), callback: AsyncCallback<[CommonEventData](../reference/apis/js-apis-commonEventManager.md#commoneventdata)>): void | Creates a subscriber. This API uses an asynchronous callback to return the result.| +| createSubscriber(subscribeInfo: [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo), callback: AsyncCallback<[CommonEventSubscriber](../reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md#usage)>): void | Creates a subscriber. This API uses an asynchronous callback to return the result.| | createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber> | Creates a subscriber. This API uses a promise to return the result.| | subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback): void | Subscribes to common events.| diff --git a/en/application-dev/application-models/figures/WidgetCreateProject.png b/en/application-dev/application-models/figures/WidgetCreateProject.png new file mode 100644 index 0000000000000000000000000000000000000000..2372e68a25c116ace77374eba86a8ea7a0680988 Binary files /dev/null and b/en/application-dev/application-models/figures/WidgetCreateProject.png differ diff --git a/en/application-dev/application-models/figures/WidgetModules.png b/en/application-dev/application-models/figures/WidgetModules.png index 6eaac0b6ca404eb9575587add72935e9ce580030..1612c2fa34fe9aea0563fa58fc7af378539ba81a 100644 Binary files a/en/application-dev/application-models/figures/WidgetModules.png and b/en/application-dev/application-models/figures/WidgetModules.png differ diff --git a/en/application-dev/application-models/figures/WidgetPrinciple.png b/en/application-dev/application-models/figures/WidgetPrinciple.png index 68ca315394fe2cb5bd2580ca6df38b9940ac1349..3f8d147f07aaa85e1a21859bf58ab4d8bd891de2 100644 Binary files a/en/application-dev/application-models/figures/WidgetPrinciple.png and b/en/application-dev/application-models/figures/WidgetPrinciple.png differ diff --git a/en/application-dev/application-models/figures/WidgetProjectView.png b/en/application-dev/application-models/figures/WidgetProjectView.png index 9d1c06e47502131983b0b7cd56e66269b5be6d88..a1c8b42becc089b6b69f58c362569faeaf84f06f 100644 Binary files a/en/application-dev/application-models/figures/WidgetProjectView.png and b/en/application-dev/application-models/figures/WidgetProjectView.png differ diff --git a/en/application-dev/application-models/figures/WidgetRender.png b/en/application-dev/application-models/figures/WidgetRender.png index 0f46bd74b0e48ac0c9f947d96d5e147786f547c0..1fec0d982b45718a7dbc9d19e679e6806f1c84cc 100644 Binary files a/en/application-dev/application-models/figures/WidgetRender.png and b/en/application-dev/application-models/figures/WidgetRender.png differ diff --git a/en/application-dev/application-models/figures/WidgetUpdatePage.png b/en/application-dev/application-models/figures/WidgetUpdatePage.png deleted file mode 100644 index 075c8e97c85386c062a651f3b4f876e6c049171f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/WidgetUpdatePage.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/widget-update-after.PNG b/en/application-dev/application-models/figures/widget-update-after.PNG new file mode 100644 index 0000000000000000000000000000000000000000..fddb9f651685332324af9a4d065c29638a58c0ba Binary files /dev/null and b/en/application-dev/application-models/figures/widget-update-after.PNG differ diff --git a/en/application-dev/application-models/figures/widget-update-before.PNG b/en/application-dev/application-models/figures/widget-update-before.PNG new file mode 100644 index 0000000000000000000000000000000000000000..6355f1b66707af8073a2e1dea7f05e839f3a9818 Binary files /dev/null and b/en/application-dev/application-models/figures/widget-update-before.PNG differ diff --git a/en/application-dev/application-models/js-ui-widget-development.md b/en/application-dev/application-models/js-ui-widget-development.md index 178aa903a36b6a4742645cfab82a390364db0b37..9e1cd4d472afc4dcbf830b901b935fde0667e9b4 100644 --- a/en/application-dev/application-models/js-ui-widget-development.md +++ b/en/application-dev/application-models/js-ui-widget-development.md @@ -56,7 +56,7 @@ The **FormExtensionAbility** class has the following APIs. For details, see [For | onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to process a widget event.| | onRemoveForm(formId: string): void | Called to notify the widget provider that a widget is being destroyed.| | onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is being updated.| -| onShareForm?(formId: string): { [key: string]: any } | Called to notify the widget provider that the widget host is sharing the widget data.| +| onShareForm?(formId: string): { [key: string]: Object } | Called to notify the widget provider that the widget host is sharing the widget data.| The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). @@ -95,7 +95,7 @@ The widget provider development based on the [stage model](stage-model-developme To create a widget in the stage model, you need to implement the lifecycle callbacks of FormExtensionAbility. Generate a widget template and then perform the following: -1. Import related modules to **EntryFormAbility.ts**. +1. Import related modules to **EntryFormAbility.ets**. ```ts @@ -106,7 +106,7 @@ To create a widget in the stage model, you need to implement the lifecycle callb import dataPreferences from '@ohos.data.preferences'; ``` -2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. +2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ets**. ```ts @@ -176,7 +176,7 @@ To create a widget in the stage model, you need to implement the lifecycle callb "extensionAbilities": [ { "name": "EntryFormAbility", - "srcEntry": "./ets/entryformability/EntryFormAbility.ts", + "srcEntry": "./ets/entryformability/EntryFormAbility.ets", "label": "$string:EntryFormAbility_label", "description": "$string:EntryFormAbility_desc", "type": "form", @@ -547,6 +547,29 @@ The following are examples: } ``` + Note: + + **JSON Value** in **data** supports multi-level nested data. When updating data, ensure that complete data is carried. + + Assume that a widget is displaying the course information of Mr. Zhang on July 18, as shown in the following code snippet. + ```ts + "data": { + "Day": "07.18", + "teacher": { + "name": "Mr.Zhang", + "course": "Math" + } + } + ``` + To update the widget content to the course information of Mr. Li on July 18, you must pass the complete data as follows, instead of only a single date item such as **name** or **course**: + ```ts + "teacher": { + "name": "Mr.Li", + "course": "English" + } + ``` + + - Receive the router event in UIAbility and obtain parameters. diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 1bb784cf96fb1d74dcbafed54498435f505814b6..a0fa4102864ba2403e7a6826f3ca3b872b5a80dd 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -1,6 +1,6 @@ # HTTP Data Request -## When to Use +## Overview An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. @@ -18,7 +18,7 @@ The following table provides only a simple description of the related APIs. For | ----------------------------------------- | ----------------------------------- | | createHttp() | Creates an HTTP request. | | request() | Initiates an HTTP request to a given URL. | -| request2()10+ | Initiates an HTTP network request based on the URL and returns a streaming response.| +| requestInStream()10+ | Initiates an HTTP network request to a given URL and returns a streaming response.| | destroy() | Destroys an HTTP request. | | on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. | | off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.| @@ -27,8 +27,8 @@ The following table provides only a simple description of the related APIs. For | off\('dataReceive'\)10+ | Unregisters the observer for events indicating receiving of HTTP streaming responses. | | on\('dataEnd'\)10+ | Registers an observer for events indicating completion of receiving HTTP streaming responses. | | off\('dataEnd'\)10+ | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.| -| on\('dataProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. | -| off\('dataProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| +| on\('dataReceiveProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. | +| off\('dataReceiveProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| ## How to Develop request APIs @@ -53,6 +53,7 @@ httpRequest.on('headersReceive', (header) => { }); httpRequest.request( // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. + "EXAMPLE_URL", { method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. // You can add header fields based on service requirements. @@ -81,7 +82,7 @@ httpRequest.request( // Call the destroy() method to release resources after HttpRequest is complete. httpRequest.destroy(); } else { - console.info('error:' + JSON.stringify(err)); + console.error('error:' + JSON.stringify(err)); // Unsubscribe from HTTP Response Header events. httpRequest.off('headersReceive'); // Call the destroy() method to release resources after HttpRequest is complete. @@ -91,12 +92,12 @@ httpRequest.request( ); ``` -## How to Develop request2 APIs +## How to Develop requestInStream APIs 1. Import the **http** namespace from **@ohos.net.http.d.ts**. 2. Call **createHttp()** to create an **HttpRequest** object. 3. Depending on your need, call **on()** of the **HttpRequest** object to subscribe to HTTP response header events as well as events indicating receiving of HTTP streaming responses, progress of receiving HTTP streaming responses, and completion of receiving HTTP streaming responses. -4. Call **request2()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. +4. Call **requestInStream()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. 5. Parse the returned response code as needed. 6. Call **off()** of the **HttpRequest** object to unsubscribe from the related events. 7. Call **httpRequest.destroy()** to release resources after the request is processed. @@ -122,11 +123,11 @@ httpRequest.on('dataEnd', () => { console.info('No more data in response, data receive end'); }); // Subscribe to events indicating progress of receiving HTTP streaming responses. -httpRequest.on('dataProgress', (data) => { - console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize); +httpRequest.on('dataReceiveProgress', (data) => { + console.log("dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize); }); -httpRequest.request2( +httpRequest.requestInStream( // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. "EXAMPLE_URL", { @@ -146,14 +147,14 @@ httpRequest.request2( readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission. usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. }, (err, data) => { - console.info('error:' + JSON.stringify(err)); + console.error('error:' + JSON.stringify(err)); console.info('ResponseCode :' + JSON.stringify(data)); // Unsubscribe from HTTP Response Header events. httpRequest.off('headersReceive'); // Unregister the observer for events indicating receiving of HTTP streaming responses. httpRequest.off('dataReceive'); // Unregister the observer for events indicating progress of receiving HTTP streaming responses. - httpRequest.off('dataProgress'); + httpRequest.off('dataReceiveProgress'); // Unregister the observer for events indicating completion of receiving HTTP streaming responses. httpRequest.off('dataEnd'); // Call the destroy() method to release resources after HttpRequest is complete. @@ -161,10 +162,3 @@ httpRequest.request2( } ); ``` - -## Samples - -The following sample is provided to help you better understand how to develop the HTTP data request feature: - -- [`Http`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) -- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index b9bbb0608dfb83ba6d2198b063e68c4b324bbd88..14016ef5da297361bd4a17a3d278357060590784 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -1,6 +1,6 @@ # IPC & RPC Development Guidelines -## When to Use +## Overview IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices. diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md index fba108e73cd8e5e3dd81a43880cf25a54aee6ee5..f3b945ab0970786000ab8b04adfe90592a11e0d1 100644 --- a/en/application-dev/connectivity/net-connection-manager.md +++ b/en/application-dev/connectivity/net-connection-manager.md @@ -1,10 +1,11 @@ # Network Connection Management -## Introduction +## Overview The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. > **NOTE** +> > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md). ## Basic Concepts diff --git a/en/application-dev/connectivity/net-ethernet.md b/en/application-dev/connectivity/net-ethernet.md index 18f20a7fd7e1a4c9516386c543c9521522df5f66..76ae1ee28078520b9d70796f71fd2b9236f47959 100644 --- a/en/application-dev/connectivity/net-ethernet.md +++ b/en/application-dev/connectivity/net-ethernet.md @@ -1,10 +1,11 @@ # Ethernet Connection -## Introduction +## Overview The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode. > **NOTE** +> > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md). ## **Constraints** diff --git a/en/application-dev/connectivity/net-mdns.md b/en/application-dev/connectivity/net-mdns.md index de7982a5c03908a70e4005bdc5fbea3584c435f5..75da959da8c4b1fc55aa0afca1cf0dcd945b86bb 100644 --- a/en/application-dev/connectivity/net-mdns.md +++ b/en/application-dev/connectivity/net-mdns.md @@ -1,6 +1,6 @@ # MDNS Management -## Introduction +## Overview Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN. - Local service: a service provider on a LAN, for example, a printer or scanner. diff --git a/en/application-dev/connectivity/net-sharing.md b/en/application-dev/connectivity/net-sharing.md index 4072217d9ced5d99b2052b5db8ccb8333fcb7023..f2b2e6ac21362691ede111db8b16316fa9fd32cb 100644 --- a/en/application-dev/connectivity/net-sharing.md +++ b/en/application-dev/connectivity/net-sharing.md @@ -1,10 +1,11 @@ # Network Sharing -## Introduction +## Overview The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. > **NOTE** +> > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md). ## Basic Concepts diff --git a/en/application-dev/connectivity/net-statistics.md b/en/application-dev/connectivity/net-statistics.md index 47ec62ff156448b3214885176c30b2f76d77b76c..6df8800dd479b48c32619514b8e6b90d5c776330 100644 --- a/en/application-dev/connectivity/net-statistics.md +++ b/en/application-dev/connectivity/net-statistics.md @@ -1,6 +1,6 @@ # Traffic Management -## Introduction +## Overview The traffic management module allows you to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID). @@ -11,6 +11,7 @@ Its functions include: - Subscribing to traffic change events by NIC or UID > **NOTE** +> > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-statistics.md). The following describes the development procedure specific to each application scenario. diff --git a/en/application-dev/connectivity/net-vpn.md b/en/application-dev/connectivity/net-vpn.md index adf38f9676f29937532579e0bbdb4a94467095f3..a93b00b932bdec33de7cb45764474c163ed456ce 100644 --- a/en/application-dev/connectivity/net-vpn.md +++ b/en/application-dev/connectivity/net-vpn.md @@ -5,6 +5,7 @@ A virtual private network (VPN) is a dedicated network established on a public network. On a VPN, the connection between any two nodes does not have an end-to-end physical link required by the traditional private network. Instead, user data is transmitted over a logical link because a VPN is a logical network deployed over the network platform (such as the Internet) provided by the public network service provider. > **NOTE** +> > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-vpn.md). The following describes the development procedure specific to each application scenario. diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 9dda8b4e4c0ac6931ea75ad706fef76c9fb3c0a3..fe8ab1f141e3525de46985ba113eee364adac723 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -1,6 +1,6 @@ # Socket Connection -## Introduction +## Overview The Socket Connection module allows an application to transmit data over a socket connection through the TCP, UDP, or TLS protocol. diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md index 5b21750ba8b56fefcb10a5fff653d7512765c279..d23385e44752cb0945217eddc74117202ca38c5f 100755 --- a/en/application-dev/connectivity/subscribe-remote-state.md +++ b/en/application-dev/connectivity/subscribe-remote-state.md @@ -1,5 +1,7 @@ # Subscribing to State Changes of a Remote Object +## Overview + IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered. ## When to Use diff --git a/en/application-dev/connectivity/websocket-connection.md b/en/application-dev/connectivity/websocket-connection.md index 4c373011c45be18183e4c622c3e7e35b97198a24..1b162256db5cad28aa50ca6989625f9191fb2257 100644 --- a/en/application-dev/connectivity/websocket-connection.md +++ b/en/application-dev/connectivity/websocket-connection.md @@ -1,6 +1,6 @@ # WebSocket Connection -## When to Use +## Overview You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event. diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index 5a1b6326bae1ecb94ef7fe8d9e4cfe2cdf2c6c56..c40f752d8f85e8894eb725965f50a7614dddef36 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -1,7 +1,6 @@ # DFX - [Development of Application Event Logging](hiappevent-guidelines.md) -- [Development of Performance Tracing](hitracemeter-guidelines.md) - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) - [HiLog Development (Native)](hilog-guidelines.md) - Performance Tracing diff --git a/en/application-dev/dfx/appfreeze-guidelines.md b/en/application-dev/dfx/appfreeze-guidelines.md index 05b52c4d8070386ec350701cefb2c6b63ef67d55..4984c95e215fe832f59abc3306bf777c6c313818 100644 --- a/en/application-dev/dfx/appfreeze-guidelines.md +++ b/en/application-dev/dfx/appfreeze-guidelines.md @@ -1,6 +1,6 @@ # Application Freeze (appfreeze) Log Analysis -## Introduction +## Overview Application freeze (appfreeze) means that an application does not respond to user operations (for example, clicking) within a given period of time. OpenHarmony provides a mechanism for detecting appfreeze faults and generates appfreeze logs for fault analysis. diff --git a/en/application-dev/dfx/apprecovery-guidelines.md b/en/application-dev/dfx/apprecovery-guidelines.md index 284de5ca6d5f6027f2cce975a29b3259b2778021..a4792d42771584ac424935790e60e5592745f8ab 100644 --- a/en/application-dev/dfx/apprecovery-guidelines.md +++ b/en/application-dev/dfx/apprecovery-guidelines.md @@ -1,6 +1,6 @@ # Application Recovery Development -## When to Use +## Overview During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the recovery framework are violated. @@ -99,9 +99,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant' - Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback. For details about its usage, see [errorManager](../reference/apis/js-apis-app-ability-errorManager.md). ```ts - var registerId = -1; - var callback = { - onUnhandledException(errMsg) { +import * as GlobalWant from "../file1" +export let abilityWant : Want // file1 + + let registerId = -1; + let callback: Callback = { + onUnhandledException(errMsg: string): void { console.log(errMsg); appRecovery.saveAppState(); appRecovery.restartApp(); @@ -112,7 +115,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant' // Main window is created, set main page for this ability console.log("[Demo] MainAbility onWindowStageCreate") - globalThis.registerObserver = (() => { + G.registerObserver = (() => { registerId = errorManager.on('error', callback); }) @@ -138,13 +141,15 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **MainAbility** is called, and the saved data is in **parameters** of **want**. ```ts -storage: LocalStorage +import * as GlobalWant from "../file1" +export let abilityWant : Want // file1 + onCreate(want, launchParam) { console.log("[Demo] MainAbility onCreate") - globalThis.abilityWant = want; + GlobalWant.abilityWant = want; if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { this.storage = new LocalStorage(); - let recoveryData = want.parameters["myData"]; + let recoveryData: string = want.parameters["myData"]; this.storage.setOrCreate("myData", recoveryData); this.context.restoreWindowStage(this.storage); } @@ -154,12 +159,15 @@ onCreate(want, launchParam) { - Unregister the **ErrorObserver** callback. ```ts +import * as GlobalWant from "../file1" +export let abilityWant : Want // file1 + onWindowStageDestroy() { // Main window is destroyed, release UI related resources console.log("[Demo] MainAbility onWindowStageDestroy") - globalThis.unRegisterObserver = (() => { - errorManager.off('error', registerId, (err) => { + G.unRegisterObserver = (() => { + errorManager.off(type: 'error', registerId: number, (err:Error) => { console.error("[Demo] err:", err); }); }) @@ -171,24 +179,25 @@ onWindowStageDestroy() { This is triggered by the recovery framework. You do not need to register an **ErrorObserver** callback. You only need to implement **onSaveState** for application state saving and **onCreate** for data restore. ```ts -export default class MainAbility extends Ability { - storage: LocalStorage - onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") - globalThis.abilityWant = want; - if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { - this.storage = new LocalStorage(); - let recoveryData = want.parameters["myData"]; - this.storage.setOrCreate("myData", recoveryData); - this.context.restoreWindowStage(this.storage); - } - } +import * as GlobalWant from "../file1" +export let abilityWant : Want // file1 - onSaveState(state, wantParams) { - // Ability has called to save app data - console.log("[Demo] MainAbility onSaveState") - wantParams["myData"] = "my1234567"; - return AbilityConstant.OnSaveResult.ALL_AGREE; +export default class MainAbility extends Ability { + onCreate(want: Want, launchParam:AbilityConstant.LaunchParam):void { + console.log("[Demo] MainAbility onCreate") + GlobalWant.abilityWant = want; + if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { + this.storage = new LocalStorage(); + let recoveryData: string = want.parameters["myData"]; + this.storage.setOrCreate("myData", recoveryData); + this.context.restoreWindowStage(this.storage); } + } + onSaveState(reason: AbilityConstant.StateType, wantParam: Record): AbilityConstant.OnSaveResult { + // Ability has called to save app data + console.log("[Demo] MainAbility onSaveState") + wantParam["myData"] = "my1234567"; + return AbilityConstant.OnSaveResult.ALL_AGREE; + } } ``` diff --git a/en/application-dev/dfx/cppcrash-guidelines.md b/en/application-dev/dfx/cppcrash-guidelines.md index c3ca07a4dc3a069272d89986329c2cbe103a45cb..15136518788324e23ac46c8c8b5bba327c03ea7a 100644 --- a/en/application-dev/dfx/cppcrash-guidelines.md +++ b/en/application-dev/dfx/cppcrash-guidelines.md @@ -1,6 +1,6 @@ # Process Crash (cppcrash) Log Analysis -## Introduction +## Overview A process crash refers to a C/C++ runtime crash. The FaultLogger module of OpenHarmony provides capabilities such as process crash detection, log collection, log storage, and log reporting, helping you to locate faults more effectively. diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md index 4679cfcfc78893590fe73eab770e49fc68a1a828..14d7735d731d0fb2eb3fc41f61de58f5de7f4e02 100644 --- a/en/application-dev/dfx/errormanager-guidelines.md +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -1,6 +1,6 @@ # Development of Error Manager -## When to Use +## Overview If coding specification issues or errors exist in the code of an application, the application may encounter unexpected errors, for example, uncaught exceptions or application lifecycle timeouts, while it is running. In such a case, the application may exit unexpectedly. Error logs, however, are usually stored on users' local storage, making it inconvenient to locate faults. With the APIs provided by the **errorManager** module, your application will be able to report related errors and logs to your service platform for fault locating before it exits. diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index d21d4e3fa9e0fa0b795c82e7157cd6215eab5e0c..6b0f4dd1cb8ec36288514e3f8767770f4e30105b 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -1,6 +1,6 @@ # Development of Application Event Logging -## Introduction +## Overview A traditional log system aggregates log information generated by all applications running on the entire device, making it difficult to identify key information in the log. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage. diff --git a/en/application-dev/dfx/hilog-guidelines.md b/en/application-dev/dfx/hilog-guidelines.md index 25b4a7f9cc5c92d9f20ed6582299d5dd65b937d0..45d46c01fb4c601241120ce9cf5d249bd0bc893f 100644 --- a/en/application-dev/dfx/hilog-guidelines.md +++ b/en/application-dev/dfx/hilog-guidelines.md @@ -1,6 +1,6 @@ # HiLog Development (Native) -## Introduction +## Overview HiLog is the log system of OpenHarmony that provides logging for the system framework, services, and applications to record information on user operations and system running status. diff --git a/en/application-dev/dfx/hitracechain-guidelines.md b/en/application-dev/dfx/hitracechain-guidelines.md index affd260b0503f3c4f4c4b748d5911d94f7fef9e3..44e2da92dfbf985f27a275ac6e02e61a934d199e 100644 --- a/en/application-dev/dfx/hitracechain-guidelines.md +++ b/en/application-dev/dfx/hitracechain-guidelines.md @@ -1,6 +1,6 @@ # Development of Distributed Call Chain Tracing -## Introduction +## Overview The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md index ed99e4e89d5b6fce3d5bd50ef8dedcfc32b04fb1..195aae4b2d98dd1ab950613c6c97ed07cfcfe98e 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-guidelines.md @@ -1,6 +1,6 @@ # Development of Performance Tracing (ArkTS) -## Introduction +## Overview hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance. @@ -21,7 +21,7 @@ hiTraceMeter provides APIs for system performance tracing. You can call the APIs ## Available APIs -The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md). +The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md). **APIs for performance tracing** @@ -35,60 +35,16 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed. -1. Create a JS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **js** > **default** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. The sample code is as follows: - - ```js - import hiTraceMeter from '@ohos.hiTraceMeter' - - export default { - data: { - title: "" - }, - onInit() { - this.title = this.$t('strings.world'); - - // Start trace tasks with the same name concurrently. - hiTraceMeter.startTrace("business", 1); - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.startTrace("business", 2); // Start the second trace task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different. - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.finishTrace("business", 1); - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.finishTrace("business", 2); - - // Start trace tasks with the same name in serial mode. - hiTraceMeter.startTrace("business", 1); - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.finishTrace("business", 1); // End the first trace task. - // Keep the service process running. - console.log(`business running`); - hiTraceMeter.startTrace("business", 1); // Start the second trace task with the same name in serial mode. - // Keep the service process running. - console.log(`business running`); - - let traceCount = 3; - hiTraceMeter.traceByValue("myTestCount", traceCount); - traceCount = 4; - hiTraceMeter.traceByValue("myTestCount", traceCount); - hiTraceMeter.finishTrace("business", 1); - } - } - ``` - -2. Create an ArkTs application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows: - +1. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows: + ```ts import hitrace from '@ohos.hiTraceMeter'; - + @Entry @Component struct Index { @State message: string = 'Hello World'; - + build() { Row() { Column() { @@ -97,7 +53,7 @@ In this example, distributed call chain tracing begins when the application star .fontWeight(FontWeight.Bold) .onClick(() => { this.message = 'Hello ArkUI'; - + // Start trace tasks with the same name concurrently. hitrace.startTrace("HITRACE_TAG_APP", 1001); // Keep the service process running. @@ -107,7 +63,7 @@ In this example, distributed call chain tracing begins when the application star hitrace.startTrace("HITRACE_TAG_APP", 1002); // Keep the service process running. console.log(`HITRACE_TAG_APP running`); - + hitrace.finishTrace("HITRACE_TAG_APP", 1001); hitrace.finishTrace("HITRACE_TAG_APP", 1002); @@ -143,7 +99,7 @@ In this example, distributed call chain tracing begins when the application star ``` 3. Click the run button on the application page. Then, run the following commands in sequence in shell: - + ```shell hdc shell hitrace --trace_begin app diff --git a/en/application-dev/dfx/hitracemeter-native-guidelines.md b/en/application-dev/dfx/hitracemeter-native-guidelines.md index bb0274f7c4077b016061430250e7a949cf826864..912ec1c5f87b6ebfdd6f14cb4da568e251501af2 100644 --- a/en/application-dev/dfx/hitracemeter-native-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-native-guidelines.md @@ -1,6 +1,6 @@ # Development of Performance Tracing (Native) -## Introduction +## Overview hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance. > **NOTE** diff --git a/en/application-dev/faqs/faqs-graphics.md b/en/application-dev/faqs/faqs-graphics.md index 345cbf83c5b2976c810e78237cb2587eaa4b1404..4cc8b196d5b8210e2360a598c1b24fdc0edb891b 100644 --- a/en/application-dev/faqs/faqs-graphics.md +++ b/en/application-dev/faqs/faqs-graphics.md @@ -21,42 +21,6 @@ try { } ``` -## How do I hide the status bar to get the immersive effect? - -Applicable to: OpenHarmony 3.2 Beta5 (API version 9) - -**Solution** - -1. Use **onWindowStageCreate** to obtain a **windowClass** object. - - ``` - onWindowStageCreate(windowStage) { - // When the main window is created, set the main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window.') - return; - } - // Obtain a windowClass object. - globalThis.windowClass = data; - }) - } - ``` - -2. Enable the full-screen mode for the window and hide the status bar. - - ``` - globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); - }); - ``` - - ## How do I obtain the window width and height? Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model) diff --git a/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md index b5a7f381053593a806b40d2214a5bb4777a1b83d..839f57643b2df5bcea03a39920e4a227fdba30f9 100644 --- a/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-notify-guidelines.md @@ -33,20 +33,21 @@ Example: Listener for changes of an image. When the image is favorited, the list ```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:photoAccessHelper.ChangeData) => { console.info('onCallback successfully, changData: ' + JSON.stringify(changeData)); } phAccessHelper.registerChange(fileAsset.uri, false, onCallback); @@ -77,21 +78,22 @@ Example: Listener for a user album. When the album is renamed, the listener call ```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); @@ -133,21 +135,22 @@ Example: Register a listener for all file assets. When an observed file asset is ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; -let onCallback = (changeData) => { +let onCallback = (changeData: photoAccessHelper.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(); @@ -175,23 +178,24 @@ Example: Unregister listening for an image. After that, the unregistered listene ```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/en/application-dev/file-management/photoAccessHelper-overview.md b/en/application-dev/file-management/photoAccessHelper-overview.md index 8c66669b4e5992b1a23dd60e9c5f3ae4fe5fc5f0..719da5ea9e1851316038dc0e92095154e715c7e6 100644 --- a/en/application-dev/file-management/photoAccessHelper-overview.md +++ b/en/application-dev/file-management/photoAccessHelper-overview.md @@ -49,7 +49,7 @@ import photoAccessHelper from '@ohos.file.photoAccessHelper'; // The phAccessHelper instance obtained here is a global object. By default, the object obtained here is used in subsequent operations in this document. If an undefined error is reported, add the code snippet here. const context = getContext(this); -let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); +let phAccessHelper: photoAccessHelper.PhotoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); ``` ## Applying for Permissions @@ -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 a0557bcb2c264b2e1a641e489d2f62bf50deaf54..1d9a2406ea9416ec02e52dcb9f699807546ed72f 100644 --- a/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-resource-guidelines.md @@ -33,10 +33,11 @@ Example: Obtain the image **test.jpg**. ```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 = { 2. Call **PhotoAccessHelper.getAssets** to obtain image assets. ```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 @@ Example: Obtain the image with the file URI **file://media/Photo/1**. ```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 = { Call **PhotoAccessHelper.getAssets** to obtain image assets. ```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,14 +96,15 @@ Example: Obtain the media assets added between 2022-06-01 and 2023-06-01. ```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; // 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 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); // Sort the obtained records in descending order. -let fetchOptions = { +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 = { Call **PhotoAccessHelper.getAssets** to obtain image assets. ```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 @@ 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 = 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 @@ Example: Create an image asset. 2. Call **createAsset** to create an image asset. ```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 @@ Example: Rename the first file in the obtained image assets. ```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 @@ Example: Move the first file in the result set to the trash. ```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/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md index e42d7bab28aa84d141bcc4fe385618bfd16114ca..b6b7b75d098724db75545a560bdda061096e04af 100644 --- a/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-systemAlbum-guidelines.md @@ -29,9 +29,11 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt 2. Call **getAlbums** to obtain a **Favorites** object. ```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 @@ Example: Favorite an image. ```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 @@ Example: Obtain an image from **Favorites**. ```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 @@ Example: Unfavorite an image. ```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 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt 2. Use **getAlbums** to obtain the video album object. ```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 @@ Example: Obtain a video in **Videos**. ```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 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt 2. Use **getAlbums** to obtain a screenshot album object. ```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 @@ Example: Obtain a media asset from **Screenshots**. ```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/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md index 87d0fa3517e1ca3fcc6e4e494b5e0bcff229b80a..35891ad5f8562ca6c5f87a966e813f5e310c5c79 100644 --- a/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md +++ b/en/application-dev/file-management/photoAccessHelper-userAlbum-guidelines.md @@ -34,9 +34,11 @@ Example: Create a user album. 2. Use **createAlbum** to create an album. ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + try { let albumName = 'albumName'; - let album = await phAccessHelper.createAlbum(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 @@ Example: Obtain the user album named **albumName**. ```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.ALBUM_NAME = 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) { @@ -106,18 +109,19 @@ Example: Rename an album named **albumName**. ```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.ALBUM_NAME = 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(); @@ -150,27 +154,28 @@ Example: Add an image to the album **albumName**. ```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..AlbumKeys.ALBUM_NAME = 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(); + 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(); @@ -202,27 +207,28 @@ Example: Obtain an image in the user album **albumName**. ```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.AlbumKeys = 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(); + 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(); @@ -256,27 +262,28 @@ Example: Remove an image from the album named **albumName**. ```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.AlbumKeys.ALBUM_NAME = 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(); + 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(); @@ -306,18 +313,19 @@ Example: Delete a user album named **albumName**. ```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..ALBUM_NAME = 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/en/application-dev/media/using-avrecorder-for-recording.md b/en/application-dev/media/using-avrecorder-for-recording.md index 71ab8557df470671088adfaa0473a6448d935881..aa204062795339cf425cb95d9726001f56b66d9a 100644 --- a/en/application-dev/media/using-avrecorder-for-recording.md +++ b/en/application-dev/media/using-avrecorder-for-recording.md @@ -20,11 +20,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts import media from '@ohos.multimedia.media'; - let avRecorder = undefined; - media.createAVRecorder().then((recorder) => { + let avRecorder: media.AVRecorder; + media.createAVRecorder().then((recorder: media.AVRecorder) => { avRecorder = recorder; - }, (err) => { - console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`); + }, (error: Error) => { + console.error(`createAVRecorder failed`); }) ``` @@ -37,13 +37,13 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts // Callback function for state changes. - avRecorder.on('stateChange', (state, reason) => { + avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`current state is ${state}`); // You can add the action to be performed after the state is switched. }) // Callback function for errors. - avRecorder.on('error', (err) => { + avRecorder.on('error', (err: BusinessError) => { console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -62,21 +62,21 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts - let avProfile = { + let avProfile: media.AVRecorderProfile = { audioBitrate: 100000, // Audio bit rate. audioChannels: 2, // Number of audio channels. audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. audioSampleRate: 48000, // Audio sampling rate. fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. } - let avConfig = { + let avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. profile: avProfile, url: 'fd://35', // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management. } avRecorder.prepare(avConfig).then(() => { console.log('Invoke prepare succeeded.'); - }, (err) => { + }, (err: BusinessError) => { console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -100,17 +100,17 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts import media from '@ohos.multimedia.media'; - +import { BusinessError } from '@ohos.base'; export class AudioRecorderDemo { - private avRecorder; - private avProfile = { + private avRecorder: media.AVRecorder; + private avProfile: media.AVRecorderProfile = { audioBitrate: 100000, // Audio bit rate. audioChannels: 2, // Number of audio channels. audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. audioSampleRate: 48000, // Audio sampling rate. fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. }; - private avConfig = { + private avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. profile: this.avProfile, url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. @@ -119,11 +119,11 @@ export class AudioRecorderDemo { // Set AVRecorder callback functions. setAudioRecorderCallback() { // Callback function for state changes. - this.avRecorder.on('stateChange', (state, reason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`AudioRecorder current state is ${state}`); }) // Callback function for errors. - this.avRecorder.on('error', (err) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`); }) } diff --git a/en/application-dev/media/video-recording.md b/en/application-dev/media/video-recording.md index 8eabb4e1aad61f954135832ff2e5439912acdb34..d2f5affc31bca6badec8329a918a2aed2e498779 100644 --- a/en/application-dev/media/video-recording.md +++ b/en/application-dev/media/video-recording.md @@ -24,10 +24,10 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts import media from '@ohos.multimedia.media' - let avRecorder - media.createAVRecorder().then((recorder) => { + let avRecorder: media.AVRecorder; + media.createAVRecorder().then((recorder: media.AVRecorder) => { avRecorder = recorder - }, (error) => { + }, (error: Error) => { console.error('createAVRecorder failed') }) ``` @@ -40,11 +40,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ```ts // Callback function for state changes. - avRecorder.on('stateChange', (state, reason) => { + avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info('current state is: ' + state); }) // Callback function for errors. - avRecorder.on('error', (err) => { + avRecorder.on('error', (err: BusinessError) => { console.error('error happened, error message is ' + err); }) ``` @@ -62,7 +62,7 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md). ```ts - let avProfile = { + let avProfile: media.AVRecorderProfile = { fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. videoBitrate: 200000, // Video bit rate. videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported. @@ -70,15 +70,15 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re videoFrameHeight: 480, // Video frame height. videoFrameRate: 30 // Video frame rate. } - let avConfig = { + let avConfig: media.AVRecorderConfig = { videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. - profile : this.avProfile, + profile : avProfile, url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. rotation: 0, // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270. } avRecorder.prepare(avConfig).then(() => { console.info('avRecorder prepare success') - }, (error) => { + }, (error: Error) => { console.error('avRecorder prepare failed') }) ``` @@ -90,9 +90,9 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data. ```ts - avRecorder.getInputSurface().then((surfaceId) => { + avRecorder.getInputSurface().then((surfaceId: string) => { console.info('avRecorder getInputSurface success') - }, (error) => { + }, (error: Error) => { console.error('avRecorder getInputSurface failed') }) ``` @@ -123,19 +123,20 @@ Refer to the sample code below to complete the process of starting, pausing, res ```ts import media from '@ohos.multimedia.media' +import { BusinessError } from '@ohos.base'; const TAG = 'VideoRecorderDemo:' export class VideoRecorderDemo { - private avRecorder; - private videoOutSurfaceId; - private avProfile = { + private avRecorder: media.AVRecorder; + private videoOutSurfaceId: string; + private avProfile: media.AVRecorderProfile = { fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. - videoBitrate : 100000, // Video bit rate. + videoBitrate: 100000, // Video bit rate. videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported. videoFrameWidth: 640, // Video frame width. videoFrameHeight: 480, // Video frame height. videoFrameRate: 30 // Video frame rate. } - private avConfig = { + private avConfig: media.AVRecorderConfig = { videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. profile : this.avProfile, url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. @@ -145,11 +146,11 @@ export class VideoRecorderDemo { // Set AVRecorder callback functions. setAvRecorderCallback() { // Callback function for state changes. - this.avRecorder.on('stateChange', (state, reason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info(TAG + 'current state is: ' + state); }) // Callback function for errors. - this.avRecorder.on('error', (err) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error(TAG + 'error ocConstantSourceNode, error message is ' + err); }) } @@ -188,7 +189,7 @@ export class VideoRecorderDemo { // 5. Start the camera stream output. await this.startCameraOutput(); // 6. Start recording. - await this.videoRecorder.start(); + await this.avRecorder.start(); } // Process of pausing recording. diff --git a/en/application-dev/napi/neural-network-runtime-guidelines.md b/en/application-dev/napi/neural-network-runtime-guidelines.md index 344ae4f1d623f67fcd3b093e8dec6653b806c4f2..974ccc5bafbfe7169034924ba27d0eb3c91606a8 100644 --- a/en/application-dev/napi/neural-network-runtime-guidelines.md +++ b/en/application-dev/napi/neural-network-runtime-guidelines.md @@ -1,4 +1,4 @@ -# Connecting the Neural Network Runtime to an AI Inference Framework +# Development Guide for Connecting the Neural Network Runtime to an AI Inference Framework ## When to Use @@ -19,8 +19,7 @@ The environment requirements for the Neural Network Runtime are as follows: - Development environment: Ubuntu 18.04 or later. - Access device: a standard device running OpenHarmony. The built-in hardware accelerator driver has been connected to the Neural Network Runtime through an HDI API. -The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications. - +The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications. ### Environment Setup @@ -33,7 +32,6 @@ unzip native-linux-{version number}.zip ``` The directory structure after decompression is as follows. The content in the directory may vary depending on version iteration. Use the Native APIs of the latest version. - ```text native/ ─ ─ build // Cross-compilation toolchain @@ -488,4 +486,4 @@ The development process of the Neural Network Runtime consists of three phases: ```shell rm /data/local/tmp/*nncache - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/performance/Readme.md b/en/application-dev/performance/Readme.md index 8172a210af94348fdb22831295c90a19b74965e6..c2e65ad02feaabc1fa88e7beb5f96af3c249568d 100644 --- a/en/application-dev/performance/Readme.md +++ b/en/application-dev/performance/Readme.md @@ -6,7 +6,7 @@ Following these practices, you can reduce your application's startup time, respo - Improving application startup and response time - - [Speeding Up Application Cold Start](../performance/improve-application-startup-and-response/improve-application-cold-start-speed.md) + - [Speeding Up Application Cold Start](improve-application-startup-and-response/improve-application-cold-start-speed.md) Application startup latency is a key factor that affects user experience. To speed up the application cold start, you are advised to perform optimization in the following four phases: @@ -18,16 +18,16 @@ Following these practices, you can reduce your application's startup time, respo ​ 4. Home page loading and drawing - - [Speeding Up Application Response](../performance/improve-application-startup-and-response/improve-application-response.md) + - [Speeding Up Application Response](improve-application-startup-and-response/improve-application-response.md) - A premium interaction experience requires quick response to user input. To improve your application's response time, you are advised to prevent the main thread from being blocked by non-UI tasks and reduce the number of component to be refreshed. + A premium interaction experience requires quick response to user input. To improve your application's response time, you are advised to prevent the main thread from being blocked by non-UI tasks and reduce the number of components to be refreshed. - Reducing frame loss - - [Reducing Nesting](../performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md) + - [Reducing Nesting](reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md) The smoothness of rendering the layout to the screen affects the user perceived quality. It is recommended that you minimize nesting in your code to shorten the render time. - - [Reducing Frame Loss](../performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md) + - [Reducing Frame Loss](reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md) Whether animations in your application run smoothly is a key factor that affects user experience. You are advised to use the system-provided animation APIs to reduce frame loss. diff --git a/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md b/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md index b99c5dfc0ac84d75954b53b3a5c291bf60f4314e..0a8dd8883f62b7502c51ac8a51894e81adddea5f 100644 --- a/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md +++ b/en/application-dev/performance/improve-application-startup-and-response/improve-application-cold-start-speed.md @@ -4,7 +4,7 @@ Application startup latency is a key factor that affects user experience. When a ## Analyzing the Time Required for Application Cold Start -The cold start process of OpenHarmony applications can be divided into four phases: application process creation and initialization, application and ability initialization, ability lifecycle, and home page loading and drawing, as shown in the following figure. +The cold start process of OpenHarmony applications can be divided into four phases: application process creation and initialization, application and ability initialization, ability lifecycle, and home page loading and drawing, as shown below. ![application-cold-start](../figure/application-cold-start.png) @@ -24,7 +24,7 @@ With regard to the icon of the startup page, the recommended maximum resolution "description": "$string:EntryAbility_desc", "icon": "$media:icon", "label": "$string:EntryAbility_label", - "startWindowIcon": "$media:startWindowIcon", // Modify the icon of the startup page. It is recommended that the icon be less than or equal to 256 pixels x 256 pixels. + "startWindowIcon": "$media:startWindowIcon", // Modify the icon of the startup page. It is recommended that the icon be less than or equal to 256 x 256 pixels. "startWindowBackground": "$color:start_window_background", "visible": true, "skills": [ @@ -43,7 +43,7 @@ With regard to the icon of the startup page, the recommended maximum resolution ## 2. Shortening Time Required for Application and Ability Initialization -In this phase of application and ability initialization, resources are loaded, VMs are created, application and ability related objects are created and initialized, and dependent modules are loaded. +In this phase of application and ability initialization, resources are loaded, virtual machines are created, application and ability related objects are created and initialized, and dependent modules are loaded. ### Minimizing the Number of Imported Modules @@ -57,7 +57,7 @@ In this phase of ability lifecycle, the ability lifecycle callbacks are executed In the application startup process, the system executes the ability lifecycle callbacks. Whenever possible, avoid performing time-consuming operations in these callbacks. You are advised to perform time-consuming operations through asynchronous tasks or execute them in other threads. -In these lifecycle callbacks, perform only necessary operations. For details, see [UIAbility Lifecycle](https://gitee.com/openharmony/docs/blob/master/en/application-dev/application-models/uiability-lifecycle.md). +In these lifecycle callbacks, perform only necessary operations. For details, see [UIAbility Lifecycle](../../application-models/uiability-lifecycle.md). ## 4. Shortening Time Required for Home Page Loading and Drawing diff --git a/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md b/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md index b740edb6f1f4e2df007631f6feef966762e0d2ba..989cfe91758f2c66830e5f277bbe19ba800f0a93 100644 --- a/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md +++ b/en/application-dev/performance/improve-application-startup-and-response/improve-application-response.md @@ -61,7 +61,7 @@ struct ImageExample1 { ### Using TaskPool for Asynchronous Processing -Compared with the worker thread, [TaskPool](https://gitee.com/sqsyqqy/docs/blob/master/en/application-dev/reference/apis/js-apis-taskpool.md) provides the task priority setting and automatic thread pool management mechanism. The following is an example: +Compared with the worker thread, [TaskPool](../../reference/apis/js-apis-taskpool.md) provides the task priority setting and automatic thread pool management mechanism. The following is an example: ```javascript import taskpool from '@ohos.taskpool'; diff --git a/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md b/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md index a61c8649e392b7fd0055e63ab48e0fa335faab7f..0a34c272b6a28109637eb3e3cb9a5ff591dc43ca 100644 --- a/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md +++ b/en/application-dev/performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md @@ -90,7 +90,7 @@ struct AttrAnimationExample { } ``` -For more details, see [Property Animator](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-animatorproperty.md). +For more details, see [Property Animation](../../reference/arkui-ts/ts-animatorproperty.md). ## Using System-Provided Explicit Animation APIs @@ -139,4 +139,4 @@ struct AnimateToExample { } ``` -For more details, see [Explicit Animation](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-explicit-animation.md). +For more details, see [Explicit Animation](../../reference/arkui-ts/ts-explicit-animation.md). diff --git a/en/application-dev/quick-start/arkts-application-state-management-overview.md b/en/application-dev/quick-start/arkts-application-state-management-overview.md index b481f79298e585c00a8a6e5c80f1c6a5cc092949..951153b3576e906d499a2cbc14063cfd869dc293 100644 --- a/en/application-dev/quick-start/arkts-application-state-management-overview.md +++ b/en/application-dev/quick-start/arkts-application-state-management-overview.md @@ -4,10 +4,10 @@ The decorators described in the previous topics are used to share state variables within a page, that is, within a component tree. If you want to share state data at the application level or across multiple pages, you would need to apply application-level state management. ArkTS provides a wide variety of application state management capabilities: -- [LocalStorage](arkts-localstorage.md): API for storing the UI state, usually used for state sharing within a [UIAbility](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md) or between pages. +- [LocalStorage](arkts-localstorage.md): API for storing the UI state, usually used for state sharing within a [UIAbility](../reference/apis/js-apis-app-ability-uiAbility.md) or between pages. - [AppStorage](arkts-appstorage.md): special, singleton LocalStorage object within the application, which is created by the UI framework at application startup and provides the central storage for application UI state attributes. - [PersistentStorage](arkts-persiststorage.md): API for persisting application attributes. It is usually used together with AppStorage to persist selected AppStorage attributes to the disk so that their values are the same upon application re-start as they were when the application was closed. -- [Environment](arkts-environment.md): a range of environment parameters regarding the device where the application runs. The environment parameters are synchronized to the AppStorage and can be used together with the AppStorage. +- [Environment](arkts-environment.md): a range of environment parameters regarding the device where the application runs. The environment parameters are synchronized to AppStorage and can be used together with AppStorage. diff --git a/en/application-dev/quick-start/arkts-appstorage.md b/en/application-dev/quick-start/arkts-appstorage.md index 50cbcf6aa0854fc901eb6bbf80b41da7c990eaa1..c1ebb9c91252d5b75a96b837e6f07bd2f1053a56 100644 --- a/en/application-dev/quick-start/arkts-appstorage.md +++ b/en/application-dev/quick-start/arkts-appstorage.md @@ -23,8 +23,7 @@ Selected state attributes of AppStorage can be synced with different data source As mentioned above, if you want to establish a binding between AppStorage and a custom component, you'll need the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component, where **key** identifies the attribute in AppStorage. -When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.) - +When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Whether the attribute with the given key exists in AppStorage depends on the application logic. This means that the attribute with the given key may be missing from AppStorage. In light of this, local initialization is mandatory for the \@StorageProp(key)/\@StorageLink(key) decorated variable. By decorating a variable with \@StorageProp(key), a one-way data synchronization is established with the attribute with the given key in AppStorage. A local change can be made, but it will not be synchronized to AppStorage. An update to the attribute with the given key in AppStorage will overwrite local changes. @@ -193,9 +192,85 @@ struct CompA { } ``` -### Persistent Subscription and Callback +### Unrecommended: Using @StorageLink to Implement Event Notification + +Compared with the common mechanism for event notification, the two-way synchronization mechanism of @StorageLink and AppStorage is far less cost efficient and therefore not recommended. This is because AppStorage stores UI-related data, and its changes will cause costly UI refresh. + +In the following example, any tap event in the **TapImage** component will trigger a change of the **tapIndex** attribute. As @StorageLink establishes a two-way data synchronization with AppStorage, the local change is synchronized to AppStorage. As a result, all visible custom components owning the **tapIndex** attribute bound to AppStorage are notified to refresh the 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; + + // Check whether the component is selected. + 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; + } + } -The persistent subscription and callback can help reduce overhead and enhance code readability. + build() { + Column() { + Image(this.uri) + .objectFit(ImageFit.Cover) + .onClick(() => { + this.tapIndex = this.index; + }) + .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor }) + } + + } +} +``` + +To implement event notification with less overhead and higher code readability, use **emit** instead, with which you can subscribe to an event and receive event callback. ```ts @@ -294,10 +369,9 @@ export struct TapImage { } ``` -The following example uses the message mechanism to subscribe to events. Because this mechanism can result in a large number of nodes to listen for and a long implementation time, it is not recommended. - +The preceding notification logic is simple. It can be simplified into a ternary expression as follows: -```ts +``` // xxx.ets class ViewData { title: string; @@ -338,22 +412,11 @@ struct Gallery2 { @Component export struct TapImage { - @StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1; + @StorageLink('tapIndex') tapIndex: number = -1; @State tapColor: Color = Color.Black; private index: number; private uri: Resource; - // Check whether the component is selected. - 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) @@ -361,14 +424,18 @@ export struct TapImage { .onClick(() => { this.tapIndex = this.index; }) - .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor }) + .border({ + width: 5, + style: BorderStyle.Dotted, + color: (this.tapIndex >= 0 && this.index === this.tapIndex) ? Color.Red : Color.Black + }) } - } } ``` + ## Restrictions When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md), pay attention to the following: @@ -377,5 +444,5 @@ When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) - A call to **Environment.EnvProp()** after creating the attribute in AppStorage will fail. This is because AppStorage already has an attribute with the same name, and the environment variable will not be written into AppStorage. Therefore, you are advised not to use the preset environment variable name in AppStorage. -- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Persistent Subscription and Callback](#persistent-subscription-and-callback). +- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Unrecommended: Using @StorageLink to Implement Event Notification](#unrecommended-using-storagelink-to-implement-event-notification). diff --git a/en/application-dev/quick-start/arkts-builder.md b/en/application-dev/quick-start/arkts-builder.md index 80a262fcd97a0dcf6808bf8cdb84bf78849cb0e1..ab1c53b103db98c49fa42a21f69adff6ea32b86b 100644 --- a/en/application-dev/quick-start/arkts-builder.md +++ b/en/application-dev/quick-start/arkts-builder.md @@ -21,14 +21,14 @@ Syntax: ```ts -@Builder myBuilderFunction({ ... }) +@Builder MyBuilderFunction({ ... }) ``` Usage: ```ts -this.myBuilderFunction({ ... }) +this.MyBuilderFunction({ ... }) ``` - Defining one or more custom builder (\@Builder decorated) functions inside a custom component is allowed. Such a custom builder function can be considered as a private, special type of member functions of that component. @@ -66,7 +66,7 @@ There are two types of parameter passing for custom builder functions: [by-value - The parameter type must be the same as the declared parameter type. The **undefined** or **null** constants as well as expressions evaluating to these values are not allowed. -- All parameters are immutable inside the custom builder function. If mutability and synchronization of the mutation is required, the custom builder should be replaced by a custom component with a [@Link](arkts-link.md) decorated variable. +- All parameters are immutable inside the@Builder decorated function. - The \@Builder function body follows the same [syntax rules](arkts-create-custom-components.md#build-function) as the **build** function. diff --git a/en/application-dev/quick-start/arkts-environment.md b/en/application-dev/quick-start/arkts-environment.md index 2f0718290460508c4510acc298fa85c855bbec26..ac80bd54590b0dffdfa6b3bf82351d27f09917a1 100644 --- a/en/application-dev/quick-start/arkts-environment.md +++ b/en/application-dev/quick-start/arkts-environment.md @@ -15,12 +15,11 @@ Environment is a singleton object created by the ArkUI framework at application - Use **Environment.EnvProp** to save the environment variables of the device to AppStorage. ```ts - // Save the language code of the device to AppStorage. The default value is en. - // Whenever its value changes in the device environment, it will update its value in AppStorage. + // Save languageCode to AppStorage. The default value is en. Environment.EnvProp('languageCode', 'en'); ``` -- To keep a component variable updated with changes in the device environment, this variable should be decorated with \@StorageProp. +- Decorate the variables with \@StorageProp to link them with components. ```ts @StorageProp('languageCode') lang : string = 'en'; @@ -29,6 +28,7 @@ Environment is a singleton object created by the ArkUI framework at application The chain of updates is as follows: Environment > AppStorage > Component. > **NOTE** +> > An \@StorageProp decorated variable can be locally modified, but the change will not be updated to AppStorage. This is because the environment variable parameters are read-only to the application. @@ -69,3 +69,29 @@ if (lang.get() === 'en') { console.info('Hello!'); } ``` + + +## Restrictions + + +Environment can be called only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. If Environment is called otherwise, no device environment data can be obtained. + + +```ts +// EntryAbility.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + windowStage.loadContent('pages/Index'); + let window = windowStage.getMainWindow() + window.then(window => { + let uicontext = window.getUIContext() + uicontext.runScopedTask(() => { + Environment.EnvProp('languageCode', 'en'); + }) + }) + } +} +``` diff --git a/en/application-dev/quick-start/arkts-get-started.md b/en/application-dev/quick-start/arkts-get-started.md index 79a401430c1a746c1850d6e6b64b72b76487b30b..76cf2844ca662c5f508dac5c574078a201a6eeff 100644 --- a/en/application-dev/quick-start/arkts-get-started.md +++ b/en/application-dev/quick-start/arkts-get-started.md @@ -7,16 +7,16 @@ ArkTS is the preferred main programming language for application development in The following syntaxes in TS are restricted in ArkTS: -- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, i.e. all types are known at the compile time, it’s much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance. +- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, that is, all types are known at the compile time, it's much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance. - Changing object layout in runtime is prohibited. To achieve maximum performance benefits, ArkTS requires that layout of objects does not change during program execution. -- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. Such as, the binary `+` operator supports only for strings and numbers but not for objects. +- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. For example, the binary `+` operator is supported for strings and numbers, but not for objects. -- structural typing is not supported. Support for structural typing is a major feature which needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider based on real-world scenarios and feedback. +- Structural typing is not supported. Support for structural typing is a major feature that needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider this feature based on real-world scenarios and feedback. -The added features offered by ArkTS for ArkUI framework include the following: +The added features offered by ArkTS for the ArkUI framework include the following: - [Basic syntax](arkts-basic-syntax-overview.md): ArkTS defines declarative UI description, custom components, and dynamic extension of UI elements. All these, together with built-in components, event methods, and attribute methods in ArkUI, jointly underpin UI development. diff --git a/en/application-dev/quick-start/arkts-localstorage.md b/en/application-dev/quick-start/arkts-localstorage.md index 392dda8432319b5695c593de178c5193fcf2a976..ad8d8a138402c2fda8bf3be3b91396e51cf6a015 100644 --- a/en/application-dev/quick-start/arkts-localstorage.md +++ b/en/application-dev/quick-start/arkts-localstorage.md @@ -402,7 +402,7 @@ On the page, call the **GetShared** API to obtain the LocalStorage instance shar ```ts -// Use the GetShared API to obtain the Storage instance shared by stage. +// Use the GetShared API to obtain the LocalStorage instance shared by stage. let storage = LocalStorage.GetShared() @Entry(storage) diff --git a/en/application-dev/quick-start/arkts-observed-and-objectlink.md b/en/application-dev/quick-start/arkts-observed-and-objectlink.md index 61f1bd8ae476f5984405eed97fb127161bb131e2..a7e47fb63e57896158a6a03aaa6896bea7ac644f 100644 --- a/en/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/en/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -162,6 +162,26 @@ class ClassB { this.a = a; } } + +@Observed +class ClassD { + public c: ClassC; + + constructor(c: ClassC) { + this.c = c; + } +} + +@Observed +class ClassC extends ClassA { + public k: number; + + constructor(k: number) { + // Invoke the parent class method to process k. + super(k); + this.k = k; + } +} ``` @@ -169,60 +189,64 @@ class ClassB { ```ts @Component -struct ViewA { - label: string = 'ViewA1'; - @ObjectLink a: ClassA; +struct ViewC { + label: string = 'ViewC1'; + @ObjectLink c: ClassC; build() { Row() { - Button(`ViewA [${this.label}] this.a.c=${this.a.c} +1`) - .onClick(() => { - this.a.c += 1; - }) - } + Column() { + Text(`ViewC [${this.label}] this.a.c = ${this.c.c}`) + .fontColor('#ffffffff') + .backgroundColor('#ff3fc4c4') + .height(50) + .borderRadius(25) + Button(`ViewC: this.c.c add 1`) + .backgroundColor('#ff7fcf58') + .onClick(() => { + this.c.c += 1; + console.log('this.c.c:' + this.c.c) + }) + } + .width(300) } } +} @Entry @Component struct ViewB { @State b: ClassB = new ClassB(new ClassA(0)); - + @State child : ClassD = new ClassD(new ClassC(0)); build() { Column() { - ViewA({ label: 'ViewA #1', a: this.b.a }) - ViewA({ label: 'ViewA #2', a: this.b.a }) - - Button(`ViewB: this.b.a.c+= 1`) - .onClick(() => { - this.b.a.c += 1; - }) - Button(`ViewB: this.b.a = new ClassA(0)`) + ViewC({ label: 'ViewC #3', c: this.child.c}) + Button(`ViewC: this.child.c.c add 10`) + .backgroundColor('#ff7fcf58') .onClick(() => { - this.b.a = new ClassA(0); - }) - Button(`ViewB: this.b = new ClassB(ClassA(0))`) - .onClick(() => { - this.b = new ClassB(new ClassA(0)); + this.child.c.c += 10 + console.log('this.child.c.c:' + this.child.c.c) }) } } } ``` +The @Observed decorated **ClassC** class can observe changes in attributes inherited from the base class. + Event handlers in **ViewB**: -- this.b.a = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes. +- this.child.c = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes. -- this.b.a.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink. +- this.child.c.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink. -Event handlers in **ViewA**: +Event handle in **ViewC**: -- this.a.c += 1: Changes to the \@ObjectLink decorated variable cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source. +- this.c.c += 1: Changes to the \@ObjectLink decorated variable **a** cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source. - The \@ObjectLink decorated variable is read-only. Assigning **this.a = new ClassA(...)** is not allowed. Once value assignment occurs, the reference to the data source is reset and the synchronization is interrupted. @@ -297,7 +321,7 @@ struct ViewB { 2. ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] }): The preceding update changes the first element in the array. Therefore, the **ViewA** component instance bound to **this.arrA[0]** is updated. - this.arrA.push(new ClassA(0)): The change of this state variable triggers two updates with different effects. - 1. ForEach: The newly added Class A object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **View A** component instance. + 1. ForEach: The newly added **ClassA** object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **ViewA** component instance. 2. ViewA({ label: ViewA this.arrA[last], a: this.arrA[this.arrA.length-1] }): The last item of the array is changed. As a result, the second **View A** component instance is changed. For **ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] })**, a change to the array does not trigger a change to the array item, so the first **View A** component instance is not refreshed. - this.arrA[Math.floor (this.arrA.length/2)].c: [@State](arkts-state.md#observed-changes) cannot observe changes at the second layer. However, as **ClassA** is decorated by \@Observed, the change of its attributes will be observed by \@ObjectLink. diff --git a/en/application-dev/quick-start/arkts-persiststorage.md b/en/application-dev/quick-start/arkts-persiststorage.md index fdbacd4235dcd50ea2777e8e3695227ff02be70c..21c854c26557e5fcd5027623b0429b625d6c9c91 100644 --- a/en/application-dev/quick-start/arkts-persiststorage.md +++ b/en/application-dev/quick-start/arkts-persiststorage.md @@ -24,7 +24,7 @@ Persistence of data is a relatively slow operation. Applications should avoid th The preceding situations may overload the change process of persisted data. As a result, the PersistentStorage implementation may limit the change frequency of persisted attributes. -PersistentStorage is associated with UIContext and can be called to persist data only when [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext) is specified. The context can be identified in [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask). +PersistentStorage can be called to persist data only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. ## Application Scenarios diff --git a/en/application-dev/quick-start/arkts-rendering-control-foreach.md b/en/application-dev/quick-start/arkts-rendering-control-foreach.md index 4c916bec86f9c9d22b9bdb60ca476f9cbdcd4846..dc6ae173f51df82fbc48f26df56368450fa6fa79 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-foreach.md +++ b/en/application-dev/quick-start/arkts-rendering-control-foreach.md @@ -3,6 +3,9 @@ **ForEach** enables repeated content based on array-type data. +> **NOTE** +> +> Since API version 9, this API is supported in ArkTS widgets. ## API Description @@ -19,15 +22,15 @@ ForEach( | Name | Type | Mandatory | Description | | ------------- | ---------------------------------------- | ---- | ---------------------------------------- | | arr | Array | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.| -| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.| -| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.| +| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.| +| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.| ## Restrictions - **ForEach** must be used in container components. -- The type of the child component must be the one allowed inside the parent container component of **ForEach**. +- The type of the child component must be the one allowed inside the parent container component of **ForEach**. - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**. diff --git a/en/application-dev/quick-start/arkts-style.md b/en/application-dev/quick-start/arkts-style.md index a380964f5893e963e6ce3c62c64d1255f37a8042..2d6cfe90ca118435e7a336027312fb4340147d17 100644 --- a/en/application-dev/quick-start/arkts-style.md +++ b/en/application-dev/quick-start/arkts-style.md @@ -45,12 +45,12 @@ If the style of each component needs to be set separately, this will result in a ```ts @Component struct FancyUse { - @State heightVlaue: number = 100 + @State heightValue: number = 100 @Styles fancy() { - .height(this.heightVlaue) + .height(this.heightValue) .backgroundColor(Color.Yellow) .onClick(() => { - this.heightVlaue = 200 + this.heightValue = 200 }) } } @@ -77,14 +77,14 @@ The following example demonstrates the usage of \@Styles inside and outside a co @Entry @Component struct FancyUse { - @State heightVlaue: number = 100 + @State heightValue: number = 100 // Define a \@Styles decorated method inside a component declaration. @Styles fancy() { .width(200) - .height(this.heightVlaue) + .height(this.heightValue) .backgroundColor(Color.Yellow) .onClick(() => { - this.heightVlaue = 200 + this.heightValue = 200 }) } diff --git a/en/application-dev/quick-start/arkts-watch.md b/en/application-dev/quick-start/arkts-watch.md index 08ae0631beda39cd2d511fd05f4d800952c26de1..f1bd84ccd6d0c067525213c0e09169fb100be2a4 100644 --- a/en/application-dev/quick-start/arkts-watch.md +++ b/en/application-dev/quick-start/arkts-watch.md @@ -52,6 +52,51 @@ An application can request to be notified whenever the value of the \@Watch deco ## Application Scenarios +### \@Watch and Custom Component Update + +This example is used to clarify the processing steps of custom component updates and \@Watch. **count** is decorated by \@State in **CountModifier** and \@Prop in **TotalView**. + + +```ts +@Component +struct TotalView { + @Prop @Watch('onCountUpdated') count: number; + @State total: number = 0; + // @Watch cb + onCountUpdated(propName: string): void { + this.total += this.count; + } + + build() { + Text(`Total: ${this.total}`) + } +} + +@Entry +@Component +struct CountModifier { + @State count: number = 0; + + build() { + Column() { + Button('add to basket') + .onClick(() => { + this.count++ + }) + TotalView({ count: this.count }) + } + } +} +``` + +Processing steps: + +1. The click event **Button.onClick** of the **CountModifier** custom component increases the value of **count**. + +2. In response to the change of the @State decorated variable **count**, \@Prop in the child component **TotalView** is updated, and its **\@Watch('onCountUpdated')** callback is triggered, which updates the **total** variable in **TotalView**. + +3. The **Text** component in the child component **TotalView** is re-rendered. + ### Combination of \@Watch and \@Link @@ -124,52 +169,6 @@ The processing procedure is as follows: 2. The value of the \@Link decorated variable **BasketViewer shopBasket** changes. -3. The state management framework calls the \@Watch callback **BasketViewer onBasketUpdated** to update the value of **BaketViewer TotalPurchase**. +3. The state management framework calls the \@Watch callback **BasketViewer onBasketUpdated** to update the value of **BasketViewer TotalPurchase**. 4. Because \@Link decorated shopBasket changes (a new item is added), the ForEach component executes the item Builder to render and build the new item. Because the @State decorated totalPurchase variables changes, the **Text** component is also re-rendered. Re-rendering happens asynchronously. - - -### \@Watch and Custom Component Update - -This example is used to clarify the processing steps of custom component updates and \@Watch. **count** is decorated by \@State in **CountModifier** and \@Prop in **TotalView**. - - -```ts -@Component -struct TotalView { - @Prop @Watch('onCountUpdated') count: number; - @State total: number = 0; - // @Watch cb - onCountUpdated(propName: string): void { - this.total += this.count; - } - - build() { - Text(`Total: ${this.total}`) - } -} - -@Entry -@Component -struct CountModifier { - @State count: number = 0; - - build() { - Column() { - Button('add to basket') - .onClick(() => { - this.count++ - }) - TotalView({ count: this.count }) - } - } -} -``` - -Processing steps: - -1. The click event **Button.onClick** of the **CountModifier** custom component increases the value of **count**. - -2. In response to the change of the @State decorated variable **count**, \@Prop in the child component **TotalView** is updated, and its **\@Watch('onCountUpdated')** callback is triggered, which updates the **total** variable in **TotalView**. - -3. The **Text** component in the child component **TotalView** is re-rendered. diff --git a/en/application-dev/quick-start/introduction-to-arkts.md b/en/application-dev/quick-start/introduction-to-arkts.md index b3bbd6671524a508d881c3d5245d0a1958d59c63..4ed847999052fd43951fcbc1452bed456ad78ea3 100644 --- a/en/application-dev/quick-start/introduction-to-arkts.md +++ b/en/application-dev/quick-start/introduction-to-arkts.md @@ -1,48 +1,21 @@ # Introduction -Welcome to the tutorial for ArkTS, a TypeScript-based programming language -designed specifically to build high-performance mobile applications! +Welcome to the tutorial for ArkTS, a TypeScript-based programming language designed specifically to build high-performance mobile applications! -ArkTS is optimized to provide better performance and efficiency, while still -maintaining the familiar syntax of TypeScript. +ArkTS is optimized to provide better performance and efficiency, while still maintaining the familiar syntax of TypeScript. -As mobile devices continue to become more prevalent in our daily lives, -there is a growing need for programming languages optimized for the -mobile environment. Many current programming languages were not designed with -mobile devices in mind, resulting in slow and inefficient applications that -drain battery life. ArkTS has been specifically designed to address such concerns -by prioritizing higher execution efficiency. +As mobile devices continue to become more prevalent in our daily lives, there is a growing need for programming languages optimized for the mobile environment. Many current programming languages were not designed with mobile devices in mind, resulting in slow and inefficient applications that drain battery life. ArkTS has been specifically designed to address such concerns by prioritizing higher execution efficiency. -ArkTS is based on the popular programming language TypeScript that extends -JavaScript by adding type definitions. TypeScript is well-loved by many developers as it -provides a more structured approach to coding in JavaScript. ArkTS aims to -keep the look and feel of TypeScript to enable a seamless transition for the existing -TypeScript developers, and to let mobile developers learn ArkTS quickly. +ArkTS is based on the popular programming language TypeScript that extends JavaScript by adding type definitions. TypeScript is well-loved by many developers as it provides a more structured approach to coding in JavaScript. ArkTS aims to keep the look and feel of TypeScript to enable a seamless transition for the existing TypeScript developers, and to let mobile developers learn ArkTS quickly. One of the key features of ArkTS is its focus on low runtime overhead. -ArkTS imposes stricter limitations on the TypeScript’s dynamically typed features, -reducing runtime overhead and allowing faster execution. By eliminating -the dynamically typed features from the language, ArkTS code can be compiled -ahead-of-time more efficiently, resulting in faster application startup and -lower power consumption. - -Interoperability with JavaScript was a critical consideration in the ArkTS language -design. Many mobile app developers already have TypeScript and JavaScript code and libraries -they would want to reuse. ArkTS has been designed for seamless JavaScript -interoperability, making it easy for the developers to integrate the JavaScript code -into their applications and vice versa. This will allow the developers to -use their existing codebases and libraries to leverage the power of our -new language. - -To ensure best experience for UI app development for OpenHarmony ecosystem, -ArkTS provides support for ArkUI, including its declarative syntax and other -features. Since this feature is outside the scope of the “stock” TypeScript, a verbose -ArkUI example is provided in a separate chapter. - -This tutorial will guide the developers through the core features, syntax, -and best practices of ArkTS. After reading this tutorial through the end, -the developers will be able to build performant and efficient mobile -applications in ArkTS. +ArkTS imposes stricter limitations on the TypeScript's dynamically typed features, reducing runtime overhead and allowing faster execution. By eliminating the dynamically typed features from the language, ArkTS code can be compiled ahead-of-time more efficiently, resulting in faster application startup and lower power consumption. + +Interoperability with JavaScript was a critical consideration in the ArkTS language design. Many mobile app developers already have TypeScript and JavaScript code and libraries they would want to reuse. ArkTS has been designed for seamless JavaScript interoperability, making it easy for the developers to integrate the JavaScript code into their applications and vice versa. This will allow the developers to use their existing codebases and libraries to leverage the power of our new language. + +To ensure best experience for UI app development for OpenHarmony ecosystem, ArkTS provides support for ArkUI, including its declarative syntax and other features. Since this feature is outside the scope of the "stock" TypeScript, a verbose ArkUI example is provided in a separate chapter. + +This tutorial will guide you through the core features, syntax, and best practices of ArkTS. After reading this tutorial through the end, you will be able to build performant and efficient mobile applications in ArkTS. # The Basics @@ -50,15 +23,14 @@ applications in ArkTS. Declarations in ArkTS introduce: -- variables, -- constants, -- functions, and -- types. +- Variables +- Constants +- Functions +- Types ### Variable Declaration -A declaration starting with the keyword `let` introduces a variable which -can have different values during program execution. +A declaration starting with the keyword `let` introduces a variable which can have different values during program execution. ```typescript let hi: string = "hello" @@ -67,8 +39,7 @@ hi = "hello, world" ### Constant Declaration -A declaration starting with the keyword `const` introduces a read-only -constant that can be assigned only once. +A declaration starting with the keyword `const` introduces a read-only constant that can be assigned only once. ```typescript const hello: string = "hello" @@ -78,16 +49,13 @@ A compile-time error occurs if a new value is assigned to a constant. ### Automatic Type Inference -As ArkTS is a statically typed language, the types of all entities, like -variables and constants, have to be known at compile time. +As ArkTS is a statically typed language, the types of all entities, like variables and constants, have to be known at compile time. -However, developers do not need to explicitly specify the type of a declared -entity if a variable or a constant declaration contains an initial value. -All cases that allow the type to be inferred automatically are specified in -the ArkTS Specification. +However, developers do not need to explicitly specify the type of a declared entity if a variable or a constant declaration contains an initial value. -Both variable declarations are valid, and both variables are of the `string` -type: +All cases that allow the type to be inferred automatically are specified in the ArkTS Specification. + +Both variable declarations are valid, and both variables are of the `string` type: ```typescript let hi1: string = "hello" @@ -96,32 +64,30 @@ let hi2 = "hello, world" ## Types -`Class`, `interface`, `function`, `enum`, `union` types, and type -`aliases` are described in the corresponding sections. +`Class`, `interface`, `function`, `enum`, `union` types, and type `aliases` are described in the corresponding sections. ### Numeric Types -ArkTS has `number` and `Number` numeric types. Any integer and -floating-point values can be assigned to a variable of these types. +ArkTS has `number` and `Number` numeric types. Any integer and floating-point values can be assigned to a variable of these types. Numeric literals include integer literals and floating-point literals with the decimal base. Integer literals include the following: -* decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`; -* hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`; -* octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`; -* binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`. +* Decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`. +* Hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`. +* Octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`. +* Binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`. A floating-point literal includes the following: -* decimal integer, optionally signed (i.e., prefixed with “+” or “-“); -* decimal point (“.”); -* fractional part (represented by a string of decimal digits); -* exponent part that starts with “e” or “E”, followed by an optionally signed (i.e., prefixed with “+” or “-”) integer. +* Decimal integer, optionally signed (i.e., prefixed with "+" or "-"); +* Decimal point ("."). +* Fractional part (represented by a string of decimal digits). +* Exponent part that starts with "e" or "E", followed by an optionally signed (i.e., prefixed with "+" or "-") integer. -For example: +Example: ```typescript let n1 = 3.14 @@ -139,8 +105,7 @@ function factorial(n: number) : number { ### `Boolean` -The `boolean` type represents logical values that are either `true` -or `false`. +The `boolean` type represents logical values that are either `true` or `false`. Usually variables of this type are used in conditional statements: @@ -156,12 +121,9 @@ if (isDone) { ### `String` -A `string` is a sequence of characters; some characters can be set by using -escape sequences. +A `string` is a sequence of characters; some characters can be set by using escape sequences. -A `string` literal consists of zero or more characters enclosed in single -(’) or double quotes (“). The special form of string literals are template -literals enclosed in backtick quotes (\`). +A `string` literal consists of zero or more characters enclosed in single (') or double quotes ("). The special form of string literals are template literals enclosed in backtick quotes (\`). ```typescript let s1 = "Hello, world!\n" @@ -185,18 +147,12 @@ let instance: Class ### `Object` Type -An `Object` class type is a base type for all reference types. Any value, -including values of primitive types (they will be automatically boxed), can -be directly assigned to variables of the type `Object`. +An `Object` class type is a base type for all reference types. Any value, including values of primitive types (they will be automatically boxed), can be directly assigned to variables of the type `Object`. ### `Array` Type -An `array` is an object comprised of elements of data types assignable to -the element type specified in the array declaration. -A value of an `array` is set by using *array composite literal*, that is a -list of zero or more expressions enclosed in square brackets ([]). Each -expression represents an element of the `array`. The length of the `array` -is set by the number of expressions. Index of the first array element is 0. +An `array` is an object comprised of elements of data types assignable to the element type specified in the array declaration. +A value of an `array` is set by using *array composite literal*, that is a list of zero or more expressions enclosed in square brackets ([]). Each expression represents an element of the `array`. The length of the `array` is set by the number of expressions. Index of the first array element is 0. The following example creates the `array` with three elements: @@ -206,18 +162,15 @@ let names: string[] = ["Alice", "Bob", "Carol"] ### `Enum` Type -An `enum` type is a value type with a defined set of named values called -enum constants. -In order to be used, an `enum` constant must be prefixed with an enum -`type` name. +An `enum` type is a value type with a defined set of named values called enum constants. +In order to be used, an `enum` constant must be prefixed with an enum `type` name. ```typescript enum Color { Red, Green, Blue } let c: Color = Color.Red ``` -A constant expression can be used to explicitly set the value of an `enum` -constant. +A constant expression can be used to explicitly set the value of an `enum` constant. ```typescript enum Color { White = 0xFF, Grey = 0x7F, Black = 0x00 } @@ -226,9 +179,7 @@ let c: Color = Color.Black ### `Union` Type -A `union` type is a reference type which is created as a combination -of other types. Values of union types can be valid values of all types -a union was created from. +A `union` type is a reference type which is created as a combination of other types. Values of union types can be valid values of all types a union was created from. ```typescript class Cat { @@ -251,7 +202,7 @@ animal = 42 There are different mechanisms to get a value of a particular type from a union. -For example +Example: ```typescript class Cat { sleep () {}; meow () {} } @@ -273,8 +224,7 @@ animal.sleep () // Any animal can sleep ### Type `Aliases` -Type `aliases` provide names for anonymous types (array, function, object -literal or union types) or alternative names for existing types. +Type `aliases` provides names for anonymous types (array, function, object literal or union types) or alternative names for existing types. ```typescript type Matrix = number[][] @@ -287,24 +237,22 @@ type NullableObject = Object | null ### Assignment Operators -Simple assignment operator ‘=’ is used as in “x = y”. +Simple assignment operator '=' is used as in "x = y". -Compound assignment operators combine an assignment with an operator, where -`x op = y` equals `x = x op y`. +Compound assignment operators combine an assignment with an operator, where `x op = y` equals `x = x op y`. -Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`, -`%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`. +Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`. ### Comparison Operators -| Operator | Description | -|------------|------------------------------------------------------------------------| -| `==` | returns true if both operands are equal | -| `!=` | returns true if both operands are not equal | -| `>` | returns true if the left operand is greater than the right | -| `>=` | returns true if the left operand is greater than or equal to the right | -| `<` | returns true if the left operand is less then the right | -| `<=` | returns true if the left operand is less than or equal to the right | +| Operator | Description | +| -------- | ------------------------------------------------------------ | +| `==` | Returns true if both operands are equal. | +| `!=` | Returns true if both operands are not equal. | +| `>` | Returns true if the left operand is greater than the right. | +| `>=` | Returns true if the left operand is greater than or equal to the right. | +| `<` | Returns true if the left operand is less than the right. | +| `<=` | Returns true if the left operand is less than or equal to the right. | ### Arithmetic Operators Unary operators are `-`, `+`, `--` and `++`. @@ -333,15 +281,15 @@ Binary operators are as follows: | Operator | Description | |------------|---------------| -| `a && b` | logical AND | -| `a \|\| b` | logical OR | -| `! a` | logical NOT | +| `a && b` | Logical AND | +| `a \|\| b` | Logical OR | +| `! a` | Logical NOT | ## Control Flow ### `If` Statements -An `if` statement is used to execute a sequence of statements when a logical -condition is `true`, or another set of statements (if provided) otherwise. +An `if` statement is used to execute a sequence of statements when a logical condition is `true`, or another set of statements (if provided) otherwise. + The `else` part can also contain more `if` statements. An `if` statement looks as follows: @@ -356,9 +304,7 @@ if (condition1) { } ``` -All conditional expressions must be of the type `boolean` or other types -(`string`, `number`, etc.). For types other than `boolean`, implicit -conversion rules apply: +All conditional expressions must be of the type `boolean` or other types (`string`, `number`, etc.). For types other than `boolean`, implicit conversion rules apply: ```typescript let s1 = "Hello" @@ -374,8 +320,7 @@ if (s2.length != 0) { ### `Switch` Statements -A `switch` statement is used to execute a sequence of statements that match -the value of a switch expression. +A `switch` statement is used to execute a sequence of statements that match the value of a switch expression. A `switch` statement looks as follows: @@ -397,27 +342,21 @@ default: } ``` -The `switch` expression type must be of `number`, `enum` or `string` -types. +The `switch` expression type must be of `number`, `enum` or `string` types. Each label must be either a constant expression or the name of an enum constant. -If the value of a `switch` expression equals the value of some label, then -the corresponding statements are executed. +If the value of a `switch` expression equals the value of some label, then the corresponding statements are executed. -If there is no match, and the `switch` has the default clause, then the -default statements are executed. +If there is no match, and the `switch` has the default clause, then the default statements are executed. -An optional `break` statement allows to break out of the `switch` and -continue executing the statement that follows the `switch`. +An optional `break` statement allows you to break out of the `switch` and continue executing the statement that follows the `switch`. -If there is no `break`, then the next statements in the `switch` is -executed. +If there is no `break`, then the next statements in the `switch` are executed. ### Conditional Expressions -The conditional expression `? :` uses the `boolean` value of the first -expression to decide which of two other expressions to evaluate. +The conditional expression `? :` uses the `boolean` value of the first expression to decide which of two other expressions to evaluate. A conditional expression looks as follows: @@ -425,9 +364,7 @@ A conditional expression looks as follows: condition ? expression1 : expression2 ``` -The condition must be a logical expression. If that logical expression is -`true`, then the first expression is used as the result of the ternary -expression; otherwise, the second expression is used. +The condition must be a logical expression. If that logical expression is `true`, then the first expression is used as the result of the ternary expression; otherwise, the second expression is used. Example: @@ -438,8 +375,7 @@ let message = isValid ? 'Valid' : 'Failed' ### `For` Statements -A `for` statement is executed repeatedly until the specified loop exit -condition is `false`. +A `for` statement is executed repeatedly until the specified loop exit condition is `false`. A `for` statement looks as follows: @@ -451,15 +387,10 @@ for ([init]; [condition]; [update]) { When a `for` statement is executed, the following process takes place: -1. An `init` expression is executed, if any. This expression usually - initializes one or more loop counters. -2. The condition is evaluated. If the value of condition is `true`, or - if the conditional expression is omitted, then the statements in the - `for` body are to be executed. If the value of condition is `false`, - then the `for` loop terminates. +1. An `init` expression is executed, if any. This expression usually initializes one or more loop counters. +2. The condition is evaluated. If the value of condition is `true`, or if the conditional expression is omitted, then the statements in the `for` body are to be executed. If the value of condition is `false`, then the `for` loop terminates. 3. The statements of the `for` body are executed. -4. If there is an `update` expression, then the `update` expression - is executed. +4. If there is an `update` expression, then the `update` expression is executed. 5. Go back to step 2. Example: @@ -491,8 +422,7 @@ for (let ch of "a string object") { /* process ch */ } ### `While` Statements -A `while` statement has its body statements executed as long as the -specified condition evaluates to `true`. +A `while` statement has its body statements executed as long as the specified condition evaluates to `true`. A `while` statement looks as follows: @@ -517,8 +447,7 @@ while (n < 3) { ### `Do-while` Statements -`do-while` statements are executed repetitively until a specified -condition evaluates to false. +`do-while` statements are executed repetitively until a specified condition evaluates to false. A `do-while` statement looks as follows: @@ -555,8 +484,7 @@ while (true) { } ``` -A `break` statement with a label identifier transfers control out of the -enclosing statement to the one which has the same label identifier. +A `break` statement with a label identifier transfers control out of the enclosing statement to the one which has the same label identifier. Example: @@ -573,8 +501,7 @@ label: while (true) { ### `Continue` Statements -A `continue` statement stops the execution of the current loop iteration -and passes control to the next iteration. +A `continue` statement stops the execution of the current loop iteration and passes control to the next iteration. Example: @@ -606,8 +533,7 @@ try { } ``` -The example below shows the `throw` and `try` statements used to handle -the zero division case: +The example below shows the `throw` and `try` statements used to handle the zero division case: ```typescript class ZeroDivisor extends Error {} @@ -655,8 +581,7 @@ function processData(s: string) { ## Function Declarations -A function declaration introduces a named function, specifying its name, -parameters, return type and body. +A function declaration introduces a named function, specifying its name, parameters, return type and body. Below is a simple function with two string parameters and string return type: @@ -668,8 +593,7 @@ function add(x: string, y: string): string { ``` For every parameter its type annotation must be specified. -An optional parameter allows to omit the corresponding argument when -calling a function. The last parameter of a function can be a rest parameter. +An optional parameter allows you to omit the corresponding argument when calling a function. The last parameter of a function can be a rest parameter. ## Optional Parameters @@ -686,8 +610,7 @@ function hello(name?: string) { ``` Another form contains an expression that specifies a default value. -If the corresponding argument to such parameter is omitted in a function call, -then this parameter’s value is default. +If the corresponding argument to such parameter is omitted in a function call, then this parameter's value is default. ```typescript function multiply(n: number, coeff: number = 2): number { @@ -699,8 +622,7 @@ multiply(2, 3) // returns 2*3 ## The Rest Parameter -The last parameter of a function can be a rest parameter. -It allows functions or methods to take unlimited number of arguments. +The last parameter of a function can be a rest parameter. It allows functions or methods to take unlimited number of arguments. ```typescript function sum(...numbers: number[]): number { @@ -716,8 +638,7 @@ sum(1, 2, 3) // returns 6 ## Return Types -If function return type can be inferred from its body content, then it can -be omitted from the function declaration. +If function return type can be inferred from its body content, then it can be omitted from the function declaration. ```typescript // Explicit return type @@ -727,9 +648,7 @@ function foo(): string { return "foo" } function goo() { return "goo" } ``` -The return type of a function that does not need to return a value can be -explicitly specified as `void` or omitted altogether. No return statement -is needed for such functions. +The return type of a function that does not need to return a value can be explicitly specified as `void` or omitted altogether. No return statement is needed for such functions. Both notations below are valid: @@ -740,16 +659,13 @@ function hi2(): void { console.log("hi") } ## Function Scope -Variables and other entities defined in a function are local to the function -and cannot be accessed from the outside. +Variables and other entities defined in a function are local to the function and cannot be accessed from the outside. -If the name of a variable defined in the function is equal to the name of an -entity in the outer scope, then the local definition shadows the outer entity. +If the name of a variable defined in the function is equal to the name of an entity in the outer scope, then the local definition shadows the outer entity. ## Function Calls -Calling a function actually leads to the execution of its body, while -the arguments of the call are assigned to the function parameters. +Calling a function actually leads to the execution of its body, while the arguments of the call are assigned to the function parameters. If the function is defined as follows: @@ -791,11 +707,9 @@ let sum = (x: number, y: number): number => { } ``` -An arrow function return type can be omitted; in such case, it is inferred -from the function body. +An arrow function return type can be omitted; in such case, it is inferred from the function body. -An expression can be specified as an arrow function to make the notation -shorter, i.e., the following two notations are equivalent: +An expression can be specified as an arrow function to make the notation shorter, i.e., the following two notations are equivalent: ```typescript let sum1 = (x: number, y: number) => { return x + y } @@ -804,9 +718,7 @@ let sum2 = (x: number, y: number) => x + y ## Closure -An arrow function is usually defined inside another function. As an inner -function, it can access all variables and functions defined in the outer -functions. +An arrow function is usually defined inside another function. As an inner function, it can access all variables and functions defined in the outer functions. To capture the context, an inner function forms a closure of its environment. The closure allows accessing such an inner function outside its own environment. @@ -826,15 +738,12 @@ In the sample above, the arrow function closure captures the `count` variable. ## Function Overload Signatures -A function can be specified to be called in different ways by writing -overload signatures. To do so, several functions’ headers that have the -same name but different signatures are written and immediately followed -by the single implementation function. +A function can be specified to be called in different ways by writing overload signatures. To do so, several functions' headers that have the same name but different signatures are written and immediately followed by the single implementation function. ```typescript function foo(): void; /* 1st signature */ function foo(x: string): void; /* 2nd signature */ -function foo(x?: string): void { /* implementation signature */ +function foo(x?: string): void { /* Implementation signature */ console.log(x) } @@ -846,11 +755,9 @@ An error occurs if two overload signatures have identical parameter lists. # Classes -A class declaration introduces a new type and defines its fields, methods -and constructors. +A class declaration introduces a new type and defines its fields, methods and constructors. -In the following example, class `Person` is defined, which has fields -‘name’ and ‘surname’, constructor, and a method `fullName`: +In the following example, class `Person` is defined, which has fields **name** and **surname**, constructor, and a method `fullName`: ```typescript class Person { @@ -866,8 +773,7 @@ class Person { } ``` -After the class is defined, its instances can be created by using -the keyword `new`: +After the class is defined, its instances can be created by using the keyword `new`: ```typescript let p = new Person("John", "Smith") @@ -887,12 +793,12 @@ let p: Point = {x: 42, y: 42} ## Fields A field is a variable of some type that is declared directly in a class. + Classes may have instance fields, static fields or both. ### Instance Fields -Instance fields exist on every instance of a class. Each instance has its own -set of instance fields. +Instance fields exist on every instance of a class. Each instance has its own set of instance fields. ```typescript class Person { @@ -917,9 +823,7 @@ this.name ### Static Fields -The keyword `static` is used to declare a field as static. Static fields -belong to the class itself, and all instances of the class share one static -field. +The keyword `static` is used to declare a field as static. Static fields belong to the class itself, and all instances of the class share one static field. The class name is used to access a static field: @@ -938,11 +842,9 @@ console.log(Person.numberOfPersons) ### Getters and Setters -Setters and getters can be used to provide controlled access to object -properties. +Setters and getters can be used to provide controlled access to object properties. -In the following example, a setter is used to forbid setting invalid -values of the ‘age’ property: +In the following example, a setter is used to forbid setting invalid values of the 'age' property: ```typescript class Person { @@ -968,16 +870,13 @@ A class can define a getter, a setter or both. A method is a function that belongs to a class. A class can define instance methods, static methods or both. -A static method belongs to the class itself, and can have access to static -fields only. -A `while` instance method has access to both static (class) fields and -instance fields including private ones of its class. +A static method belongs to the class itself, and can have access to static fields only. +A `while` instance method has access to both static (class) fields and instance fields including private ones of its class. ### Instance Methods The example below illustrates how instanced methods work. -The `calculateArea` method calculates the area of a rectangle by -multiplying the height by the width: +The `calculateArea` method calculates the area of a rectangle by multiplying the height by the width: ```typescript class Rectangle { @@ -1001,8 +900,7 @@ console.log(square.calculateArea()) // output: 100 ### Static Methods -The keyword `static` is used to declare a method as static. Static methods -belong to the class itself and have access to static fields only. +The keyword `static` is used to declare a method as static. Static methods belong to the class itself and have access to static fields only. A static method defines a common behavior of the class as a whole. All instances have access to static methods. @@ -1019,8 +917,7 @@ console.log(Cl.staticMethod()) ### Inheritance -A class can extend another class (called base class) and implement several -interfaces by using the following syntax: +A class can extend another class (called base class) and implement several interfaces by using the following syntax: ```typescript class [extends BaseClassName] [implements listOfInterfaces] { @@ -1028,12 +925,9 @@ class [extends BaseClassName] [implements listOfInterfaces] { } ``` -The extended class inherits fields and methods from the base class, but -not constructors, and can add its own fields and methods as well as override -methods defined by the base class. +The extended class inherits fields and methods from the base class, but not constructors, and can add its own fields and methods as well as override methods defined by the base class. -The base class is also called ‘parent class’ or ‘superclass’. -The extended class also called ‘derived class’ or ‘subclass’. +The base class is also called 'parent class' or 'superclass'. The extended class also called 'derived class' or 'subclass'. Example: @@ -1053,9 +947,7 @@ class Employee extends Person { } ``` -A class containing the `implements` clause must implement all methods -defined in all listed interfaces, except the methods defined with default -implementation. +A class containing the `implements` clause must implement all methods defined in all listed interfaces, except the methods defined with default implementation. ```typescript interface DateInterface { @@ -1071,11 +963,9 @@ class MyDate implements DateInterface { ### Access to Super -The keyword `super` can be used to access instance fields, instance methods -and constructors from the super class. +The keyword `super` can be used to access instance fields, instance methods and constructors from the super class. -It is often used to extend basic functionality of subclass with the required -behavior taken from the super class: +It is often used to extend basic functionality of subclass with the required behavior taken from the super class: ```typescript class Rectangle { @@ -1109,10 +999,8 @@ class FilledRectangle extends Rectangle { ### Override Methods A subclass can override implementation of a method defined in its superclass. -An overridden method can be marked with the keyword `override` to improve -readability. -An overridden method must have the same types of parameters, and same or -derived return type as the original method. +An overridden method can be marked with the keyword `override` to improve readability. +An overridden method must have the same types of parameters, and same or derived return type as the original method. ```typescript class Rectangle { @@ -1132,10 +1020,7 @@ class Square extends Rectangle { ### Method Overload Signatures -A method can be specified to be called in different ways by writing overload -signatures. To do so, several method headers that have the same name but -different signatures are written and immediately followed by the single -implementation method. +A method can be specified to be called in different ways by writing overload signatures. To do so, several method headers that have the same name but different signatures are written and immediately followed by the single implementation method. ```typescript class C { @@ -1150,13 +1035,11 @@ c.foo() // ok, 1st signature is used c.foo("aa") // ok, 2nd signature is used ``` -An error occurs if two overload signatures have the same name and identical -parameter lists. +An error occurs if two overload signatures have the same name and identical parameter lists. ## Constructors -A class declaration may contain a constructor that is used to initialize -object state. +A class declaration may contain a constructor that is used to initialize object state. A constructor is defined as follows: @@ -1166,8 +1049,7 @@ constructor ([parameters]) { } ``` -If no constructor is defined, then a default constructor with an empty -parameter list is created automatically, for example: +If no constructor is defined, then a default constructor with an empty parameter list is created automatically, for example: ```typescript class Point { @@ -1177,13 +1059,11 @@ class Point { let p = new Point() ``` -In this case the default constructor fills the instance fields with -default values for the field types. +In this case the default constructor fills the instance fields with default values for the field types. ### Constructors in Derived Class -The first statement of a constructor body can use the keyword `super` -to explicitly call a constructor of the direct superclass. +The first statement of a constructor body can use the keyword `super` to explicitly call a constructor of the direct superclass. ```typescript class Rectangle { @@ -1198,22 +1078,17 @@ class Square extends Rectangle { } ``` -If a constructor body does not begin with such an explicit call of a -superclass constructor, then the constructor body implicitly begins -with a superclass constructor call `super()`. +If a constructor body does not begin with such an explicit call of a superclass constructor, then the constructor body implicitly begins with a superclass constructor call `super()`. ### Constructor Overload Signatures -A constructor can be specified to be called in different ways by writing -overload signatures. To do so, several constructor headers that have the -same name but different signatures are written and immediately followed -by the single implementation constructor. +A constructor can be specified to be called in different ways by writing overload signatures. To do so, several constructor headers that have the same name but different signatures are written and immediately followed by the single implementation constructor. ```typescript class C { constructor() /* 1st signature */ constructor(x: string) /* 2nd signature */ - constructor(x?: string) { /* implementation signtaure */ + constructor(x?: string) { /* Implementation signature */ console.log(x) } } @@ -1221,8 +1096,7 @@ let c1 = new C() // ok, 1st signature is used let c2 = new C("abc") // ok, 2nd signature is used ``` -An error occurs if two overload signatures have the same name and -identical parameter lists. +An error occurs if two overload signatures have the same name and identical parameter lists. ## Visibility Modifiers @@ -1236,18 +1110,16 @@ There are several visibility modifiers: - `internal`. The default visibility is `public`. -The modifier `internal` allows to limit visibility within -the current package. +The modifier `internal` allows you to limit visibility within the current package. ### Public Visibility -The `public` members (fields, methods, constructors) of a class are -visible in any part of the program, where their class is visible. +The `public` members (fields, methods, constructors) of a class are visible in any part of the program, where their class is visible. ### Private Visibility -A `private` member cannot be accessed outside the class it is declared in, -for example: +A `private` member cannot be accessed outside the class it is declared in. +Example: ```typescript class C { @@ -1264,8 +1136,8 @@ c.y = "b" // compile-time error: 'y' is not visible ### Protected Visibility -The modifier `protected` acts much like the modifier `private`, but -the `protected` members are also accessible in derived classes, for example: +The modifier `protected` acts much like the modifier `private`, but the `protected` members are also accessible in derived classes. +Example: ```typescript class Base { @@ -1282,12 +1154,9 @@ class Derived extends Base { ## Object Literals -An object literal is an expression that can be used to create a class instance -and provide some initial values. It can be used instead of the expression -`new` as it is more convenient in some cases. +An object literal is an expression that can be used to create a class instance and provide some initial values. It can be used instead of the expression `new` as it is more convenient in some cases. -A class composite is written as a comma-separated list of name-value pairs -enclosed in ‘{’ and ‘}’. +A class composite is written as a comma-separated list of name-value pairs enclosed in '{' and '}'. ```typescript class C { @@ -1298,9 +1167,7 @@ class C { let c: C = {n: 42, s: "foo"} ``` -Due to the static typing of the ArkTS, object literals can be used in a -context where the class or interface type of the object literal can be -inferred as in the example above. Other valid cases are illustrated below: +Due to the static typing of the ArkTS, object literals can be used in a context where the class or interface type of the object literal can be inferred as in the example above. Other valid cases are illustrated below: ```typescript class C { @@ -1332,8 +1199,7 @@ let cc: C[] = [{n: 1, s: "a"}, {n: 2, s: "b"}] ### Object Literals of Record Type -The generic Record type is used to map the properties of a type -(Key type) to another type (Value type). +The generic Record type is used to map the properties of a type (Key type) to another type (Value type). A special form of object literal is used to initialize the value of such type: @@ -1361,11 +1227,9 @@ let map: Record = { # Interfaces -An interface declaration introduces a new type. Interfaces are a common way -of defining contracts between various part of codes. +An interface declaration introduces a new type. Interfaces are a common way of defining contracts between various part of codes. -Interfaces are used to write polymorphic code, which can be applied to any -class instances that implement a particular interface. +Interfaces are used to write polymorphic code, which can be applied to any class instances that implement a particular interface. An interface usually contains properties and method headers. @@ -1406,11 +1270,9 @@ class Rectangle implements Area { ## Interface Properties -An interface property can be in a form of field, getter, setter, or both -getter and setter. +An interface property can be in a form of field, getter, setter, or both getter and setter. -A property field is just a shortcut notation of a getter/setter pair, and -the following notations are equal: +A property field is just a shortcut notation of a getter/setter pair, and the following notations are equal: ```typescript interface Style { @@ -1463,8 +1325,7 @@ interface ExtendedStyle extends Style { } ``` -An extended interface contains all properties and methods of the -interface it extends, and can also add its own properties and methods. +An extended interface contains all properties and methods of the interface it extends, and can also add its own properties and methods. ## Interface Visibility Modifiers @@ -1474,13 +1335,11 @@ Only methods with default implementation can be defined as `private`. # Generic Types and Functions -Generic types and functions allow creating the code capable to work over a -variety of types rather than a single type. +Generic types and functions allow creating the code capable to work over a variety of types rather than a single type. ## Generic Classes and Interfaces -A class and an interface can be defined as generics, adding parameters to the -type definition, like the type parameter `Element` in the following example: +A class and an interface can be defined as generics, adding parameters to the type definition, like the type parameter `Element` in the following example: ```typescript class Stack { @@ -1510,9 +1369,7 @@ s.push(55) // That will be a compile-time error ## Generic Constraints -Type parameters of generic types can be bounded. For example, the `Key` -type parameter in the `HashMap` container must have a hash -method, i.e., it must be hashable. +Type parameters of generic types can be bounded. For example, the `Key` type parameter in the `HashMap` container must have a hash method, that is, it must be hashable. ```typescript interface Hashable { @@ -1526,13 +1383,11 @@ class HasMap { } ``` -In the above example, the `Key` type extends `Hashable`, and all methods -of `Hashable` interface can be called for keys. +In the above example, the `Key` type extends `Hashable`, and all methods of `Hashable` interface can be called for keys. ## Generic Functions -Use a generic function to create a more universal code. Consider a function -that returns the last element of the array: +Use a generic function to create a more universal code. Consider a function that returns the last element of the array: ```typescript function last(x: number[]): number { @@ -1541,8 +1396,7 @@ function last(x: number[]): number { console.log(last([1, 2, 3])) // output: 3 ``` -If the same function needs to be defined for any array, then define it as -a generic with a type parameter: +If the same function needs to be defined for any array, then define it as a generic with a type parameter: ```typescript function last(x: T[]): T { @@ -1566,10 +1420,8 @@ console.log(last([1, 2, 3])) ## Generic Defaults -Type parameters of generic types can have defaults. -It allows using just the generic type name instead of specifying the actual -type arguments. -Example below illustrates this for both classes and functions. +Type parameters of generic types can have defaults. It allows using just the generic type name instead of specifying the actual type arguments. +The example below illustrates this for both classes and functions. ```typescript class SomeType {} @@ -1589,10 +1441,8 @@ foo() # Null Safety -All types in ArkTS by default are non-nullable, so the value of a type -cannot be null. -It is similar to TypeScript behavior in strict null checking mode -(`strictNullChecks`), but the rules are stricter. +All types in ArkTS by default are non-nullable, so the value of a type cannot be null. +It is similar to TypeScript behavior in strict null checking mode (`strictNullChecks`), but the rules are stricter. In the example below, all lines cause a compile-time error: @@ -1615,8 +1465,7 @@ if (x != null) { /* do something */ } A postfix operator `!` can be used to assert that its operand is non-null. -If applied to a null value, the operator throws an error. Otherwise, the -type of the value is changed from `T | null` to `T`: +If applied to a null value, the operator throws an error. Otherwise, the type of the value is changed from `T | null` to `T`: ```typescript let x: number | null = 1 @@ -1627,15 +1476,12 @@ y = x! + 1 // ok ## Null-Coalescing Operator -The null-coalescing binary operator `??` checks whether the evaluation -of the left-hand-side expression is equal to null. -If it is, then the result of the expression is the right-hand-side expression; -otherwise, it is the left-hand-side expression. +The null-coalescing binary operator `??` checks whether the evaluation of the left-hand-side expression is equal to null. +If it is, then the result of the expression is the right-hand-side expression; otherwise, it is the left-hand-side expression. In other words, `a ?? b` equals the ternary operator `a != null ? a : b`. -In the following example, the method `getNick` returns a nickname if it is -set; otherwise, an empty string is returned: +In the following example, the method `getNick` returns a nickname if it is set; otherwise, an empty string is returned: ```typescript class Person { @@ -1649,8 +1495,7 @@ class Person { ## Optional Chaining -Optional chaining operator `?.` allows writing code where the evaluation -stops at an expression that is partially evaluated to `null` or `undefined`. +Optional chaining operator `?.` allows writing code where the evaluation stops at an expression that is partially evaluated to `null` or `undefined`. ```typescript class Person { @@ -1672,14 +1517,11 @@ class Person { } ``` -**Note**: the return type of `getSpouseNick` must be `string | null | undefined`, as -the method can return null or undefined. +**Note**: The return type of `getSpouseNick` must be `string | null | undefined`, as the method can return null or undefined. -An optional chain can be of any length and contain any number of `?.` -operators. +An optional chain can be of any length and contain any number of `?.` operators. -In the following sample, the output is a person’s spouse nickname if that -person has a spouse, and the spouse has a nickname. +In the following sample, the output is a person's spouse nickname if that person has a spouse, and the spouse has a nickname. Otherwise, the output is `undefined`: @@ -1702,19 +1544,15 @@ console.log(p.spouse?.nick) // print: undefined Programs are organized as sets of compilation units or modules. -Each module creates its own scope, i.e., any declarations (variables, -functions, classes, etc.) declared in the module are not visible outside -that module unless they are explicitly exported. +Each module creates its own scope, i.e., any declarations (variables, functions, classes, etc.) declared in the module are not visible outside that module unless they are explicitly exported. -Conversely, a variable, function, class, interface, etc. exported from -another module must first be imported to a module. +Conversely, a variable, function, class, interface, etc. exported from another module must first be imported to a module. ## Export A top-level declaration can be exported by using the keyword `export`. -A declared name that is not exported is considered private and can be used -only in the module where it is declared. +A declared name that is not exported is considered private and can be used only in the module where it is declared. ```typescript export class Point { @@ -1733,20 +1571,17 @@ export function Distance(p1: Point, p2: Point): number { ## Import -Import declarations are used to import entities exported from other modules -and provide their bindings in the current module. An import declaration -consists of two parts: +Import declarations are used to import entities exported from other modules and provide their bindings in the current module. +An import declaration consists of two parts: -* Import path that determines the module to import from; -* Import bindings that define the set of usable entities in the imported - module, and the form of use (i.e., qualified or unqualified use). +* Import path that determines the module to import from. +* Import bindings that define the set of usable entities in the imported module, and the form of use (i.e., qualified or unqualified use). Import bindings may have several forms. -Let’s assume a module has the path ‘./utils’ and export entities ‘X’ and ‘Y’. +Let's assume a module has the path './utils' and export entities 'X' and 'Y'. -An import binding of the form `* as A` binds the name ‘A’, and all entities -exported from the module defined by the import path can be accessed by using +An import binding of the form `* as A` binds the name 'A', and all entities exported from the module defined by the import path can be accessed by using the qualified name `A.name`: ```typescript @@ -1755,8 +1590,7 @@ Utils.X // denotes X from Utils Utils.Y // denotes Y from Utils ``` -An import binding of the form `{ ident1, ..., identN }` binds an exported -entity with a specified name, which can be used as a simple name: +An import binding of the form `{ ident1, ..., identN }` binds an exported entity with a specified name, which can be used as a simple name: ```typescript import { X, Y } from "./utils" @@ -1764,8 +1598,7 @@ X // denotes X from Utils Y // denotes Y from Utils ``` -If a list of identifiers contains aliasing of the form `ident as alias`, -then entity `ident` is bound under the name `alias`: +If a list of identifiers contains aliasing of the form `ident as alias`, then entity `ident` is bound under the name `alias`: ```typescript import { X as Z, Y } from "./utils" @@ -1778,17 +1611,13 @@ X // Compile-time error: 'X' is not visible A module can contain any statements at the module level, except `return` ones. -If a module contains a `main` function (program entry point), then -top-level statements of the module are executed immediately before -the body of this function. -Otherwise, they are executed before execution of any other function -of the module. +If a module contains a `main` function (program entry point), then top-level statements of the module are executed immediately before the body of this function. +Otherwise, they are executed before execution of any other function of the module. ## Program Entry Point An entry point of a program (application) is the top-level `main` function. -The `main` function must have either an empty parameter list or a single -parameter of `string[]` type. +The `main` function must have either an empty parameter list or a single parameter of `string[]` type. ```typescript function main() { @@ -1798,18 +1627,11 @@ function main() { # Support for ArkUI -This section demonstrates mechanisms that ArkTS provides for -creating graphical user interface (GUI) programs. The section is based on -the ArkUI declarative framework. ArkUI provides a set of extensions of -the standard TypeScript to declaratively describe the GUI of the applications -and the interaction between the GUI components. +This section demonstrates mechanisms that ArkTS provides for creating graphical user interface (GUI) programs. The section is based on the ArkUI declarative framework. ArkUI provides a set of extensions of the standard TypeScript to declaratively describe the GUI of the applications and the interaction between the GUI components. ## ArkUI Example -The following example provides a complete ArkUI-based application as an -illustration of GUI programming capabilities. For more details of the -ArkUI features, refer to the ArkUI -[tutorial](arkts-get-started.md). +The following example provides a complete ArkUI-based application as an illustration of GUI programming capabilities. For more details of the ArkUI features, refer to the ArkUI [tutorial](arkts-get-started.md). ```typescript // ViewModel classes --------------------------- @@ -1990,7 +1812,7 @@ struct PersonEditView { // delete found contact this.addrBook.contacts.splice(index, 1) - // determin new selectedPerson + // determine new selectedPerson index = (index < this.addrBook.contacts.length) ? index : index - 1 diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index b6e4a864d4dce6a991c6aa148fc7e45cf5bf002a..a0990b276e19ef44bbf2f93d76f51a90552fe374 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -97,6 +97,7 @@ As shown above, the **module.json5** file contains several tags. | isolationMode | Multi-process configuration of the module. The options are as follows:
- **nonisolationFirst**: The module preferentially runs in a non-independent process.
- **isolationFirst**: The module preferentially runs in an independent process.
- **isolationOnly**: The module runs only in an independent process.
- **nonisolationOnly**: The module runs only in non-independent processes.|String|Yes (initial value: **nonisolationFirst**)| | generateBuildHash |Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.
This tag is enabled only when the **generateBuildHash** tag in the [app.json5](./app-configuration-file.md) file is **false**.**
**NOTE**
This tag applies only to system applications.**|Boolean|Yes (initial value: **false**)| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.
- **true**: The **libs** libraries are packaged in the HAP file after being compressed.
- **false**: The **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **true**)| +| libIsolation | Whether to save the .so files of the current HAP to a separate folder (named after the module) in the **libs** directory. This is intended to avoid .so file conflicts between HAPs.
- **true**: The .so files of the current HAP are stored in a separate folder (named after the module) in the **libs** directory.
- **false**: The .so files of the current HAP are directly stored in the **libs** directory.| Boolean| Yes (initial value: **false**)| ## deviceTypes diff --git a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md index eb3a47adb6545ddb001689b8374b206703a0b9b3..29865c79c490f4ad1678034e001b71e1011f1ab3 100644 --- a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md +++ b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md @@ -779,7 +779,9 @@ interface Employee extends Identity, Contact {} **Severity: error** -ArkTS does not support the returning `this` type. Use explicit type instead. +ArkTS does not support type notation using the `this` keyword (for example, +specifying a method's return type `this` is not allowed). Use explicit type +instead. **TypeScript** @@ -959,7 +961,9 @@ type N = number **Severity: error** ArkTS does not support indexed access for class fields. Use dot notation -instead. +instead. An exception are all typed arrays from the standard library +(for example, `Int32Array`), which support access to their elements through +`container[index]` syntax. **TypeScript** @@ -975,6 +979,9 @@ let x = p["x"] class Point {x: number = 0; y: number = 0} let p: Point = {x: 1, y: 2} let x = p.x + +let arr = new Int32Array(1) +console.log(arr[0]) ``` ## Recipe: Structural identity is not supported @@ -1541,33 +1548,6 @@ let a2: C[] = [{n: 1, s: "1"}, {n: 2, s : "2"}] // ditto * Recipe: Object literal must correspond to some explicitly declared class or interface * Recipe: Object literals cannot be used as type declarations -## Recipe: Lambdas require explicit type annotation for parameters - -**Rule `arkts-explicit-param-types-in-lambdas`** - -**Severity: error** - -Currently, ArkTS requires the types of lambda parameters -to be explicitly specified. - -**TypeScript** - -```typescript -// Compile-time error only with noImplicitAny: -let f = (s /* type any is assumed */) => { - console.log(s) -} -``` - -**ArkTS** - -```typescript -// Explicit types for lambda parameters are mandatory: -let f = (s: string) => { - console.log(s) -} -``` - ## Recipe: Use arrow functions instead of function expressions **Rule `arkts-no-func-expressions`** @@ -1989,9 +1969,9 @@ let f = "string" + true // "stringtrue" let g = (new Object()) + "string" // "[object Object]string" -let i = true + true // JS: 2, TS: compile-time error -let j = true + 2 // JS: 3, TS: compile-time error -let k = E.E1 + true // JS: 1, TS: compile-time error +let i = true + true // compile-time error +let j = true + 2 // compile-time error +let k = E.E1 + true // compile-time error ``` **ArkTS** @@ -2011,7 +1991,7 @@ let g = (new Object()).toString() + "string" let i = true + true // compile-time error -let j = true + 2 // compile-time error +let j = true + 2 // compile-time error let k = E.E1 + true // compile-time error ``` @@ -2341,7 +2321,8 @@ iterate over data. **Severity: error** ArkTS supports the iteration over arrays and strings by the `for .. of` loop, -but does not support the iteration of objects content. +but does not support the iteration of objects content. All typed arrays from +the standard library (for example, `Int32Array`) are also supported. **TypeScript** @@ -2433,7 +2414,8 @@ console.log("Area: ", Math.PI * r * r) **Severity: error** -ArkTS supports `case` statements that contain only compile-time values. +ArkTS supports `case` statements that contain only compile-time values, +top-level scope `const` values, and `static readonly` class fields. Use `if` statements as an alternative. **TypeScript** @@ -2907,7 +2889,8 @@ function main(): void { The only supported scenario for the spread operator is to spread an array into the rest parameter. Otherwise, manually “unpack” data from arrays and objects, -where necessary. +where necessary. All typed arrays from the standard library (for example, +`Int32Array`) are also supported. **TypeScript** @@ -3880,34 +3863,6 @@ let ce = new CustomError() * Recipe: Prototype assignment is not supported -## Recipe: Runtime import expressions are not supported - -**Rule `arkts-no-runtime-import`** - -**Severity: error** - -ArkTS does not support such “runtime” import expressions as `await import...` -because in the language import is a compile-time, not a runtime feature. -Use regular import syntax instead. - -**TypeScript** - -```typescript -const zipUtil = await import("utils/create-zip-file") -``` - -**ArkTS** - -```typescript -import { zipUtil } from "utils/create-zip-file" -``` - -**See also** - -* Recipe: Wildcards in module names are not supported -* Recipe: Universal module definitions (UMD) are not supported -* Recipe: Import assertions are not supported - ## Recipe: Definite assignment assertions are not supported **Rule `arkts-no-definite-assignment`** @@ -4065,8 +4020,7 @@ M.abc = 200 **Severity: error** Currently ArkTS does not support utility types from TypeScript extensions to the -standard library (`Omit`, `Pick`, etc.). Exceptions are: `Partial`, -`Record`. +standard library, except following: `Partial`, `Record`. For the type *Record*, the type of an indexing expression *rec[index]* is of the type *V | undefined*. @@ -4349,7 +4303,6 @@ import { something } from "module" * Recipe: Wildcards in module names are not supported * Recipe: Universal module definitions (UMD) are not supported -* Recipe: Runtime import expressions are not supported ## Recipe: Usage of standard library is restricted @@ -4364,9 +4317,7 @@ the following APIs is prohibited: Properties and functions of the global object: `eval`, `Infinity`, `NaN`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`, -`encodeURI`, `encodeURIComponent`, `Encode`, -`decodeURI`, `decodeURIComponent`, `Decode`, -`escape`, `unescape`, `ParseHexOctet` +`Encode`, `Decode`, `ParseHexOctet` `Object`: `__proto__`, `__defineGetter__`, `__defineSetter__`, `__lookupGetter__`, `__lookupSetter__`, `assign`, `create`, @@ -4561,3 +4512,54 @@ class BugReport { } ``` +## Recipe: Classes cannot be used as objects + +**Rule `arkts-no-classes-as-obj`** + +**Severity: error** + +ArkTS does not support using classes as objects (assigning them to variables, +etc.) because in ArkTS, a `class` declaration introduces a new type, +not a value. + +**TypeScript** + +```typescript +class C { + s: string = "" + n: number = 0 +} + +let c = C +``` + +## Recipe: `import` statements after other statements are not allowed + +**Rule `arkts-no-misplaced-imports`** + +**Severity: error** + +In ArkTS, all `import` statements should go before all other statements +in the program. + +**TypeScript** + +```typescript +class C { + s: string = "" + n: number = 0 +} + +import foo from "module1" +``` + +**ArkTS** + +```typescript +import foo from "module1" + +class C { + s: string = "" + n: number = 0 +} +``` diff --git a/en/application-dev/reference/apis/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-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index b717abf0ad082e4ea7586cc8713596a08e7b3740..de2f146c7226f3a1ef3d61dad588c84b6cc2a1ab 100644 --- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -1,15 +1,13 @@ # @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks) -The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling. - -When developing an application, you can override the APIs of this module and add your own task logic to the APIs. +The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling. You can override the APIs provided by this module. When a deferred task is triggered, the system calls back the application through the APIs and processes the task logic in the callback. > **NOTE** > > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > - The APIs of this module can be used only in the stage model. - ## Modules to Import ```ts @@ -36,7 +34,7 @@ Called when the system starts scheduling the deferred task. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | -------------- | -| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.| +| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that starts.| **Example** @@ -60,7 +58,7 @@ Called when the system stops scheduling the deferred task. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | -------------- | -| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.| +| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that stops.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md index 39a7d2b1ec4699882f2155420b5071b0e8ad73a2..274fda648f730e68ab89177cd86f1ce500a737f6 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -66,11 +66,14 @@ import fs from '@ohos.file.fs'; try { let fd = fs.openSync('/path/to/form.png'); - let obj = { - 'temperature': '21°', - 'formImages': { 'image': fd } - }; - formBindingData.createFormBindingData(obj); + + let createFormBindingDataParam = new Map() + let formImagesParam = new Map() + formImagesParam.set('image', fd) + createFormBindingDataParam.set("name", '21°') + createFormBindingDataParam.set('formImages', formImagesParam) + + formBindingData.createFormBindingData(createFormBindingDataParam); } catch (error) { console.error(`catch error, code: ${error.code}, message: ${error.message}`); } diff --git a/en/application-dev/reference/apis/js-apis-arkui-UIContext.md b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md index 946463e335769b047494f0ed5b85ddbb911b3490..24fa265ba8dc81bd16b27f9538b056132205207b 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-UIContext.md +++ b/en/application-dev/reference/apis/js-apis-arkui-UIContext.md @@ -214,7 +214,7 @@ struct AnimateToExample { ### showAlertDialog -showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons): void +showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void Shows an alert dialog box. @@ -224,7 +224,8 @@ Shows an alert dialog box. | Name | Type | Mandatory| Description| | ---- | --------------- | -------- | -------- | -| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons) | Yes| Defines and displays the **\** component.| +| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons) \| [AlertDialogParamWithOptions](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithoptions10) | Yes| Defines and displays the **\** component.| + **Example** @@ -579,7 +580,7 @@ Obtains information about a system font based on the font name. | Type | Description | | ------------------------------------ | -------------- | -| [FontInfo](js-apis-font.md#fontinfo) | Information about the system font.| +| [FontInfo](js-apis-font.md#fontinfo10) | Information about the system font.| **Example** @@ -1201,7 +1202,7 @@ try { ### pushNamedRoute -pushNamedRoute(options: router.NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void +pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void Navigates to a page using the named route. This API uses a promise to return the result. @@ -1361,7 +1362,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found, only throw in standard system. | +| 100001 | if can not get the delegate, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** @@ -1425,7 +1426,7 @@ router.replaceNamedRoute({ ### back -back(options: router.RouterOptions ): void +back(options?: router.RouterOptions ): void Returns to the previous page or a specified page. @@ -1435,7 +1436,7 @@ Returns to the previous page or a specified page. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.| +| options | [router.RouterOptions](js-apis-router.md#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.| **Example** @@ -1618,7 +1619,7 @@ try { ### showDialog -showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse<): void +showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void Shows a dialog box. This API uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-arkui-componentUtils.md b/en/application-dev/reference/apis/js-apis-arkui-componentUtils.md index 7dd3cbb5a41f2bb4b6cbb401cd6f90c0d77d39e9..3ab626a5cdce1298a8c7de73ef8a2d392f909dde 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-componentUtils.md +++ b/en/application-dev/reference/apis/js-apis-arkui-componentUtils.md @@ -62,8 +62,8 @@ let modePosition = componentUtils.getRectangleById("onClick"); | Name | Type| Mandatory| Description | | -------- | ---- | ----------------------------------| ----------------------------------| -| width | number | Yes| Component width. | -| height | number | Yes| Component height. | +| width | number | Yes| Component width.
Unit: px | +| height | number | Yes| Component height.
Unit: px | ### Offset @@ -71,8 +71,8 @@ let modePosition = componentUtils.getRectangleById("onClick"); | Name | Type| Mandatory| Description | | --------| ---- | -----------------------------------| -----------------------------------| -| x | number | Yes| X coordinate. | -| y | number | Yes| Y coordinate. | +| x | number | Yes| X coordinate.
Unit: px | +| y | number | Yes| Y coordinate.
Unit: px | ### TranslateResult @@ -80,9 +80,9 @@ let modePosition = componentUtils.getRectangleById("onClick"); | Name | Type| Mandatory| Description | | --------| ---- | -----------------------------------| -----------------------------------| -| x | number | Yes| Translation distance along the x-axis. | -| y | number | Yes| Translation distance along the y-axis. | -| z | number | Yes| Translation distance along the z-axis. | +| x | number | Yes| Translation distance along the x-axis.
Unit: px | +| y | number | Yes| Translation distance along the y-axis.
Unit: px | +| z | number | Yes| Translation distance along the z-axis.
Unit: px | ### ScaleResult @@ -90,11 +90,11 @@ let modePosition = componentUtils.getRectangleById("onClick"); | Name | Type| Mandatory| Description | | --------| ---- | -----------------------------------| -----------------------------------| -| x | number | Yes| Scale factor along the x-axis. | -| y | number | Yes| Scale factor along the y-axis. | -| z | number | Yes| Scale factor along the z-axis. | -| centerX | number | Yes| X coordinate of the center point. | -| centerY | number | Yes| Y coordinate of the center point. | +| x | number | Yes| Scale factor along the x-axis.
Unit: px | +| y | number | Yes| Scale factor along the y-axis.
Unit: px | +| z | number | Yes| Scale factor along the z-axis.
Unit: px | +| centerX | number | Yes| X coordinate of the center point.
Unit: px | +| centerY | number | Yes| Y coordinate of the center point.
Unit: px | ### RotateResult @@ -102,12 +102,12 @@ let modePosition = componentUtils.getRectangleById("onClick"); | Name | Type| Mandatory| Description | | --------| ---- | -----------------------------------| -----------------------------------| -| x | number | Yes| X coordinate of the rotation vector. | -| y | number | Yes| Y coordinate of the rotation vector. | -| z | number | Yes| Z coordinate of the rotation vector. | -| angle | number | Yes| Rotation angle. | -| centerX | number | Yes| X coordinate of the center point. | -| centerY | number | Yes| Y coordinate of the center point. | +| x | number | Yes| X coordinate of the rotation vector.
Unit: px | +| y | number | Yes| Y coordinate of the rotation vector.
Unit: px | +| z | number | Yes| Z coordinate of the rotation vector.
Unit: px | +| angle | number | Yes| Rotation angle.
Unit: px | +| centerX | number | Yes| X coordinate of the center point.
Unit: px | +| centerY | number | Yes| Y coordinate of the center point.
Unit: px | ### Matrix4Result @@ -115,7 +115,7 @@ let modePosition = componentUtils.getRectangleById("onClick"); | Value Range | Description | | --------| -----------------------------------| -| [number,number,number,number,
number,number,number,number,
number,number,number,number,
number,number,number,number] | A number array whose length is 16 (4 x 4). For details, see **4 x 4 matrix description**.| +| [number,number,number,number,
number,number,number,number,
number,number,number,number,
number,number,number,number] | A number array whose length is 16 (4 x 4). The unit is px. For details, see **4 x 4 matrix description**. | **4 x 4 matrix description** diff --git a/en/application-dev/reference/apis/js-apis-arkui-dragController.md b/en/application-dev/reference/apis/js-apis-arkui-dragController.md index 8c4292fc30bf74109f0d76728543b368f1e1ef4d..7cfc9a9de30b4ade9848903448e82b46d4462dc1 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-dragController.md +++ b/en/application-dev/reference/apis/js-apis-arkui-dragController.md @@ -63,9 +63,9 @@ struct DragControllerPage { extraParams: '' } dragController.executeDrag(this.DraggingBuilder.bind(this), dragInfo, (err, {event, extraParams}) => { - if (event.getResult() == DragRet.DRAG_SUCCESS) { + if (event.getResult() == DragResult.DRAG_SUCCESSFUL) { // ... - } else if (event.getResult() == DragRet.DRAG_FAILED) { + } else if (event.getResult() == DragResult.DRAG_FAILED) { // ... } }) @@ -151,9 +151,9 @@ struct DragControllerPage { dragController.executeDrag(dragItemInfo, dragInfo) .then(({event, extraParams}) => { - if (event.getResult() == DragRet.DRAG_SUCCESS) { + if (event.getResult() == DragResult.DRAG_SUCCESSFUL) { // ... - } else if (event.getResult() == DragRet.DRAG_FAILED) { + } else if (event.getResult() == DragResult.DRAG_FAILED) { // ... } }) diff --git a/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md index 60a21b51554ccf04399842de7a6272e03fdbd2a5..818d35f722a41276b4f00fca2f195875f8b9e614 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md +++ b/en/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @@ -141,7 +141,7 @@ Obtains the **DrawableDescriptor** object of the background. **Example** ```ts let resManager = getContext().resourceManager -drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon') +let drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon') .id))).getBackground(); ``` 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-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 5a4af7f39f321fc486a4e359b567666dc359135a..ff3fb9a3d6af1c9ab3250d892ad729dabb5220ad 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -12,6 +12,8 @@ The **CommonEvent** module provides common event capabilities, including the cap ```ts import CommonEvent from '@ohos.commonEvent'; +import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; ``` ## Support @@ -43,7 +45,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publish failed, code is ${err.code}`); } else { @@ -80,14 +82,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event. + data: "initial data",// Result data of the common event. isOrdered: true // The common event is an ordered one. } // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publish failed, code is ${err.code}`); } else { @@ -125,7 +127,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publishAsUser failed, code is ${err.code}`); } else { @@ -168,13 +170,13 @@ Publishes a common event with given attributes to a specific user. This API uses ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. data: "initial data",// Result data of the common event. } // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err.code) { console.error(`publishAsUser failed, code is ${err.code}`); } else { @@ -212,15 +214,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { - events: ["event"] +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { + events: ["event"] }; // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -259,18 +261,18 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { +CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`createSubscriber failed, code is ${err.code}`); }); ``` @@ -297,15 +299,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err.code) { console.error(`subscribe failed, code is ${err.code}`); } else { @@ -314,7 +316,7 @@ function subscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -351,15 +353,15 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err.code) { console.error(`subscribe failed, code is ${err.code}`); } else { @@ -368,7 +370,7 @@ function subscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -380,7 +382,7 @@ function createCB(err, commonEventSubscriber) { } // Callback for common event unsubscription. -function unsubscribeCB(err) { +function unsubscribeCB(err:Base.BusinessError) { if (err.code) { console.error(`unsubscribe failed, code is ${err.code}`); } else { diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md index 61d22613c35ceb0556ab66748f635c3e92c7b412..070fee6a9381edfea0ceaf7758b01f41a137b861 100644 --- a/en/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -10,6 +10,7 @@ The **CommonEventManager** module provides common event capabilities, including ```ts import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; ``` ## Support @@ -48,7 +49,7 @@ Publishes a common event and executes an asynchronous callback after the event i ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { @@ -95,14 +96,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. data: "initial data",// Result data of the common event. isOrdered: true // The common event is an ordered one. } // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { @@ -151,7 +152,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ```ts // Callback for common event publication -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { @@ -205,13 +206,13 @@ Publishes a common event with given attributes to a specific user. This API uses ```ts // Attributes of a common event. -let options = { +let options:CommonEventManager.CommonEventPublishData = { code: 0, // Result code of the common event. data: "initial data",// Result data of the common event. } // Callback for common event publication. -function publishCB(err) { +function publishCB(err:Base.BusinessError) { if (err) { console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { @@ -248,15 +249,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if(!err) { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -295,18 +296,18 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Create a subscriber. -CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { +CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); }); @@ -341,15 +342,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th ```ts // Subscriber information. -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function SubscribeCB(err, data) { +function SubscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err) { console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -358,7 +359,7 @@ function SubscribeCB(err, data) { } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if(!err) { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -409,13 +410,13 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur **Example** ```ts -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function subscribeCB(err, data) { +function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) { if (err) { console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -423,7 +424,7 @@ function subscribeCB(err, data) { } } // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err) { console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } else { @@ -438,7 +439,7 @@ function createCB(err, commonEventSubscriber) { } } // Callback for common event unsubscription. -function unsubscribeCB(err) { +function unsubscribeCB(err:Base.BusinessError) { if (err) { console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } else { @@ -493,7 +494,7 @@ Removes a sticky common event. This API uses an asynchronous callback to return ```ts -CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => { +CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => { if (err) { console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); return; @@ -542,7 +543,7 @@ Removes a sticky common event. This API uses a promise to return the result. ```ts CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => { console.info(`Remove sticky event AsyncCallback success`); -}).catch ((err) => { +}).catch ((err:Base.BusinessError) => { console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); }); ``` @@ -577,7 +578,7 @@ Enables or disables static subscription for the current application. This API us ```ts -CommonEventManager.setStaticSubscriberState(true, (err) => { +CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => { if (!err) { console.info(`Set static subscriber state callback failed, err is null.`); return; @@ -627,7 +628,7 @@ Enables or disables static subscription for the current application. This API us ```ts CommonEventManager.setStaticSubscriberState(false).then(() => { console.info(`Set static subscriber state promise success`); -}).catch ((err) => { +}).catch ((err:Base.BusinessError) => { console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md index ffc902f8eda9f2a5d5d0c55a4f6b6ceeabc1c031..6c47da8d85af191fdc7fc4fca312906f97c49d26 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -316,7 +316,7 @@ Since API version 9, this API is supported in ArkTS widgets. ```ts import Curves from '@ohos.curves' -let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. +let curveValue = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. ``` diff --git a/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md index 737c91f0036c5217469a254aaad8974913eed1d9..bae8a5884f39618b18c4ed00d60ed3c6fa432b9e 100644 --- a/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md +++ b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md @@ -4,9 +4,9 @@ The **cooperate** module implements screen hopping for two or more networked dev > **NOTE** > -> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - The APIs provided by this module are system APIs. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -26,7 +26,7 @@ Prepares for screen hopping. This API uses an asynchronous callback to return th | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | --------------------------- | -| callback | AsyncCallback<void> | Yes|Callback used to return the result. | +| callback | AsyncCallback<void> | Yes|Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | **Example** @@ -56,7 +56,7 @@ Prepares for screen hopping. This API uses a promise to return the result. | Parameters | Description | | ------------------- | ------------------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| @@ -75,7 +75,6 @@ try { ``` - ## cooperate.unprepare unprepare(callback: AsyncCallback<void>): void; @@ -86,7 +85,7 @@ Cancels the preparation for screen hopping. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------ | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -104,8 +103,6 @@ try { } ``` - - ## cooperate.unprepare unprepare(): Promise<void>; @@ -118,7 +115,7 @@ Cancels the preparation for screen hopping. This API uses a promise to return th | Parameters | Description | | ------------------- | --------------------------------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| ```js try { @@ -133,7 +130,6 @@ try { ``` - ## cooperate.activate activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback<void>): void; @@ -148,7 +144,7 @@ Starts screen hopping. This API uses an asynchronous callback to return the resu | -------- | ---------------------------- | ---- | ---------------------------- | | targetNetworkId | string | Yes | Descriptor of the target device for screen hopping. | | inputDeviceId | number | Yes | Identifier of the input device for screen hopping.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -156,7 +152,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode | ID| Error Message| | -------- | ---------------------------------------- | -| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. | +| 20900001 | Operation failed.| **Example** @@ -197,7 +193,7 @@ Starts screen hopping. This API uses a promise to return the result. | Name | Description | | ---------------------- | ------------------------------- | -| Promise<void> | Promise used to return the result. | +| Promise<void> | Promise that returns no value. | **Error codes** @@ -205,7 +201,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode | ID| Error Message| | -------- | ---------------------------------------- | -| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. | +| 20900001 | Operation failed. | **Example** @@ -235,8 +231,8 @@ Stops screen hopping. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory | Description | | -------- | ---------------------------- | ---- | ---------------------------- | -| isUnchained | boolean | Yes| Whether to disable the cross-device link.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| isUnchained | boolean | Yes| Whether to disable the cross-device link.
The value **true** means to disable the cross-device link, and the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -268,7 +264,7 @@ Stops screen hopping. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------- | ------- | ---- | ------------------ | -| isUnchained | boolean | Yes | Whether to disable the cross-device link.| +| isUnchained | boolean | Yes | Whether to disable the cross-device link.
The value **true** means to disable the cross-device link, and the value **false** means the opposite.| @@ -276,7 +272,7 @@ Stops screen hopping. This API uses a promise to return the result. | Name | Description | | -------- | ---------------------------- | -| Promise<void> | Promise used to return the result. | +| Promise<void> | Promise that returns no value. | @@ -307,7 +303,7 @@ Obtains the screen hopping status of the target device. This API uses an asynchr | Name | Type | Mandatory | Description | | -------- | --------- | ---- | ---------------------------- | | networkId | string | Yes | Descriptor of the target device for screen hopping. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.| **Example** @@ -336,9 +332,9 @@ Obtains the screen hopping status of the target device. This API uses a promise **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------- | ---- | ---------------------------- | -| networkId | string | Yes | Descriptor of the target device for screen hopping. | +| Name | Type | Mandatory | Description | +| -------- | --------- | ---- | ---------------------------- | +| networkId | string | Yes | Descriptor of the target device for screen hopping. | @@ -346,7 +342,7 @@ Obtains the screen hopping status of the target device. This API uses a promise | Parameters | Description | | ------------------- | ------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.| diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md index 93e460019144b0e321b1f39b4c41a37f9c908d37..ddc6fb296b8e88bd3866696cb7a0e409918c7745 100644 --- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -1,6 +1,6 @@ # @ohos.distributedMissionManager (Distributed Mission Management) -The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device. +The **distributedMissionManager** module implements mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device by mission ID or bundle name. > **NOTE** > @@ -14,7 +14,6 @@ The **distributedMissionManager** module implements system mission management ac import distributedMissionManager from '@ohos.distributedMissionManager' ``` - ## distributedMissionManager.registerMissionListener registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback, callback: AsyncCallback<void>): void; @@ -30,8 +29,8 @@ Registers a mission status listener. This API uses an asynchronous callback to r | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | --------- | | parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for.| -| options | [MissionCallback](#missioncallback) | Yes | Callback to register. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| options | [MissionCallback](#missioncallback) | Yes | Callback to register.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the listener is registered, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -80,14 +79,14 @@ Registers a mission status listener. This API uses a promise to return the resul | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------- | -| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | +| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | | options | MissionCallback | Yes | Callback to register.| **Return value** | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -123,7 +122,6 @@ Registers a mission status listener. This API uses a promise to return the resul } ``` - ## distributedMissionManager.unRegisterMissionListener unRegisterMissionListener(parameter: MissionDeviceInfo, callback: AsyncCallback<void>): void; @@ -138,8 +136,8 @@ Deregisters a mission status listener. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | --------- | -| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the listener is deregistered, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -159,7 +157,6 @@ Deregisters a mission status listener. This API uses an asynchronous callback to } ``` - ## distributedMissionManager.unRegisterMissionListener unRegisterMissionListener(parameter: MissionDeviceInfo): Promise<void> @@ -180,7 +177,7 @@ Deregisters a mission status listener. This API uses a promise to return the res | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -215,7 +212,7 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | --------- | ------------------------------------- | ---- | --------- | | parameter | [MissionParameter](#missionparameter) | Yes | Parameters required for synchronization. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the synchronization is started, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -257,7 +254,7 @@ Starts to synchronize the remote mission list. This API uses a promise to return | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -294,7 +291,7 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | --------- | | parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Parameters required for synchronization. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the synchronization is stopped, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -334,7 +331,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -358,7 +355,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callback: AsyncCallback<void>): void; -Continues a mission on a remote device. This API uses an asynchronous callback to return the result. +Continues a mission on a remote device, with the mission ID specified. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC @@ -370,7 +367,7 @@ Continues a mission on a remote device. This API uses an asynchronous callback t | --------- | --------------------------------------- | ---- | ----- | | parameter | [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.| | options | [ContinueCallback](js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -416,7 +413,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promise<void> -Continues a mission on a remote device. This API uses a promise to return the result. +Continues a mission on a remote device, with the mission ID specified. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC @@ -433,7 +430,7 @@ Continues a mission on a remote device. This API uses a promise to return the re | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Error codes** @@ -490,7 +487,7 @@ Continues a mission on a remote device, with the bundle name specified. This API | Name | Type | Mandatory | Description | | --------- | --------------------------------------- | ---- | ----- | | parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the mission continuation is complete.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -546,7 +543,7 @@ Continues a mission on a remote device, with the bundle name specified. This API | Type | Description | | ------------------- | ---------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Error codes** @@ -586,7 +583,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er on(type: 'continueStateChange', callback: Callback<{ state: ContinueState, info: ContinuableInfo }>): void -Registers a listener for the mission continuation state of the current application. +Subscribes to continuation state change events of the current mission. **Required permissions**: ohos.permission.MANAGE_MISSIONS @@ -596,8 +593,8 @@ Registers a listener for the mission continuation state of the current applicati | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------- | -| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. | -| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | Yes | Callback used to return the mission continuation state and information. | +| type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. | +| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | Yes | Callback used to return the continuation state and information of the current mission. | **Example** @@ -615,7 +612,7 @@ Registers a listener for the mission continuation state of the current applicati off(type: 'continueStateChange', callback?: Callback<{ state: ContinueState, info: ContinuableInfo }>): void -Deregisters a listener for the mission continuation state of the current application. +Unsubscribes from continuation state change events of the current mission. **Required permissions**: ohos.permission.MANAGE_MISSIONS @@ -625,8 +622,8 @@ Deregisters a listener for the mission continuation state of the current applica | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------- | -| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. | -| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | No | Callback used for the listener to be deregistered. | +| type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. | +| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | No | Callback used to return the continuation state and information of the current mission.
If the callback is unspecified, all subscriptions to the specified event are canceled. | **Example** @@ -688,5 +685,5 @@ Enumerates the mission continuation states. | Name | Value | Description | | ------------- | --------- | ------------------------------------------------------------ | -| ACTIVE | 0 | Mission continuation is activated for the current application. | -| INACTIVE | 1 | Mission continuation is not activated for the current application. | +| ACTIVE | 0 | Continuation is activated for the current mission. | +| INACTIVE | 1 | Continuation is not activated for the current mission. | 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-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index e2ff3f6fa98d46577475cdaa86222b0eb3522b1f..ed0fdfc9c2f1a1d9e58683f19d11f7d2e9194f48 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -4,7 +4,7 @@ The **hiAppEvent** module provides the application event logging functions, such > **NOTE** > -> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead. +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md). > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -20,7 +20,7 @@ Before using application event logging, you need to understand the requirements **Event Name** -An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_). +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_). **Event Type** @@ -30,8 +30,8 @@ An event type is an enumerated value of [EventType](#eventtype). An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: -- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_). -- The parameter value can be of the string, number, boolean, or array type. +- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_). +- A parameter value can be of the string, number, boolean, or array type. - If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. - If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. - If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. @@ -156,12 +156,12 @@ Provides the configuration items for application event logging. | Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------------------------------------ | | disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.| -| maxStorage | string | No | Maximum size of the event file storage directory. The default value is 10M. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.| +| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.| ## EventType -Enumerates event types. +Enumerates the event types. **System capability**: SystemCapability.HiviewDFX.HiAppEvent diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md index 03cad26cfecb5295b611d48fbc9f69862895ddb0..41d5566ed0ffaa6a9327f3da04e2c92c6a31465b 100644 --- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -122,10 +122,10 @@ Defines parameters for an **AppEventInfo** object. | Name | Type | Mandatory| Description | | --------- | ----------------------- | ---- | ------------------------------------------------------------ | -| domain | string | Yes | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).| -| name | string | Yes | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).| +| domain | string | Yes | Event domain. The value is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).| +| name | string | Yes | Event name. The value is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).| | eventType | [EventType](#eventtype) | Yes | Event type. | -| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:
- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).
- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.| +| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:
- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).
- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.| ## hiAppEvent.configure @@ -436,7 +436,7 @@ hiAppEvent.clearData(); ## EventType -Enumerates event types. +Enumerates the event types. **System capability**: SystemCapability.HiviewDFX.HiAppEvent diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 50069e993211374ce83715a18f42f6bae26d2895..6f8d2c742f12ebd5d32855d72548266abc308160 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -86,7 +86,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req | Type | Description | | :---------- | :----------------------------------------------------------- | -| HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.| +| HttpRequest | An **HttpRequest** object, which contains the **request**, **requestInStream**, **destroy**, **on**, or **off** method.| **Example** @@ -364,9 +364,9 @@ Destroys an HTTP request. httpRequest.destroy(); ``` -### request210+ +### requestInStream10+ -request2(url: string, callback: AsyncCallback\): void +requestInStream(url: string, callback: AsyncCallback\): void Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. @@ -424,18 +424,18 @@ Initiates an HTTP request containing specified options to a given URL. This API **Example** ```js -httpRequest.request2("EXAMPLE_URL", (err, data) => { +httpRequest.requestInStream("EXAMPLE_URL", (err, data) => { if (!err) { - console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); + console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); } else { - console.info("request2 ERROR : err = " + JSON.stringify(err)); + console.info("requestInStream ERROR : err = " + JSON.stringify(err)); } }) ``` -### request210+ +### requestInStream10+ -request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void +requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response. @@ -494,7 +494,7 @@ Initiates an HTTP request containing specified options to a given URL. This API **Example** ```js -httpRequest.request2("EXAMPLE_URL", +httpRequest.requestInStream("EXAMPLE_URL", { method: http.RequestMethod.GET, header: { @@ -504,16 +504,16 @@ httpRequest.request2("EXAMPLE_URL", connectTimeout: 60000 }, (err, data) => { if (!err) { - console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); + console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); } else { - console.info("request2 ERROR : err = " + JSON.stringify(err)); + console.info("requestInStream ERROR : err = " + JSON.stringify(err)); } }) ``` -### request210+ +### requestInStream10+ -request2(url: string, options? : HttpRequestOptions): Promise\ +requestInStream(url: string, options? : HttpRequestOptions): Promise\ Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response. @@ -577,7 +577,7 @@ Initiates an HTTP request containing specified options to a given URL. This API **Example** ```js -let promise = httpRequest.request2("EXAMPLE_URL", { +let promise = httpRequest.requestInStream("EXAMPLE_URL", { method: http.RequestMethod.GET, connectTimeout: 60000, readTimeout: 60000, @@ -586,9 +586,9 @@ let promise = httpRequest.request2("EXAMPLE_URL", { } }); promise.then((data) => { - console.info("request2 OK!" + JSON.stringify(data)); + console.info("requestInStream OK!" + JSON.stringify(data)); }).catch((err) => { - console.info("request2 ERROR : err = " + JSON.stringify(err)); + console.info("requestInStream ERROR : err = " + JSON.stringify(err)); }); ``` @@ -815,9 +815,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre httpRequest.off('dataEnd'); ``` -### on('dataProgress')10+ +### on('dataReceiveProgress')10+ -on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void +on(type: 'dataReceiveProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void Registers an observer for events indicating progress of receiving HTTP streaming responses. @@ -830,20 +830,20 @@ Registers an observer for events indicating progress of receiving HTTP streaming | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | --------------------------------- | -| type | string | Yes | Event type. The value is **dataProgress**.| +| type | string | Yes | Event type. The value is **dataReceiveProgress**.| | callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.
- **receiveSize**: number of received bytes.
- **totalSize**: total number of bytes to be received.| **Example** ```js -httpRequest.on('dataProgress', (data) => { - console.info('dataProgress:' + JSON.stringify(data)); +httpRequest.on('dataReceiveProgress', (data) => { + console.info('dataReceiveProgress:' + JSON.stringify(data)); }); ``` -### off('dataProgress')10+ +### off('dataReceiveProgress')10+ -off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void +off(type: 'dataReceiveProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void Unregisters the observer for events indicating progress of receiving HTTP streaming responses. @@ -856,13 +856,13 @@ Unregisters the observer for events indicating progress of receiving HTTP stream | Name | Type | Mandatory| Description | | -------- | ------------------ | ---- | -------------------------------------- | -| type | string | Yes | Event type. The value is **dataProgress**.| +| type | string | Yes | Event type. The value is **dataReceiveProgress**.| | callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. | **Example** ```js -httpRequest.off('dataProgress'); +httpRequest.off('dataReceiveProgress'); ``` ## HttpRequestOptions6+ diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md index 02112d5b265e73139c9cd662246a819bc16c0b1f..cc3d507ee9d208bc66571ca56daf1cf518c3d5fe 100644 --- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md +++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md @@ -10,15 +10,17 @@ Before using the **CommonEventSubscriber** module, you must obtain a **subscribe ```ts import CommonEvent from '@ohos.commonEvent'; -let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +import CommonEventManager from '@ohos.commonEventManager'; +import Base from '@ohos.base'; +let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -let subscribeInfo = { +let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = { events: ["event"] }; // Callback for subscriber creation. -function createCB(err, commonEventSubscriber) { +function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) { if (err.code) { console.error(`createSubscriber failed, code is ${err.code}`); } else { @@ -49,7 +51,7 @@ Obtains the code of this common event. This API uses an asynchronous callback to ```ts // Callback for result code obtaining of an ordered common event. -function getCodeCB(err, code) { +function getCodeCB(err:Base.BusinessError, code:number) { if (err.code) { console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -76,9 +78,9 @@ Obtains the code of this common event. This API uses a promise to return the res **Example** ```ts -subscriber.getCode().then((code) => { +subscriber.getCode().then((code:number) => { console.info("getCode " + JSON.stringify(code)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -102,7 +104,7 @@ Sets the code for this common event. This API uses an asynchronous callback to r ```ts // Callback for result code setting of an ordered common event. -function setCodeCB(err) { +function setCodeCB(err:Base.BusinessError) { if (err.code) { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -137,7 +139,7 @@ Sets the code for this common event. This API uses a promise to return the resul ```ts subscriber.setCode(1).then(() => { console.info("setCode"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -160,7 +162,7 @@ Obtains the data of this common event. This API uses an asynchronous callback to ```ts // Callback for result data obtaining of an ordered common event. -function getDataCB(err, data) { +function getDataCB(err:Base.BusinessError, data:string) { if (err.code) { console.error(`getData failed, code is ${err.code}, message is ${err.message}`); } else { @@ -187,9 +189,9 @@ Obtains the data of this common event. This API uses a promise to return the res **Example** ```ts -subscriber.getData().then((data) => { +subscriber.getData().then((data:string) => { console.info("getData " + JSON.stringify(data)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -213,7 +215,7 @@ Sets the data for this common event. This API uses an asynchronous callback to r ```ts // Callback for result data setting of an ordered common event -function setDataCB(err) { +function setDataCB(err:Base.BusinessError) { if (err.code) { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -248,7 +250,7 @@ Sets the data for this common event. This API uses a promise to return the resul ```ts subscriber.setData("publish_data_changed").then(() => { console.info("setData"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -273,7 +275,7 @@ Sets the code and data for this common event. This API uses an asynchronous call ```ts // Callback for code and data setting of an ordered common event. -function setCodeDataCB(err) { +function setCodeDataCB(err:Base.BusinessError) { if (err.code) { console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); } else { @@ -309,7 +311,7 @@ Sets the code and data for this common event. This API uses a promise to return ```ts subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -332,7 +334,7 @@ Checks whether this common event is an ordered one. This API uses an asynchronou ```ts // Callback for checking whether the current common event is an ordered one. -function isOrderedCB(err, isOrdered) { +function isOrderedCB(err:Base.BusinessError, isOrdered:boolean) { if (err.code) { console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -359,9 +361,9 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** ```ts -subscriber.isOrderedCommonEvent().then((isOrdered) => { +subscriber.isOrderedCommonEvent().then((isOrdered:boolean) => { console.info("isOrdered " + JSON.stringify(isOrdered)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -384,7 +386,7 @@ Checks whether this common event is a sticky one. This API uses an asynchronous ```ts // Callback for checking whether the current common event is a sticky one. -function isStickyCB(err, isSticky) { +function isStickyCB(err:Base.BusinessError, isSticky:boolean) { if (err.code) { console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -411,9 +413,9 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** ```ts -subscriber.isStickyCommonEvent().then((isSticky) => { +subscriber.isStickyCommonEvent().then((isSticky:boolean) => { console.info("isSticky " + JSON.stringify(isSticky)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -436,7 +438,7 @@ Aborts this common event. After the abort, the common event is not sent to the n ```ts // Callback for common event aborting. -function abortCB(err) { +function abortCB(err:Base.BusinessError) { if (err.code) { console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -465,7 +467,7 @@ Aborts this common event. After the abort, the common event is not sent to the n ```ts subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -488,7 +490,7 @@ Clears the aborted state of this common event. This API takes effect only for or ```ts // Callback for clearing the aborted state of the current common event. -function clearAbortCB(err) { +function clearAbortCB(err:Base.BusinessError) { if (err.code) { console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -517,7 +519,7 @@ Clears the aborted state of this common event. This API takes effect only for or ```ts subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -540,7 +542,7 @@ Checks whether this common event is in the aborted state. This API takes effect ```ts // Callback for checking whether the current common event is in the aborted state. -function getAbortCB(err, abortEvent) { +function getAbortCB(err:Base.BusinessError, abortEvent:boolean) { if (err.code) { console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -567,9 +569,9 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```ts -subscriber.getAbortCommonEvent().then((abortEvent) => { +subscriber.getAbortCommonEvent().then((abortEvent:boolean) => { console.info("abortCommonEvent " + JSON.stringify(abortEvent)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -592,7 +594,7 @@ Obtains the subscriber information. This API uses an asynchronous callback to re ```ts // Callback for subscriber information obtaining. -function getCB(err, subscribeInfo) { +function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) { if (err.code) { console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); } else { @@ -619,9 +621,9 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** ```ts -subscriber.getSubscribeInfo().then((subscribeInfo) => { +subscriber.getSubscribeInfo().then((subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) => { console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -644,7 +646,7 @@ Finishes this common event. This API takes effect only for ordered common events ```ts // Callback for ordered common event finishing. -function finishCB(err) { +function finishCB(err:Base.BusinessError) { if (err.code) { console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { @@ -674,7 +676,7 @@ Finishes this common event. This API takes effect only for ordered common events ```ts subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); -}).catch((err) => { +}).catch((err:Base.BusinessError) => { console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md index 9ad267c45ee6c702c5e81af064f169b74dc597ac..be6d3472df78e2755b5d00854c84d0e36b71a8de 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationRequest.md @@ -10,45 +10,45 @@ The **NotificationRequest** module provides APIs for defining the notification r **System capability**: SystemCapability.Notification.Notification -| Name | Type | Mandatory| Description | -| --------------------- | --------------------------------------------- | --- | -------------------------- | -| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | Yes | Notification content. | -| id | number | No | Notification ID. | -| slotType | [SlotType](js-apis-notificationManager.md#slottype) | No | Notification slot type. | -| isOngoing | boolean | No | Whether the notification is an ongoing notification. | -| isUnremovable | boolean | No | Whether the notification can be removed. | -| deliveryTime | number | No | Time when the notification is sent. | -| tapDismissed | boolean | No | Whether the notification is automatically cleared. | -| autoDeletedTime | number | No | Time when the notification is automatically cleared. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** instance to which the notification will be redirected after being clicked.| -| extraInfo | {[key: string]: any} | No | Extended parameters. | -| color | number | No | Background color of the notification. Not supported currently.| -| colorEnabled | boolean | No | Whether the notification background color can be enabled. Not supported currently.| -| isAlertOnce | boolean | No | Whether the notification triggers an alert only once.| -| isStopwatch | boolean | No | Whether to display the stopwatch. | -| isCountDown | boolean | No | Whether to display the countdown time. | -| isFloatingIcon | boolean | No | Whether the notification is displayed as a floating icon in the status bar. | -| label | string | No | Notification label. | -| badgeIconStyle | number | No | Notification badge type. Not supported currently. | -| showDeliveryTime | boolean | No | Whether to display the time when the notification is delivered. | -| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | No | Buttons in the notification. Up to three buttons are allowed. | -| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | No | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| -| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | No | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| -| creatorBundleName | string | No | Name of the bundle that creates the notification. | -| creatorUid | number | No | UID used for creating the notification. | -| creatorPid | number | No | PID used for creating the notification. | -| creatorUserId8+ | number | No | ID of the user who creates the notification. | -| hashCode | string | No | Unique ID of the notification. | -| classification | string | No | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | -| groupName8+ | string | No | Notification group name. | -| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | No | Notification template. | -| isRemoveAllowed10+ | boolean | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | -| source8+ | number | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| distributedOption8+ | [DistributedOptions](#distributedoptions) | No | Distributed notification options. | -| deviceId8+ | string | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationFlags.md#notificationflags) | No | Notification flags. | -| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** instance to which the notification will be redirected when it is removed. | -| badgeNumber9+ | number | No | Number of notifications displayed on the application icon. | +| Name | Type | Mandatory| Description | +|-------------------------------| --------------------------------------------- | --- |-----------------------------------------------------------------------| +| content | [NotificationContent](js-apis-inner-notification-notificationContent.md#notificationcontent) | Yes | Notification content. | +| id | number | No | Notification ID. | +| slotType | [SlotType](js-apis-notificationManager.md#slottype) | No | Notification slot type. | +| isOngoing | boolean | No | Whether the notification is an ongoing notification. | +| isUnremovable | boolean | No | Whether the notification can be removed. This parameter applies to continuous notification tasks, such as navigation and music playback. If a notifiation is not removable, it will not be deleted when the user touches the delete button below the notification, but it can still be deleted by swiping left on the notification and touching the delete button. | +| deliveryTime | number | No | Time when the notification is sent. | +| tapDismissed | boolean | No | Whether the notification is automatically cleared. | +| autoDeletedTime | number | No | Time when the notification is automatically cleared. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** instance to which the notification will be redirected after being clicked. | +| extraInfo | {[key: string]: any} | No | Extended parameters. | +| color | number | No | Background color of the notification. Not supported currently. | +| colorEnabled | boolean | No | Whether the notification background color can be enabled. Not supported currently. | +| isAlertOnce | boolean | No | Whether the notification triggers an alert only once. | +| isStopwatch | boolean | No | Whether to display the stopwatch. | +| isCountDown | boolean | No | Whether to display the countdown time. | +| isFloatingIcon | boolean | No | Whether the notification is displayed as a floating icon in the status bar. | +| label | string | No | Notification label. | +| badgeIconStyle | number | No | Notification badge type. Not supported currently. | +| showDeliveryTime | boolean | No | Whether to display the time when the notification is delivered. | +| actionButtons | Array\<[NotificationActionButton](js-apis-inner-notification-notificationActionButton.md)\> | No | Buttons in the notification. Up to three buttons are allowed. | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | No | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB. | +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | No | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB. | +| creatorBundleName | string | No | Name of the bundle that creates the notification. | +| creatorUid | number | No | UID used for creating the notification. | +| creatorPid | number | No | PID used for creating the notification. | +| creatorUserId8+ | number | No | ID of the user who creates the notification. | +| hashCode | string | No | Unique ID of the notification. | +| classification | string | No | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName8+ | string | No | Notification group name. | +| template8+ | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | No | Notification template. | +| isRemoveAllowed8+ | boolean | No | Whether the notification can be removed. If a notifiation is not removable, it will not be deleted when the user touches the delete button below the notification, but it can still be deleted by swiping left on the notification and touching the delete button.
**System API**: This is a system API and cannot be called by third-party applications.| +| source8+ | number | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| distributedOption8+ | [DistributedOptions](#distributedoptions) | No | Distributed notification options. | +| deviceId8+ | string | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| notificationFlags8+ | [NotificationFlags](js-apis-inner-notification-notificationFlags.md#notificationflags) | No | Notification flags. | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | number | No | Number of notifications displayed on the application icon. | ## DistributedOptions diff --git a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md index 73a6bab743f76ff7d139723b0c491b35bcb3772b..afea772afef9616c93c2cdaca2e422aa5313315a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md +++ b/en/application-dev/reference/apis/js-apis-inner-notification-notificationSorting.md @@ -12,8 +12,8 @@ The **NotificationSorting** module provides APIs for defining the sorting inform **System API**: This is a system API and cannot be called by third-party applications. -| Name | Type | Mandatory| Description | -| -------------------- | --------------------- | --- | ------------------------------------------ | -| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | Yes | Notification slot type. | -| level | number | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | string | Yes | Description of the notification slot. | +| Name | Type | Mandatory| Description | +|---------| --------------------- | --- |------------------------| +| slot | [NotificationSlot](js-apis-inner-notification-notificationSlot.md) | Yes | Notification slot type. | +| ranking | number | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| hashCode | string | Yes | Unique ID of the notification. | diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 0bd9b716421a85fdc2e28582d2799ced24b12109..0dc717e3b5f35c05502cad7e898740c383e67077 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -158,7 +158,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.| +| callback | AsyncCallback\<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.| **Error codes** @@ -192,7 +192,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses a prom | Type | Description | | --------------------------------- | ------------------------------------- | -| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.| +| Promise\<[HttpProxy](#httpproxy10)> | Promise used to return the result.| **Error codes** @@ -229,7 +229,7 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch | Name | Type | Mandatory| Description | | --------- | ----------------------- | ---- | ------------------------------------------------------------ | -| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network. | +| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **error** is **undefined**. Otherwise, **error** is an error object.| **Error codes** @@ -274,7 +274,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------------------ | ---- | ---------------- | -| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.| +| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network.| **Return value** @@ -324,7 +324,7 @@ This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.| +| callback | AsyncCallback<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.| **Error codes** @@ -347,7 +347,7 @@ connection.getDefaultHttpProxy((error, data) => { getDefaultHttpProxy(): Promise\; Obtains the default proxy configuration of the network. -If the global proxy is set, the global proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned. +If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned. This API uses a promise to return the result. **System capability**: SystemCapability.Communication.NetManager.Core @@ -356,7 +356,7 @@ This API uses a promise to return the result. | Type | Description | | -------------------------------- | ----------------------------------------- | -| Promise<[HttpProxy](#httpproxy)> | Promise used to return the result.| +| Promise<[HttpProxy](#httpproxy10)> | Promise used to return the result.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index 21fdb44e402a4a0cb4a6f39d883522ab84513217..e7aae4ef5ef646af82499c8d3fdfd2bfd53cf905 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -486,7 +486,7 @@ Defines the network configuration for the Ethernet connection. | gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| | netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.| | dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| -| httpProxy10+ | [HttpProxy](js-apis-net-connection.md#httpproxy) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.| +| httpProxy10+ | [HttpProxy](js-apis-net-connection.md#httpproxy10) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.| ## IPSetMode9+ diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 646f07fc4d30ec6ad4585eacd840a99954b34973..5ab31338dad186152b29dab25f05f1175822902a 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -4,7 +4,7 @@ The **Notification** module provides notification management capabilities, cover > **NOTE** > -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. This module is deprecated since API version 9. > > Notification subscription and unsubscription APIs are available only to system applications. @@ -1460,7 +1460,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | --------------- | ----------------------------------| ---- | -------------------- | | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. | | notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1502,7 +1502,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | --------------- | --------------- | ---- | ---------- | | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.| | notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback. | -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. | +| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback.| +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| -| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. | +| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. | **Example** @@ -2872,10 +2872,10 @@ Notification.getDeviceRemindType().then((data) => { > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) instead. -| Name | Type | Read-only| Mandatory| Description | -| ------ | ------ |---- | --- | ------ | -| bundle | string | No | Yes | Bundle information of the application.| -| uid | number | No | No | User ID.| +| Name | Type | Mandatory| Description | +| ------ | ------ | --- | ------ | +| bundle | string | Yes | Bundle information of the application.| +| uid | number | No | User ID.| ## NotificationKeydeprecated @@ -3059,7 +3059,7 @@ Describes the notification request. | classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | | groupName8+| string | Yes | Yes | Notification group name. | | template8+ | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. | -| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| isRemoveAllowed10+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | | source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | | distributedOption8+ | [DistributedOptions](#distributedoptions8) | Yes | Yes | Distributed notification options. | | deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | @@ -3203,7 +3203,7 @@ Provides the notification user input. | TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_TIMER | 2 | Timed notification. | -## RemoveReason9+ deprecated +## RemoveReason deprecated **System capability**: SystemCapability.Notification.Notification @@ -3211,9 +3211,9 @@ Provides the notification user input. > **NOTE** > -> This API is supported since API version 9 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead. | Name | Value | Description | | -------------------- | --- | -------------------- | -| CLICK_REASON_REMOVE9+ | 1 | The notification is removed after a click on it. | -| CANCEL_REASON_REMOVE9+ | 2 | The notification is removed by the user. | +| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | +| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-notificationManager.md b/en/application-dev/reference/apis/js-apis-notificationManager.md index b993f99fcba29fa6bfef5bd78b8b268340844c86..206dd80d0c86c4c811538569f99f5d4b3cdc8c7b 100644 --- a/en/application-dev/reference/apis/js-apis-notificationManager.md +++ b/en/application-dev/reference/apis/js-apis-notificationManager.md @@ -10,6 +10,7 @@ The **notificationManager** module provides notification management capabilities ```ts import notificationManager from '@ohos.notificationManager'; +import Base from '@ohos.base'; ``` ## notificationManager.publish @@ -45,7 +46,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // publish callback -function publishCallback(err) { +function publishCallback(err: Base.BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { @@ -155,7 +156,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // publish callback -function publishCallback(err) { +function publishCallback(err: Base.BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { @@ -163,7 +164,7 @@ function publishCallback(err) { } } // User ID -let userId = 1; +let userId: number = 1; // NotificationRequest object let notificationRequest: notificationManager.NotificationRequest = { id: 1, @@ -228,7 +229,7 @@ let notificationRequest: notificationManager.NotificationRequest = { } }; -let userId = 1; +let userId: number = 1; notificationManager.publish(notificationRequest, userId).then(() => { console.info("publish success"); @@ -267,7 +268,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // cancel callback -function cancelCallback(err) { +function cancelCallback(err: Base.BusinessError) { if (err) { console.error(`cancel failed, code is ${err.code}, message is ${err.message}`); } else { @@ -341,7 +342,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // cancel callback -function cancelCallback(err) { +function cancelCallback(err: Base.BusinessError) { if (err) { console.error(`cancel failed, code is ${err.code}, message is ${err.message}`); } else { @@ -379,7 +380,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // cancel callback -function cancelAllCallback(err) { +function cancelAllCallback(err: Base.BusinessError) { if (err) { console.error(`cancelAll failed, code is ${err.code}, message is ${err.message}`); } else { @@ -449,7 +450,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // addSlot callback -function addSlotCallBack(err) { +function addSlotCallBack(err: Base.BusinessError) { if (err) { console.error(`addSlot failed, code is ${err.code}, message is ${err.message}`); } else { @@ -457,7 +458,7 @@ function addSlotCallBack(err) { } } // NotificationSlot object -let notificationSlot = { +let notificationSlot: notificationManager.NotificationSlot = { type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; notificationManager.addSlot(notificationSlot, addSlotCallBack); @@ -496,7 +497,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // NotificationSlot object -let notificationSlot = { +let notificationSlot: notificationManager.NotificationSlot = { type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; notificationManager.addSlot(notificationSlot).then(() => { @@ -534,7 +535,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // addSlot callback -function addSlotCallBack(err) { +function addSlotCallBack(err: Base.BusinessError) { if (err) { console.error(`addSlot failed, code is ${err.code}, message is ${err.message}`); } else { @@ -611,7 +612,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // addSlots callback -function addSlotsCallBack(err) { +function addSlotsCallBack(err: Base.BusinessError) { if (err) { console.error(`addSlots failed, code is ${err.code}, message is ${err.message}`); } else { @@ -619,11 +620,11 @@ function addSlotsCallBack(err) { } } // NotificationSlot object -let notificationSlot = { +let notificationSlot: notificationManager.NotificationSlot = { type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; // NotificationSlotArray object -let notificationSlotArray = new Array(); +let notificationSlotArray: notificationManager.NotificationSlot[] = new Array(); notificationSlotArray[0] = notificationSlot; notificationManager.addSlots(notificationSlotArray, addSlotsCallBack); @@ -662,11 +663,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // NotificationSlot object -let notificationSlot = { +let notificationSlot: notificationManager.NotificationSlot = { type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; // NotificationSlotArray object -let notificationSlotArray = new Array(); +let notificationSlotArray: notificationManager.NotificationSlot[] = new Array(); notificationSlotArray[0] = notificationSlot; notificationManager.addSlots(notificationSlotArray).then(() => { @@ -703,14 +704,14 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // getSlot callback -function getSlotCallback(err,data) { +function getSlotCallback(err: Base.BusinessError, data: notificationManager.NotificationSlot) { if (err) { console.error(`getSlot failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getSlot success"); + console.info(`getSlot success, data is ${JSON.stringify(data)}`); } } -let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +let slotType: notificationManager.SlotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; notificationManager.getSlot(slotType, getSlotCallback); ``` @@ -747,9 +748,10 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; -notificationManager.getSlot(slotType).then((data) => { - console.info("getSlot success, data: " + JSON.stringify(data)); +let slotType: notificationManager.SlotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; + +notificationManager.getSlot(slotType).then((data: notificationManager.NotificationSlot) => { + console.info("getSlot success, data: " + JSON.stringify(data)); }); ``` @@ -781,12 +783,12 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // getSlots callback -function getSlotsCallback(err,data) { - if (err) { - console.error(`getSlots failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("getSlots success"); - } +function getSlotsCallback(err: Base.BusinessError, data: Array) { + if (err) { + console.error(`getSlots failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info(`getSlots success, data is ${JSON.stringify(data)}`); + } } notificationManager.getSlots(getSlotsCallback); ``` @@ -818,7 +820,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -notificationManager.getSlots().then((data) => { +notificationManager.getSlots().then((data: Array) => { console.info("getSlots success, data: " + JSON.stringify(data)); }); ``` @@ -852,15 +854,15 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // removeSlot callback -function removeSlotCallback(err) { - if (err) { - console.error(`removeSlot failed, code is ${err.code}, message is ${err.message}`); - } else { - console.info("removeSlot success"); - } +function removeSlotCallback(err: Base.BusinessError) { + if (err) { + console.error(`removeSlot failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("removeSlot success"); + } } let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; -notificationManager.removeSlot(slotType,removeSlotCallback); +notificationManager.removeSlot(slotType, removeSlotCallback); ``` ## notificationManager.removeSlot @@ -890,7 +892,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +let slotType: notificationManager.SlotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; notificationManager.removeSlot(slotType).then(() => { console.info("removeSlot success"); }); @@ -923,7 +925,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function removeAllCallBack(err) { +function removeAllCallBack(err: Base.BusinessError) { if (err) { console.error(`removeAllSlots failed, code is ${err.code}, message is ${err.message}`); } else { @@ -993,17 +995,17 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function setNotificationEnablenCallback(err) { +function setNotificationEnableCallback(err: Base.BusinessError) { if (err) { - console.error(`setNotificationEnablenCallback failed, code is ${err.code}, message is ${err.message}`); + console.error(`setNotificationEnableCallback failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("setNotificationEnablenCallback success"); + console.info("setNotificationEnableCallback success"); } } -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -notificationManager.setNotificationEnable(bundle, false, setNotificationEnablenCallback); +notificationManager.setNotificationEnable(bundle, false, setNotificationEnableCallback); ``` ## notificationManager.setNotificationEnable @@ -1039,7 +1041,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; notificationManager.setNotificationEnable(bundle, false).then(() => { @@ -1080,16 +1082,18 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function isNotificationEnabledCallback(err, data) { +function isNotificationEnabledCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isNotificationEnabled failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("isNotificationEnabled success"); + console.info(`isNotificationEnabled success, data is ${JSON.stringify(data)}`); } } -let bundle = { + +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; + notificationManager.isNotificationEnabled(bundle, isNotificationEnabledCallback); ``` @@ -1131,10 +1135,10 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -notificationManager.isNotificationEnabled(bundle).then((data) => { +notificationManager.isNotificationEnabled(bundle).then((data: boolean) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1170,11 +1174,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function isNotificationEnabledCallback(err, data) { +function isNotificationEnabledCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isNotificationEnabled failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("isNotificationEnabled success"); + console.info(`isNotificationEnabled success, data is ${JSON.stringify(data)}`); } } @@ -1212,7 +1216,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -notificationManager.isNotificationEnabled().then((data) => { +notificationManager.isNotificationEnabled().then((data: boolean) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1250,15 +1254,15 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function isNotificationEnabledCallback(err, data) { +function isNotificationEnabledCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isNotificationEnabled failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("isNotificationEnabled success"); + console.info(`isNotificationEnabled success, data is ${JSON.stringify(data)}`); } } -let userId = 1; +let userId: number = 1; notificationManager.isNotificationEnabled(userId, isNotificationEnabledCallback); ``` @@ -1301,9 +1305,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let userId = 1; +let userId: number = 1; -notificationManager.isNotificationEnabled(userId).then((data) => { +notificationManager.isNotificationEnabled(userId).then((data: boolean) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1342,14 +1346,14 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function displayBadgeCallback(err) { +function displayBadgeCallback(err: Base.BusinessError) { if (err) { console.error(`displayBadge failed, code is ${err.code}, message is ${err.message}`); } else { console.info("displayBadge success"); } } -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; notificationManager.displayBadge(bundle, false, displayBadgeCallback); @@ -1388,7 +1392,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; notificationManager.displayBadge(bundle, false).then(() => { @@ -1413,7 +1417,7 @@ Checks whether the notification badge is enabled for a specified application. Th | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | | bundle | [BundleOption](./js-apis-inner-notification-notificationCommonDef.md#bundleoption) | Yes | Bundle of the application. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1429,14 +1433,14 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function isBadgeDisplayedCallback(err, data) { +function isBadgeDisplayedCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isBadgeDisplayed failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("isBadgeDisplayed success"); + console.info(`isBadgeDisplayed success, data is ${JSON.stringify(data)}`); } } -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; notificationManager.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); @@ -1480,10 +1484,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundle = { - bundle: "bundleName1", +let bundle: notificationManager.BundleOption = { + bundle: "bundleName1", }; -notificationManager.isBadgeDisplayed(bundle).then((data) => { + +notificationManager.isBadgeDisplayed(bundle).then((data: boolean) => { console.info("isBadgeDisplayed success, data: " + JSON.stringify(data)); }); ``` @@ -1514,7 +1519,8 @@ Sets the notification badge number. This API uses a promise to return the result **Example** ```ts -let badgeNumber = 10 +let badgeNumber: number = 10; + notificationManager.setBadgeNumber(badgeNumber).then(() => { console.info("displayBadge success"); }); @@ -1549,7 +1555,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function setBadgeNumberCallback(err) { +function setBadgeNumberCallback(err: Base.BusinessError) { if (err) { console.info(`displayBadge failed code is ${err.code}, message is ${err.message}`); } else { @@ -1557,7 +1563,7 @@ function setBadgeNumberCallback(err) { } } -let badgeNumber = 10 +let badgeNumber: number = 10; notificationManager.setBadgeNumber(badgeNumber, setBadgeNumberCallback); ``` @@ -1595,17 +1601,17 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function setSlotByBundleCallback(err) { +function setSlotByBundleCallback(err: Base.BusinessError) { if (err) { console.error(`setSlotByBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setSlotByBundle success"); } } -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -let notificationSlot = { +let notificationSlot: notificationManager.NotificationSlot = { type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; notificationManager.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); @@ -1644,12 +1650,14 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -let notificationSlot = { + +let notificationSlot: notificationManager.NotificationSlot = { type: notificationManager.SlotType.SOCIAL_COMMUNICATION }; + notificationManager.setSlotByBundle(bundle, notificationSlot).then(() => { console.info("setSlotByBundle success"); }); @@ -1688,14 +1696,14 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function getSlotsByBundleCallback(err, data) { +function getSlotsByBundleCallback(err: Base.BusinessError, data: Array) { if (err) { console.error(`getSlotByBundle failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getSlotsByBundle success"); + console.info(`getSlotsByBundle success, data is ${JSON.stringify(data)}`); } } -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; notificationManager.getSlotsByBundle(bundle, getSlotsByBundleCallback); @@ -1739,10 +1747,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -notificationManager.getSlotsByBundle(bundle).then((data) => { + +notificationManager.getSlotsByBundle(bundle).then((data: Array) => { console.info("getSlotsByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -1780,16 +1789,18 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function getSlotNumByBundleCallback(err, data) { +function getSlotNumByBundleCallback(err: Base.BusinessError, data: number) { if (err) { console.error(`getSlotByBundle failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getSlotNumByBundle success"); + console.info(`getSlotNumByBundle success data is ${JSON.stringify(data)}`); } } -let bundle = { - bundle: "bundleName1", + +let bundle: notificationManager.BundleOption = { + bundle: "bundleName1", }; + notificationManager.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); ``` @@ -1831,10 +1842,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundle = { - bundle: "bundleName1", +let bundle: notificationManager.BundleOption = { + bundle: "bundleName1", }; -notificationManager.getSlotNumByBundle(bundle).then((data) => { + +notificationManager.getSlotNumByBundle(bundle).then((data: number) => { console.info("getSlotNumByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -1869,11 +1881,11 @@ Obtains all active notifications. This API uses an asynchronous callback to retu **Example** ```ts -function getAllActiveNotificationsCallback(err, data) { +function getAllActiveNotificationsCallback(err: Base.BusinessError, data: Array) { if (err) { console.error(`getAllActiveNotifications failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getAllActiveNotifications success"); + console.info(`getAllActiveNotifications success, data is ${JSON.stringify(data)}`); } } @@ -1911,7 +1923,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -notificationManager.getAllActiveNotifications().then((data) => { +notificationManager.getAllActiveNotifications().then((data: Array) => { console.info("getAllActiveNotifications success, data: " + JSON.stringify(data)); }); ``` @@ -1943,11 +1955,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function getActiveNotificationCountCallback(err, data) { +function getActiveNotificationCountCallback(err: Base.BusinessError, data: number) { if (err) { console.error(`getActiveNotificationCount failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getActiveNotificationCount success"); + console.info(`getActiveNotificationCount success, data is ${JSON.stringify(data)}`); } } @@ -1981,7 +1993,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -notificationManager.getActiveNotificationCount().then((data) => { +notificationManager.getActiveNotificationCount().then((data: number) => { console.info("getActiveNotificationCount success, data: " + JSON.stringify(data)); }); ``` @@ -2013,7 +2025,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function getActiveNotificationsCallback(err, data) { +function getActiveNotificationsCallback(err: Base.BusinessError, data: Array) { if (err) { console.error(`getActiveNotifications failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2051,7 +2063,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -notificationManager.getActiveNotifications().then((data) => { +notificationManager.getActiveNotifications().then((data: Array) => { console.info("removeGroupByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -2084,7 +2096,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function cancelGroupCallback(err) { +function cancelGroupCallback(err: Base.BusinessError) { if (err) { console.error(`cancelGroup failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2092,7 +2104,7 @@ function cancelGroupCallback(err) { } } -let groupName = "GroupName"; +let groupName: string = "GroupName"; notificationManager.cancelGroup(groupName, cancelGroupCallback); ``` @@ -2124,7 +2136,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let groupName = "GroupName"; +let groupName: string = "GroupName"; notificationManager.cancelGroup(groupName).then(() => { console.info("cancelGroup success"); }); @@ -2164,7 +2176,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function removeGroupByBundleCallback(err) { +function removeGroupByBundleCallback(err: Base.BusinessError) { if (err) { console.error(`removeGroupByBundle failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2172,8 +2184,8 @@ function removeGroupByBundleCallback(err) { } } -let bundleOption = {bundle: "Bundle"}; -let groupName = "GroupName"; +let bundleOption: notificationManager.BundleOption = { bundle: "Bundle" }; +let groupName: string = "GroupName"; notificationManager.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); ``` @@ -2211,8 +2223,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let bundleOption = {bundle: "Bundle"}; -let groupName = "GroupName"; +let bundleOption: notificationManager.BundleOption = { bundle: "Bundle" }; +let groupName: string = "GroupName"; + notificationManager.removeGroupByBundle(bundleOption, groupName).then(() => { console.info("removeGroupByBundle success"); }); @@ -2251,7 +2264,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function setDoNotDisturbDateCallback(err) { +function setDoNotDisturbDateCallback(err: Base.BusinessError) { if (err) { console.error(`setDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2259,7 +2272,7 @@ function setDoNotDisturbDateCallback(err) { } } -let doNotDisturbDate = { +let doNotDisturbDate: notificationManager.DoNotDisturbDate = { type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) @@ -2300,7 +2313,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let doNotDisturbDate = { +let doNotDisturbDate: notificationManager.DoNotDisturbDate = { type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) @@ -2346,7 +2359,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function setDoNotDisturbDateCallback(err) { +function setDoNotDisturbDateCallback(err: Base.BusinessError) { if (err) { console.error(`setDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2354,13 +2367,13 @@ function setDoNotDisturbDateCallback(err) { } } -let doNotDisturbDate = { +let doNotDisturbDate: notificationManager.DoNotDisturbDate = { type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) }; -let userId = 1; +let userId: number = 1; notificationManager.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); ``` @@ -2399,13 +2412,13 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let doNotDisturbDate = { +let doNotDisturbDate: notificationManager.DoNotDisturbDate = { type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) }; -let userId = 1; +let userId: number = 1; notificationManager.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { console.info("setDoNotDisturbDate success"); @@ -2445,11 +2458,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function getDoNotDisturbDateCallback(err,data) { +function getDoNotDisturbDateCallback(err: Base.BusinessError, data: notificationManager.DoNotDisturbDate) { if (err) { console.error(`getDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getDoNotDisturbDate success"); + console.info(`getDoNotDisturbDate success, data is ${JSON.stringify(data)}`); } } @@ -2488,8 +2501,8 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -notificationManager.getDoNotDisturbDate().then((data) => { - console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); +notificationManager.getDoNotDisturbDate().then((data: notificationManager.DoNotDisturbDate) => { + console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` @@ -2528,15 +2541,15 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -function getDoNotDisturbDateCallback(err,data) { +function getDoNotDisturbDateCallback(err: Base.BusinessError, data: notificationManager.DoNotDisturbDate) { if (err) { console.error(`getDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getDoNotDisturbDate success"); + console.info(`getDoNotDisturbDate success, data is ${JSON.stringify(data)}`); } } -let userId = 1; +let userId: number = 1; notificationManager.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); ``` @@ -2580,9 +2593,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let userId = 1; +let userId: number = 1; -notificationManager.getDoNotDisturbDate(userId).then((data) => { +notificationManager.getDoNotDisturbDate(userId).then((data: notificationManager.DoNotDisturbDate) => { console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` @@ -2617,7 +2630,7 @@ Checks whether DND mode is supported. This API uses an asynchronous callback to **Example** ```ts -function isSupportDoNotDisturbModeCallback(err,data) { +function isSupportDoNotDisturbModeCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isSupportDoNotDisturbMode failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2659,7 +2672,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -notificationManager.isSupportDoNotDisturbMode().then((data) => { +notificationManager.isSupportDoNotDisturbMode().then((data: boolean) => { console.info("supportDoNotDisturbMode success, data: " + JSON.stringify(data)); }); ``` @@ -2692,8 +2705,8 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -let templateName = 'process'; -function isSupportTemplateCallback(err, data) { +let templateName: string = 'process'; +function isSupportTemplateCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isSupportTemplate failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2737,9 +2750,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -let templateName = 'process'; +let templateName: string = 'process'; -notificationManager.isSupportTemplate(templateName).then((data) => { +notificationManager.isSupportTemplate(templateName).then((data: boolean) => { console.info("isSupportTemplate success, data: " + JSON.stringify(data)); }); ``` @@ -2771,7 +2784,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function requestEnableNotificationCallback(err) { +function requestEnableNotificationCallback(err: Base.BusinessError) { if (err) { console.error(`requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2808,7 +2821,76 @@ notificationManager.requestEnableNotification().then(() => { }); ``` +## notificationManager.requestEnableNotification10+ + +requestEnableNotification(context: UIAbilityContext, callback: AsyncCallback\): void + +Requests notification to be enabled for this application in a modal. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- |--------------------| +| context | UIAbilityContext | Yes | Ability context bound to the notification dialog box.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```javascript +function requestEnableNotificationCallback(err) { + if (err) { + console.error(`requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("requestEnableNotification success"); + } +}; + +notificationManager.requestEnableNotification(globalThis.uicontext, requestEnableNotificationCallback); +``` + +## notificationManager.requestEnableNotification10+ + +requestEnableNotification(context: UIAbilityContext): Promise\ + +Requests notification to be enabled for this application in a modal. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- |--------------------| +| context | UIAbilityContext | Yes | Ability context bound to the notification dialog box.| + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```javascript +notificationManager.requestEnableNotification(globalThis.uicontext).then(() => { + console.info("requestEnableNotification success"); +}); +``` ## notificationManager.setDistributedEnable @@ -2843,7 +2925,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function setDistributedEnableCallback(err) { +function setDistributedEnableCallback(err: Base.BusinessError) { if (err) { console.error(`setDistributedEnable failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2851,7 +2933,7 @@ function setDistributedEnableCallback(err) { } }; -let enable = true; +let enable: boolean = true; notificationManager.setDistributedEnable(enable, setDistributedEnableCallback); ``` @@ -2888,11 +2970,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -let enable = true; +let enable: boolean = true; notificationManager.setDistributedEnable(enable).then(() => { - console.info("setDistributedEnable success"); - }); + console.info("setDistributedEnable success"); +}); ``` @@ -2924,7 +3006,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function isDistributedEnabledCallback(err, data) { +function isDistributedEnabledCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isDistributedEnabled failed, code is ${err.code}, message is ${err.message}`); } else { @@ -2966,7 +3048,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```javascript notificationManager.isDistributedEnabled() - .then((data) => { + .then((data: boolean) => { console.info("isDistributedEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -3007,7 +3089,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function setDistributedEnableByBundleCallback(err) { +function setDistributedEnableByBundleCallback(err: Base.BusinessError) { if (err) { console.error(`setDistributedEnableByBundle failed, code is ${err.code}, message is ${err.message}`); } else { @@ -3015,11 +3097,11 @@ function setDistributedEnableByBundleCallback(err) { } }; -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -let enable = true +let enable: boolean = true; notificationManager.setDistributedEnableByBundle(bundle, enable, setDistributedEnableByBundleCallback); ``` @@ -3060,11 +3142,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -let enable = true +let enable: boolean = true; notificationManager.setDistributedEnableByBundle(bundle, enable).then(() => { console.info("setDistributedEnableByBundle success"); @@ -3105,7 +3187,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function isDistributedEnabledByBundleCallback(err, data) { +function isDistributedEnabledByBundleCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isDistributedEnabledByBundle failed, code is ${err.code}, message is ${err.message}`); } else { @@ -3113,7 +3195,7 @@ function isDistributedEnabledByBundleCallback(err, data) { } }; -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; @@ -3159,11 +3241,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -let bundle = { +let bundle: notificationManager.BundleOption = { bundle: "bundleName1", }; -notificationManager.isDistributedEnabledByBundle(bundle).then((data) => { +notificationManager.isDistributedEnabledByBundle(bundle).then((data: boolean) => { console.info("isDistributedEnabledByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -3200,11 +3282,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -function getDeviceRemindTypeCallback(err, data) { +function getDeviceRemindTypeCallback(err: Base.BusinessError, data: notificationManager.DeviceRemindType) { if (err) { console.error(`getDeviceRemindType failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("getDeviceRemindType success"); + console.info(`getDeviceRemindType success, data is ${JSON.stringify(data)}`); } }; @@ -3242,7 +3324,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```javascript -notificationManager.getDeviceRemindType().then((data) => { +notificationManager.getDeviceRemindType().then((data: notificationManager.DeviceRemindType) => { console.info("getDeviceRemindType success, data: " + JSON.stringify(data)); }); ``` @@ -3288,7 +3370,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // publishAsBundle callback -function callback(err) { +function callback(err: Base.BusinessError) { if (err) { console.error(`publishAsBundle failed, code is ${err.code}, message is ${err.message}`); } else { @@ -3296,11 +3378,11 @@ function callback(err) { } } // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; +let representativeBundle: string = "com.example.demo"; // User ID -let userId = 100; +let userId: number = 100; // NotificationRequest object -let request = { +let request: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -3355,11 +3437,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; +let representativeBundle: string = "com.example.demo"; // User ID -let userId = 100; +let userId: number = 100; // NotificationRequest object -let request = { +let request: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -3415,7 +3497,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // cancelAsBundle -function cancelAsBundleCallback(err) { +function cancelAsBundleCallback(err: Base.BusinessError) { if (err) { console.error(`cancelAsBundle failed, code is ${err.code}, message is ${err.message}`); } else { @@ -3423,9 +3505,9 @@ function cancelAsBundleCallback(err) { } } // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; +let representativeBundle: string = "com.example.demo"; // User ID -let userId = 100; +let userId: number = 100; notificationManager.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); ``` @@ -3468,9 +3550,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo"; +let representativeBundle: string = "com.example.demo"; // User ID -let userId = 100; +let userId: number = 100; notificationManager.cancelAsBundle(0, representativeBundle, userId).then(() => { console.info("cancelAsBundle success"); @@ -3513,7 +3595,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // setNotificationEnableSlot -function setNotificationEnableSlotCallback(err) { +function setNotificationEnableSlotCallback(err: Base.BusinessError) { if (err) { console.error(`setNotificationEnableSlot failed, code is ${err.code}, message is ${err.message}`); } else { @@ -3606,11 +3688,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // isNotificationSlotEnabled -function getEnableSlotCallback(err, data) { +function getEnableSlotCallback(err: Base.BusinessError, data: boolean) { if (err) { console.error(`isNotificationSlotEnabled failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("isNotificationSlotEnabled success"); + console.info(`isNotificationSlotEnabled success, data is ${JSON.stringify(data)}`); } }; @@ -3661,7 +3743,7 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ ```ts // isNotificationSlotEnabled notificationManager.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, - notificationManager.SlotType.SOCIAL_COMMUNICATION).then((data) => { + notificationManager.SlotType.SOCIAL_COMMUNICATION).then((data: boolean) => { console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -3701,10 +3783,10 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let userId = 100; -let enable = true; +let userId: number = 100; +let enable: boolean = true; -function callback(err) { +function callback(err: Base.BusinessError) { if (err) { console.error(`setSyncNotificationEnabledWithoutApp failed, code is ${err.code}, message is ${err.message}`); } else { @@ -3755,13 +3837,11 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let userId = 100; -let enable = true; +let userId: number = 100; +let enable: boolean = true; notificationManager.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { console.info('setSyncNotificationEnabledWithoutApp success'); -}).catch((err) => { - console.error(`setSyncNotificationEnabledWithoutApp failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -3799,9 +3879,9 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let userId = 100; +let userId: number = 100; -function getSyncNotificationEnabledWithoutAppCallback(err, data) { +function getSyncNotificationEnabledWithoutAppCallback(err: Base.BusinessError, data: boolean) { if (err) { console.info('getSyncNotificationEnabledWithoutAppCallback, err:' + err); } else { @@ -3851,11 +3931,10 @@ For details about the error codes, see [Notification Error Codes](../errorcodes/ **Example** ```ts -let userId = 100; -notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => { - console.info('getSyncNotificationEnabledWithoutApp, data:' + data); -}).catch((err) => { - console.info('getSyncNotificationEnabledWithoutApp, err:' + err); +let userId: number = 100; + +notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data: boolean) => { + console.info('getSyncNotificationEnabledWithoutApp, data:' + data); }); ``` @@ -3897,9 +3976,11 @@ try{ function OnCheckNotification(info : notificationManager.NotificationCheckInfo) { console.info(`====>OnCheckNotification info: ${JSON.stringify(info)}`); if(info.notificationId == 1){ - return { code: 1, message: "testMsg1"} + let result: notificationManager.NotificationCheckResult = { code: 1, message: "testMsg1"}; + return result; } else { - return { code: 0, message: "testMsg0"} + let result: notificationManager.NotificationCheckResult = { code: 0, message: "testMsg0"}; + return result; } } ``` diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index 1ca3f7833aadfde7058e24f8231d0e0360d82122..b9c7bb055262735c5eb790764acb2cd4c861ebe1 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -443,6 +443,90 @@ notificationSubscribe.remove(hashCode, reason).then(() => { console.info("remove success"); }); ``` +## NotificationSubscribe.remove10+ + +remove(hashCodes: Array\, reason: RemoveReason, callback: AsyncCallback\): void + +Removes specified notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +|-----------|-------------------------------| ---- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| hashCodes | Array\ | Yes | Array of unique notification IDs. It is the **hashCode** in the [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) object of [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onConsume) callback.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +let hashCodes = ['hashCode1', 'hashCode2']; + +function removeCallback(err) { + if (err) { + console.error(`remove failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("remove success"); + } +} +let reason = notificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; +notificationSubscribe.remove(hashCodes, reason, removeCallback); +``` + +## NotificationSubscribe.remove10+ + +remove(hashCodes: Array\, reason: RemoveReason): Promise\ + +Removes specified notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +|-----------|-------------------------------| ---- |-------------| +| hashCodes | Array\ | Yes | Array of unique notification IDs.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +let hashCodes = ['hashCode1','hashCode2']; +let reason = notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +notificationSubscribe.remove(hashCodes, reason).then(() => { + console.info("remove success"); +}); +``` ## NotificationSubscribe.removeAll diff --git a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md index aae05347c5a05bdcb5e6bcae488fe53fa89602f4..b7bf574032b04eb83909c0006bce06a5e3900560 100644 --- a/en/application-dev/reference/apis/js-apis-photoAccessHelper.md +++ b/en/application-dev/reference/apis/js-apis-photoAccessHelper.md @@ -84,11 +84,12 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getAssets'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -96,7 +97,7 @@ async function example() { phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => { if (fetchResult != undefined) { console.info('fetchResult success'); - let photoAsset = await fetchResult.getFirstObject(); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName : ' + photoAsset.displayName); } @@ -141,19 +142,21 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('getAssets'); - 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 fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); if (fetchResult != undefined) { console.info('fetchResult success'); - let photoAsset = await fetchResult.getFirstObject(); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName :' + photoAsset.displayName); } @@ -198,7 +201,7 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts async function example() { console.info('createAssetDemo'); - let testFileName = 'testFile' + Date.now() + '.jpg'; + let testFileName: string = 'testFile' + Date.now() + '.jpg'; phAccessHelper.createAsset(testFileName, (err, photoAsset) => { if (photoAsset != undefined) { console.info('createAsset file displayName' + photoAsset.displayName); @@ -247,11 +250,13 @@ For details about the error codes, see [File Management Error Codes](../errorcod **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createAssetDemo'); try { - let testFileName = 'testFile' + Date.now() + '.jpg'; - let photoAsset = await phAccessHelper.createAsset(testFileName); + let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let photoAsset: photoAccessHelper.photoAsset = await phAccessHelper.createAsset(testFileName); console.info('createAsset file displayName' + photoAsset.displayName); console.info('createAsset successfully'); } catch (err) { @@ -293,10 +298,12 @@ For details about the error codes, see [File Management Error Codes](../errorcod **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createAssetDemo'); - let testFileName = 'testFile' + Date.now() + '.jpg'; - let createOption = { + let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let createOption: photoAccessHelper.CreateOptions = { subtype: photoAccessHelper.PhotoSubtype.DEFAULT } phAccessHelper.createAsset(testFileName, createOption, (err, photoAsset) => { @@ -348,14 +355,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createAssetDemo'); try { - let testFileName = 'testFile' + Date.now() + '.jpg'; - let createOption = { + let testFileName: string = 'testFile' + Date.now() + '.jpg'; + let photoAccessHelper: photoAccessHelper.PhotoAccessHelper = { subtype: photoAccessHelper.PhotoSubtype.DEFAULT } - let photoAsset = await phAccessHelper.createAsset(testFileName, createOption); + let photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName, createOption); console.info('createAsset file displayName' + photoAsset.displayName); console.info('createAsset successfully'); } catch (err) { @@ -394,11 +403,13 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createAssetDemo'); - let photoType = photoAccessHelper.PhotoType.IMAGE; - let extension = 'jpg'; - let options = { + let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; + let extension: string = 'jpg'; + let options: photoAccessHelper.FetchOptions = { title: 'testPhoto' } phAccessHelper.createAsset(photoType, extension, options, (err, uri) => { @@ -441,10 +452,12 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createAssetDemo'); - let photoType = photoAccessHelper.PhotoType.IMAGE; - let extension = 'jpg'; + let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; + let extension: string = 'jpg'; phAccessHelper.createAsset(photoType, extension, (err, uri) => { if (uri != undefined) { console.info('createAsset uri' + uri); @@ -491,15 +504,17 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createAssetDemo'); try { - let photoType = photoAccessHelper.PhotoType.IMAGE; - let extension = 'jpg'; - let options = { + let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; + let extension: string = 'jpg'; + let options: photoAccessHelper.FetchOptions = { title: 'testPhoto' } - let uri = await phAccessHelper.createAsset(photoType, extension, options); + let uri: photoAccessHelper.PhotoAccess = await phAccessHelper.createAsset(photoType, extension, options); console.info('createAsset uri' + uri); console.info('createAsset successfully'); } catch (err) { @@ -545,6 +560,8 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createAlbumDemo'); let albumName = 'newAlbumName' + new Date().getTime(); @@ -645,18 +662,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { // Delete the album named newAlbumName. console.info('deleteAlbumsDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions = { + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - 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(); phAccessHelper.deleteAlbums([album], (err) => { if (err) { console.error('deletePhotoAlbumsCallback failed with err: ' + err); @@ -707,18 +726,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { // Delete the album named newAlbumName. console.info('deleteAlbumsDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions = { + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - 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(); phAccessHelper.deleteAlbums([album]).then(() => { console.info('deletePhotoAlbumsPromise successfully'); }).catch((err) => { @@ -761,13 +782,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { // Obtain the album named newAlbumName. console.info('getAlbumsDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions = { + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -780,7 +803,7 @@ async function example() { console.error('getAlbumsCallback fetchResult is undefined'); return; } - let album = await fetchResult.getFirstObject(); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('getAlbumsCallback successfully, albumName: ' + album.albumName); fetchResult.close(); }); @@ -818,6 +841,8 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err **Example** ```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { // Obtain the system album VIDEO, which is preset by default. console.info('getAlbumsDemo'); @@ -830,7 +855,7 @@ async function example() { console.error('getAlbumsCallback fetchResult is undefined'); return; } - let album = await fetchResult.getFirstObject(); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('getAlbumsCallback successfully, albumUri: ' + album.albumUri); fetchResult.close(); }); @@ -875,13 +900,15 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { // Obtain the album named newAlbumName. console.info('getAlbumsDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.equalTo('album_name', 'newAlbumName'); - let fetchOptions = { + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -890,7 +917,7 @@ async function example() { console.error('getAlbumsPromise fetchResult is undefined'); return; } - let album = await fetchResult.getFirstObject(); + let album: photoAccessHelper.Album = await fetchResult.getFirstObject(); console.info('getAlbumsPromise successfully, albumName: ' + album.albumName); fetchResult.close(); }).catch((err) => { @@ -931,11 +958,13 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('deleteAssetDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -997,11 +1026,13 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('deleteDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -1055,24 +1086,26 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('registerChangeDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let photoAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName : ' + photoAsset.displayName); } - let onCallback1 = (changeData) => { + let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { console.info('onCallback1 success, changData: ' + JSON.stringify(changeData)); //file had changed, do something } - let onCallback2 = (changeData) => { + let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { console.info('onCallback2 success, changData: ' + JSON.stringify(changeData)); //file had changed, do something } @@ -1120,23 +1153,25 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('offDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOptions); - let photoAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOptions); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); if (photoAsset != undefined) { console.info('photoAsset.displayName : ' + photoAsset.displayName); } - let onCallback1 = (changeData) => { + let onCallback1 = (changeData: photoAccessHelper.ChangeData) => { console.info('onCallback1 on'); } - let onCallback2 = (changeData) => { + let onCallback2 = (changeData: photoAccessHelper.ChangeData) => { console.info('onCallback2 on'); } // Register onCallback1. @@ -1184,11 +1219,13 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createDeleteRequestDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -1247,11 +1284,13 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('createDeleteRequestDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -1313,28 +1352,30 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('getPhotoIndexDemo'); - let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); - let fetchOp = { + let predicatesForGetAsset: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOp: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicatesForGetAsset }; //Obtain the uri of the album - let albumFetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let predicates = new dataSharePredicates.DataSharePredicates(); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.orderByAsc("add_modified"); - let fetchOptions = { + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let photoFetchResult = await album.getAssets(fetchOptions); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); let expectIndex = 1; //Obtain the uri of the second file - let photoAsset = await photoFetchResult.getObjectByPosition(expectIndex); + let photoAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getObjectByPosition(expectIndex); photoAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => { try { @@ -1388,25 +1429,27 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('getPhotoIndexDemo'); - let predicatesForGetAsset = new dataSharePredicates.DataSharePredicates(); - let fetchOp = { + let predicatesForGetAsset: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOp: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicatesForGetAsset }; //Obtain the uri of the album - let albumFetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); - let album = await albumFetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await helper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); - let predicates = new dataSharePredicates.DataSharePredicates(); + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); predicates.orderByAsc("add_modified"); - let fetchOptions = { + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let photoFetchResult = await album.getAssets(fetchOptions); + let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions); let expectIndex = 1; //Obtain the uri of the second file let photoAsset = await photoFetchResult.getObjectByPosition(expectIndex); @@ -1541,19 +1584,21 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('photoAssetGetDemo'); try { - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset = await fetchResult.getFirstObject(); - let title = photoAccessHelper.PhotoKeys.TITLE; - let photoAssetTitle = photoAsset.get(title.toString()); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE; + let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title.toString()); console.info('photoAsset Get photoAssetTitle = ', photoAssetTitle); } catch (err) { console.error('release failed. message = ', err); @@ -1588,18 +1633,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('photoAssetSetDemo'); try { - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset = await fetchResult.getFirstObject(); - let title = photoAccessHelper.PhotoKeys.TITLE.toString(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE.toString(); photoAsset.set(title, 'newTitle'); } catch (err) { console.error('release failed. message = ', err); @@ -1635,23 +1682,25 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('commitModifyDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOption = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset = await fetchResult.getFirstObject(); - let title = photoAccessHelper.PhotoKeys.TITLE.toString(); - let photoAssetTitle = photoAsset.get(title); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE.toString(); + let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); console.info('photoAsset get photoAssetTitle = ', photoAssetTitle); photoAsset.set(title, 'newTitle2'); photoAsset.commitModify((err) => { if (err == undefined) { - let newPhotoAssetTitle = photoAsset.get(title); + let newPhotoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); console.info('photoAsset get newPhotoAssetTitle = ', newPhotoAssetTitle); } else { console.error('commitModify failed, message =', err); @@ -1688,23 +1737,25 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('commitModifyDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: ['title'], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset = await fetchResult.getFirstObject(); - let title = photoAccessHelper.PhotoKeys.TITLE.toString(); - let photoAssetTitle = photoAsset.get(title); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); + let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE.toString(); + let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); console.info('photoAsset get photoAssetTitle = ', photoAssetTitle); photoAsset.set(title, 'newTitle3'); try { await photoAsset.commitModify(); - let newPhotoAssetTitle = photoAsset.get(title); + let newPhotoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title); console.info('photoAsset get newPhotoAssetTitle = ', newPhotoAssetTitle); } catch (err) { console.error('release failed. message = ', err); @@ -1747,7 +1798,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts async function example() { console.info('openDemo'); - let testFileName = 'testFile' + Date.now() + '.jpg'; + let testFileName: string = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); photoAsset.open('rw', (err, fd) => { if (fd != undefined) { @@ -1801,7 +1852,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err async function example() { console.info('openDemo'); try { - let testFileName = 'testFile' + Date.now() + '.jpg'; + let testFileName: string = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); let fd = await photoAsset.open('rw'); if (fd != undefined) { @@ -1847,7 +1898,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts async function example() { console.info('getReadOnlyFdDemo'); - let testFileName = 'testFile' + Date.now() + '.jpg'; + let testFileName: string = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); photoAsset.getReadOnlyFd((err, fd) => { if (fd != undefined) { @@ -1892,7 +1943,7 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err async function example() { console.info('getReadOnlyFdDemo'); try { - let testFileName = 'testFile' + Date.now() + '.jpg'; + let testFileName: string = 'testFile' + Date.now() + '.jpg'; const photoAsset = await phAccessHelper.createAsset(testFileName); let fd = await photoAsset.getReadOnlyFd(); if (fd != undefined) { @@ -1934,16 +1985,18 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('closeDemo'); try { - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const photoAsset = await fetchResult.getFirstObject(); let fd = await photoAsset.open('rw'); console.info('file fd', fd); @@ -1992,16 +2045,18 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('closeDemo'); try { - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); let fd = await asset.open('rw'); console.info('file fd', fd); @@ -2041,15 +2096,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getThumbnailDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); console.info('asset displayName = ', asset.displayName); asset.getThumbnail((err, pixelMap) => { @@ -2091,16 +2147,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; +import image from '@ohos.multimedia.image'; + + async function example() { console.info('getThumbnailDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let size = { width: 720, height: 720 }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let size: image.Size = { width: 720, height: 720 }; + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); console.info('asset displayName = ', asset.displayName); asset.getThumbnail(size, (err, pixelMap) => { @@ -2147,16 +2207,19 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; +import image from '@ohos.multimedia.image'; + async function example() { console.info('getThumbnailDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let size = { width: 720, height: 720 }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let size: image.Size = { width: 720, height: 720 }; + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); console.info('asset displayName = ', asset.displayName); asset.getThumbnail(size).then((pixelMap) => { @@ -2199,15 +2262,17 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('setFavoriteDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setFavorite(true, (err) => { if (err == undefined) { @@ -2256,15 +2321,17 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('setFavoriteDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setFavorite(true).then(function () { console.info('setFavorite successfully'); @@ -2308,15 +2375,17 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { console.info('setHiddenDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setHidden(true, (err) => { if (err == undefined) { @@ -2367,18 +2436,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { // Restore a file from a hidden album. Before the operation, ensure that the file exists in the hidden album. console.info('setHiddenDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumList = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.HIDDEN); + let albumList: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.HIDDEN); const album = await albumList.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); const asset = await fetchResult.getFirstObject(); asset.setHidden(false).then(() => { console.info('setHidden successfully'); @@ -2453,17 +2524,19 @@ For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#proper ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { try { console.info('getExifDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [ 'all_exif', photoKeys.USER_COMMENT], predicates: predicates }; - 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(); let exifMessage = await fileAsset.getExif(); let userCommentKey = 'UserComment'; let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]); @@ -2539,17 +2612,19 @@ For details about the EXIF tags, see [image.PropertyKey](js-apis-image.md#proper ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { try { console.info('getExifDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [ 'all_exif', photoKeys.USER_COMMENT], predicates: predicates }; - 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(); let userCommentKey = 'UserComment'; fileAsset.getExif((err, exifMessage) => { if (exifMessage != undefined) { @@ -2595,17 +2670,19 @@ Sets user comment information of an image or video. This API uses a promise to r ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { try { console.info('setUserCommentDemo') - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - 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(); let userComment = 'test_set_user_comment'; await fileAsset.setUserComment(userComment); } catch (err) { @@ -2639,17 +2716,19 @@ Sets user comment information of an image or video. This API uses an asynchronou ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + async function example() { try { console.info('setUserCommentDemo') - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - 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(); let userComment = 'test_set_user_comment'; fileAsset.setUserComment(userComment, (err) => { if (err === undefined) { @@ -2694,15 +2773,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getCountDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const fetchCount = fetchResult.getCount(); console.info('fetchCount = ', fetchCount); } @@ -2734,17 +2814,18 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); const fetchCount = fetchResult.getCount(); console.info('count:' + fetchCount); - let photoAsset = await fetchResult.getLastObject(); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getLastObject(); if (fetchResult.isAfterLast()) { console.info('photoAsset isAfterLast displayName = ', photoAsset.displayName); } else { @@ -2773,16 +2854,17 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('fetchResultCloseDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; try { - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.close(); console.info('close succeed.'); } catch (err) { @@ -2817,15 +2899,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getFirstObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getFirstObject((err, photoAsset) => { if (photoAsset != undefined) { console.info('photoAsset displayName: ', photoAsset.displayName); @@ -2862,16 +2945,17 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getFirstObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset = await fetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); console.info('photoAsset displayName: ', photoAsset.displayName); } ``` @@ -2902,15 +2986,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getNextObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); await fetchResult.getFirstObject(); if (fetchResult.isAfterLast()) { fetchResult.getNextObject((err, photoAsset) => { @@ -2950,15 +3035,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getNextObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); await fetchResult.getFirstObject(); if (fetchResult.isAfterLast()) { let photoAsset = await fetchResult.getNextObject(); @@ -2993,15 +3079,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getLastObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getLastObject((err, photoAsset) => { if (photoAsset != undefined) { console.info('photoAsset displayName: ', photoAsset.displayName); @@ -3038,16 +3125,17 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getLastObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset = await fetchResult.getLastObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getLastObject(); console.info('photoAsset displayName: ', photoAsset.displayName); } ``` @@ -3079,15 +3167,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getObjectByPositionDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getObjectByPosition(0, (err, photoAsset) => { if (photoAsset != undefined) { console.info('photoAsset displayName: ', photoAsset.displayName); @@ -3130,16 +3219,17 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getObjectByPositionDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAsset = await fetchResult.getObjectByPosition(0); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getObjectByPosition(0); console.info('photoAsset displayName: ', photoAsset.displayName); } ``` @@ -3170,15 +3260,16 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getAllObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); fetchResult.getAllObjects((err, photoAssetList) => { if (photoAssetList != undefined) { console.info('photoAssetList length: ', photoAssetList.length); @@ -3215,16 +3306,17 @@ For details about the error codes, see [File Management Error Codes](../errorcod ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('getAllObjectDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let photoAssetList = await fetchResult.getAllObjects(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let photoAssetList: photoAccessHelper.PhotoAsset = await fetchResult.getAllObjects(); console.info('photoAssetList length: ', photoAssetList.length); } ``` @@ -3275,15 +3367,16 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumGetAssetsDemoCallback'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchOption = { + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -3333,16 +3426,17 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumGetAssetsDemoPromise'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let fetchOption = { + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -3384,11 +3478,12 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumCommitModifyDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -3433,11 +3528,12 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { console.info('albumCommitModifyDemo'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let albumFetchOptions = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; @@ -3481,19 +3577,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('addAssetsDemoCallback'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.addAssets([asset], (err) => { if (err === undefined) { console.info('album addAssets successfully'); @@ -3541,19 +3638,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('addAssetsDemoPromise'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await phAccessHelper.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.addAssets([asset]).then(() => { console.info('album addAssets successfully'); }).catch((err) => { @@ -3594,19 +3692,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('removeAssetsDemoCallback'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.removeAssets([asset], (err) => { if (err === undefined) { console.info('album removeAssets successfully'); @@ -3654,19 +3753,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('removeAssetsDemoPromise'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.removeAssets([asset]).then(() => { console.info('album removeAssets successfully'); }).catch((err) => { @@ -3710,19 +3810,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('recoverAssetsDemoCallback'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.recoverAssets([asset], (err) => { if (err === undefined) { console.info('album recoverAssets successfully'); @@ -3773,19 +3874,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('recoverAssetsDemoPromise'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.recoverAssets([asset]).then(() => { console.info('album recoverAssets successfully'); }).catch((err) => { @@ -3831,19 +3933,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('deleteAssetsDemoCallback'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.deleteAssets([asset], (err) => { if (err === undefined) { console.info('album deleteAssets successfully'); @@ -3896,19 +3999,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('deleteAssetsDemoPromise'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.deleteAssets([asset]).then(() => { console.info('album deleteAssets successfully'); }).catch((err) => { @@ -3954,19 +4058,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('setCoverUriDemoCallback'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.setCoverUri(asset.uri, (err) => { if (err === undefined) { console.info('album setCoverUri successfully'); @@ -4019,19 +4124,20 @@ For details about the error codes, see [Universal Error Codes](../errorcodes/err ```ts import dataSharePredicates from '@ohos.data.dataSharePredicates'; +import photoAccessHelper from '@ohos.file.photoAccessHelper'; async function example() { try { console.info('setCoverUriDemoCallback'); - let predicates = new dataSharePredicates.DataSharePredicates(); - let fetchOption = { + let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption: photoAccessHelper.FetchOptions = { fetchColumns: [], predicates: predicates }; - let albumFetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); - let album = await albumFetchResult.getFirstObject(); - let fetchResult = await album.getAssets(fetchOption); - let asset = await fetchResult.getFirstObject(); + let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC); + let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject(); + let fetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOption); + let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); album.setCoverUri(asset.uri, (err) => { if (err === undefined) { console.info('album setCoverUri successfully'); diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 9f949c10e762e34ae641d648d676f0d754c9b52c..39d64c64f8d0f015b44823b5fe87f42f8a06bde2 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -850,7 +850,7 @@ Enumerates mouse pointer styles. | MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east |![MID_Btn_South_East.png](./figures/MID_Btn_South_East.png)| | MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west |![MID_Btn_South_West.png](./figures/MID_Btn_South_West.png)| | MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions|![MID_Btn_North_South_West_East.png](./figures/MID_Btn_North_South_West_East.png)| -| HORIZONTAL_TEXT_CURSOR10+ | 39 | Horizontal text selection|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)| +| HORIZONTAL_TEXT_CURSOR10+ | 39 | Horizontal text cursor|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)| | CURSOR_CROSS10+ | 40 | Cross cursor|![Cursor_Cross.png](./figures/Cursor_Cross.png)| | CURSOR_CIRCLE10+ | 41 | Circular cursor|![Cursor_Circle.png](./figures/Cursor_Circle.png)| @@ -1726,3 +1726,357 @@ try { console.log(`getTouchpadRightClickType failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` + +## pointer.setPointerSize10+ + +setPointerSize(size: number, callback: AsyncCallback<void>): void + +Sets the pointer size. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------------------- | +| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +try { + pointer.setPointerSize(1, (error) => { + if (error) { + console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`setPointerSize success`); + }); +} catch (error) { + console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setPointerSize10+ + +setPointerSize(size: number): Promise<void> + +Sets the pointer size. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**.| + +**Return value** + +| Name | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +try { + pointer.setPointerSize(3).then(() => { + console.log(`setPointerSize success`); + }); +} catch (error) { + console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setPointerSizeSync10+ + +setPointerSizeSync(size: number): void; + +Sets the pointer size. This API returns the result synchronously. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**.| + +**Example** + +```js +try { + pointer.setPointerSizeSync(5); + console.log(`setPointerSizeSync success`); +} catch (error) { + console.log(`setPointerSizeSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerSize10+ + +getPointerSize(callback: AsyncCallback<number>): void + +Obtains the pointer size. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.getPointerSize((error, size) => { + console.log(`getPointerSize success, size: ${JSON.stringify(size)}`); + }); +} catch (error) { + console.log(`getPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerSize10+ + +getPointerSize(): Promise<number> + +Obtains the pointer size. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| Promise<number> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.getPointerSize().then((size) => { + console.log(`getPointerSize success, size: ${JSON.stringify(size)}`); + }); +} catch (error) { + console.log(`getPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerSizeSync10+ + +getPointerSizeSync(): number + +Obtains the pointer size. This API returns the result synchronously. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| number | Pointer size. | + +**Example** + +```js +try { + let pointerSize = pointer.getPointerSizeSync(); + console.log(`getPointerSizeSync success, pointerSize: ${JSON.stringify(pointerSize)}`); +} catch (error) { + console.log(`getPointerSizeSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setPointerColor10+ + +setPointerColor(color: number, callback: AsyncCallback<void>): void + +Sets the pointer color. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------------------- | +| color | number | Yes | Pointer color. The default value is **black** (0x000000). | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +try { + pointer.setPointerColor(0xF6C800, (error) => { + if (error) { + console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`setPointerColor success`); + }); +} catch (error) { + console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setPointerColor10+ + +setPointerColor(color: number): Promise<void> + +Sets the pointer color. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| color | number | Yes | Pointer color. The default value is **black** (0x000000).| + +**Return value** + +| Name | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +try { + pointer.setPointerColor(0xF6C800).then(() => { + console.log(`setPointerColor success`); + }); +} catch (error) { + console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setPointerColorSync10+ + +setPointerColorSync(color: number): void; + +Sets the pointer color. This API returns the result synchronously. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| color | number | Yes | Pointer color. The default value is **black** (0x000000).| + +**Example** + +```js +try { + pointer.setPointerColorSync(0xF6C800); + console.log(`setPointerColorSync success`); +} catch (error) { + console.log(`setPointerColorSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerColor10+ + +getPointerColor(callback: AsyncCallback<number>): void + +Obtains the pointer color. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.getPointerColor((error, color) => { + console.log(`getPointerColor success, color: ${JSON.stringify(color)}`); + }); +} catch (error) { + console.log(`getPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerColor10+ + +getPointerColor(): Promise<number> + +Obtains the pointer color. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| Promise<number> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.getPointerColor().then((color) => { + console.log(`getPointerColor success, color: ${JSON.stringify(color)}`); + }); +} catch (error) { + console.log(`getPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerColorSync10+ + +getPointerColorSync(): number + +Obtains the pointer color. This API returns the result synchronously. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**System API**: This is a system API. + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| number | Pointer color.| + +**Example** + +```js +try { + let pointerColor = pointer.getPointerColorSync(); + console.log(`getPointerColorSync success, pointerColor: ${JSON.stringify(pointerColor)}`); +} catch (error) { + console.log(`getPointerColorSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md index b5cda219aca77e3aefb888c1793f7f9e7b2d3f0a..c2992be105f8e5e73fdf2078e0792f6142737a82 100644 --- a/en/application-dev/reference/apis/js-apis-promptAction.md +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -191,7 +191,10 @@ Describes the options for showing the dialog box. | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | | message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Text body. | -| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| +| buttons | Array<[Button](#button)> | No | Array of buttons in the dialog box. The array structure is {text:'button', color: '\#666666'}. More than one button is supported. +| alignment10+ | [DialogAlignment](../arkui-ts/ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| +| offset10+ | [Offset](../arkui-ts/ts-types.md#offset) | No | Offset of the dialog box based on the **alignment** settings.
Default value: **{ dx: 0 , dy: 0 }**| +| maskRect10+| [Rectangle](../arkui-ts/ts-methods-alert-dialog-box.md#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| ## ShowDialogSuccessResponse diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 644759435975c722de9fd274b704ecd01804d2fd..de1e1e04ddfc51d5e24ef783f022ab2f400f09dc 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,8 +1,6 @@ -# @ohos.reminderAgentManager (reminderAgentManager) +# @ohos.reminderAgentManager (Agent-Powered Reminders) -The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. - -You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +The **reminderAgentManager** module provides APIs related to agent-powered reminders. When your application is frozen or exits, the timing and notification functions of your application will be taken over by a system service running in the background. You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. > **NOTE** > @@ -15,12 +13,15 @@ You can use the APIs to create scheduled reminders for countdown timers, calenda import reminderAgentManager from'@ohos.reminderAgentManager'; ``` - ## reminderAgentManager.publishReminder publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void -Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). +Publishes a reminder. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API can be called only after the [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8) permission is obtained. **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER @@ -28,10 +29,10 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.| +| callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Error codes** @@ -62,26 +63,29 @@ try { }; ``` - ## reminderAgentManager.publishReminder publishReminder(reminderReq: ReminderRequest): Promise\ -Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). +Publishes a reminder. This API uses a promise to return the result. + +> **NOTE** +> +> This API can be called only after the [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8) permission is obtained. **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise\ | Promise used to return the published reminder's ID.| +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the published reminder's ID.| **Error codes** @@ -115,7 +119,7 @@ try { cancelReminder(reminderId: number, callback: AsyncCallback\): void -Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. +Cancels a reminder published. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -124,7 +128,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the reminder is canceled, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -151,12 +155,11 @@ try { }; ``` - ## reminderAgentManager.cancelReminder cancelReminder(reminderId: number): Promise\ -Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. +Cancels a reminder published. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -170,7 +173,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -199,8 +202,7 @@ try { getValidReminders(callback: AsyncCallback>): void - -Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. +Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -208,7 +210,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\> | Yes| Callback used to return all the valid reminders.| **Error codes** @@ -259,7 +261,7 @@ try { getValidReminders(): Promise\> -Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. +Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -267,7 +269,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\> | Promise used to return all the valid reminders.| **Error codes** @@ -312,12 +314,11 @@ try { }; ``` - ## reminderAgentManager.cancelAllReminders cancelAllReminders(callback: AsyncCallback\): void -Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. +Cancels all reminders set by the current application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -325,7 +326,7 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If all the reminders are canceled, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** @@ -351,12 +352,11 @@ try { }; ``` - ## reminderAgentManager.cancelAllReminders cancelAllReminders(): Promise\ -Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. +Cancels all reminders set by the current application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -364,7 +364,7 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -401,8 +401,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the notification slot is added, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -438,13 +438,13 @@ Adds a notification slot. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.| **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -470,7 +470,7 @@ try { removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\): void -Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. +Removes a notification slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -479,7 +479,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the notification slot is removed, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -504,7 +504,7 @@ try { removeNotificationSlot(slotType: notification.SlotType): Promise\ -Removes a notification slot of a specified type. This API uses a promise to return the result. +Removes a notification slot. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -518,7 +518,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -538,7 +538,7 @@ try { ## ActionButtonType -Enumerates button types. +Enumerates the button types. **System capability**: SystemCapability.Notification.ReminderAgent @@ -551,7 +551,7 @@ Enumerates button types. ## ReminderType -Enumerates reminder types. +Enumerates the reminder types. **System capability**: SystemCapability.Notification.ReminderAgent @@ -564,8 +564,7 @@ Enumerates reminder types. ## ActionButton -Defines a button displayed for the reminder in the notification panel. - +Defines the button on the reminder displayed. **System capability**: SystemCapability.Notification.ReminderAgent @@ -573,7 +572,7 @@ Defines a button displayed for the reminder in the notification panel. | -------- | -------- | -------- | -------- | | title | string | Yes| Text on the button.| | type | [ActionButtonType](#actionbuttontype) | Yes| Button type.| -| wantAgent10+ | [WantAgent](#wantagent) | No| Ability information that is displayed after the button is clicked.
**System API**: This is a system API and cannot be called by third-party applications.| +| wantAgent10+ | [WantAgent](#wantagent) | No| Information about the ability that is displayed after the button is clicked.
**System API**: This is a system API and cannot be called by third-party applications.| ## WantAgent @@ -592,19 +591,19 @@ Defines the information about the redirected-to ability. ## MaxScreenWantAgent -Provides the information about the target package and ability to start automatically when the reminder is displayed in full-screen mode. This API is reserved. +Provides the information about the ability that is started automatically and displayed in full-screen mode when the reminder arrives. This API is reserved. **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| -| abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the target package. (If the device is in use, only a notification banner is displayed.)| +| abilityName | string | Yes| Name of the target ability. (If the device is in use, only a notification banner is displayed.)| ## ReminderRequest -Defines the reminder to publish. +Defines the request for publishing a reminder. **System capability**: SystemCapability.Notification.ReminderAgent @@ -613,7 +612,7 @@ Defines the reminder to publish. | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| | actionButton | [ActionButton](#actionbutton) | No| Buttons displayed for the reminder in the notification panel.
- For common applications, a maximum of two buttons are supported.
- For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.| -| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| +| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is started automatically and displayed in full-screen mode when the reminder arrives. If the device is in use, only a notification banner is displayed.
This API is reserved.| | ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| | snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| | timeInterval | number | No| Reminder snooze interval, in seconds. The minimum value is 5 minutes.| @@ -623,8 +622,8 @@ Defines the reminder to publish. | snoozeContent | string | No| Content to be displayed when the reminder is snoozing.| | notificationId | number | No| Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.| | slotType | [notification.SlotType](js-apis-notificationManager.md#slottype) | No| Type of the slot used by the reminder.| -| tapDismissed10+ | boolean | No| Whether the notification is automatically cleared. The value is the same as that of [NotificationRequest.tapDismissed](js-apis-inner-notification-notificationRequest.md#notificationrequest).| -| autoDeletedTime10+ | number | No| Time when the notification is automatically cleared. The value is the same as that of [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).| +| tapDismissed10+ | boolean | No| Whether the reminder is automatically cleared. For details, see [NotificationRequest.tapDismissed](js-apis-inner-notification-notificationRequest.md#notificationrequest). | +| autoDeletedTime10+ | number | No| Time when the reminder is automatically cleared. For details, see [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).| ## ReminderRequestCalendar diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 40cb3dc087b7b7a756a602925699597ec557c294..d4807f0517fc537ac7283d612c856dae10c235d7 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -22,10 +22,10 @@ For details about how to reference context in the stage model, see [Context in t import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - let context = this.context; - let resourceManager = context.resourceManager; - } + onWindowStageCreate(windowStage) { + let context = this.context; + let resourceManager = context.resourceManager; + } } ``` @@ -48,17 +48,17 @@ Obtains the **ResourceManager** object of this application. This API uses an asy **Example** ```js resourceManager.getResourceManager((error, mgr) => { + if (error != null) { + console.log("error is " + error); + return; + } + mgr.getStringValue(0x1000000, (error, value) => { if (error != null) { - console.log("error is " + error); - return; + console.log("error is " + error); + } else { + let str = value; } - mgr.getStringValue(0x1000000, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + }); }); ``` > **NOTE**
In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file. @@ -107,15 +107,15 @@ Obtains the **ResourceManager** object of this application. This API uses a prom **Example** ```js resourceManager.getResourceManager().then(mgr => { - mgr.getStringValue(0x1000000, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + mgr.getStringValue(0x1000000, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); }).catch(error => { - console.log("error is " + error); + console.log("error is " + error); }); ``` > **NOTE**
In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file. @@ -150,7 +150,6 @@ Obtains the **ResourceManager** object of an application based on the specified }); ``` - ## resourceManager.getSystemResourceManager10+ getSystemResourceManager(): ResourceManager @@ -177,16 +176,16 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```js import resourceManager from '@ohos.resourceManager'; -try { + try { let systemResourceManager = resourceManager.getSystemResourceManager(); systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then(value => { - let str = value; + let str = value; }).catch(error => { - console.log("systemResourceManager getStringValue promise error is " + error); + console.log("systemResourceManager getStringValue promise error is " + error); }); -} catch (error) { + } catch (error) { console.error(`systemResourceManager getStringValue failed, error code: ${error.code}, message: ${error.message}.`); -} + } ``` @@ -259,7 +258,7 @@ Defines the device capability. | Name | Type | Readable | Writable | Description | | ------------- | ------------------------------- | ---- | ---- | -------- | | screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device.| -| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. | +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | ## RawFileDescriptor8+ @@ -301,20 +300,25 @@ Defines the capability of accessing application resources. > > - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**. -### getStringValue9+ +### getStringSync9+ -getStringValue(resId: number, callback: AsyncCallback<string>): void +getStringSync(resId: number): string -Obtains the string corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string corresponding to the specified resource ID. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** + +| Type | Description | +| ------ | ----------- | +| string | String corresponding to the specified resource ID.| **Error codes** @@ -322,31 +326,24 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the module resId invalid. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | -**Example (stage)** +**Example** ```ts - try { - this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); - } catch (error) { - console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`); - } + try { + this.context.resourceManager.getStringSync($r('app.string.test').id); + } catch (error) { + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + } ``` +### getStringSync10+ -### getStringValue9+ - -getStringValue(resId: number): Promise<string> +getStringSync(resId: number, ...args: Array): string -Obtains the string corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -355,42 +352,39 @@ Obtains the string corresponding to the specified resource ID. This API uses a p | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | | resId | number | Yes | Resource ID.| +| args | Array | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| **Return value** -| Type | Description | -| --------------------- | ----------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ------ | ---------------------------- | +| string | Formatted string.| **Error codes** For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). | ID| Error Message| -| -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| -------- | ----------------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | +| 9001007 | If the resource obtained by resId formatting error. | **Example** ```ts try { - this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => { - let str = value; - }).catch(error => { - console.log("getStringValue promise error is " + error); - }); + this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 10, 98.78); } catch (error) { - console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` +### getStringSync9+ -### getStringValue9+ - -getStringValue(resource: Resource, callback: AsyncCallback<string>): void +getStringSync(resource: Resource): string -Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result. +Obtains the string corresponding to the specified resource object. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -398,10 +392,15 @@ Obtains the string corresponding to the specified resource object. This API uses **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------- | -| resource | [Resource](#resource9) | Yes | Resource object. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| string | String corresponding to the specified resource object.| **Error codes** @@ -416,30 +415,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.string.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.string.test').id }; try { - this.context.resourceManager.getStringValue(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + this.context.resourceManager.getStringSync(resource); } catch (error) { - console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); } - ``` +### getStringSync10+ -### getStringValue9+ - -getStringValue(resource: Resource): Promise<string> +getStringSync(resource: Resource, ...args: Array): string -Obtains the string corresponding to the specified resource object. This API uses a promise to return the result. +Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -450,12 +441,13 @@ Obtains the string corresponding to the specified resource object. This API uses | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | Yes | Resource object.| +| args | Array | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| **Return value** -| Type | Description | -| --------------------- | ---------------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ------ | ---------------------------- | +| string | Formatted string.| **Error codes** @@ -466,40 +458,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | | 9001006 | If the resource re-ref too much. | +| 9001007 | If the resource obtained by resId formatting error. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.string.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.string.test').id }; try { - this.context.resourceManager.getStringValue(resource).then(value => { - let str = value; - }).catch(error => { - console.log("getStringValue promise error is " + error); - }); + this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78); } catch (error) { - console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); } - ``` - + ``` -### getStringArrayValue9+ +### getStringByNameSync9+ -getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): void +getStringByNameSync(resName: string): string -Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string corresponding to the specified resource name. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| + +**Return value** + +| Type | Description | +| ------ | ---------- | +| string | String corresponding to the specified resource name.| **Error codes** @@ -507,45 +500,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | | 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let strArray = value; - } - }); + this.context.resourceManager.getStringByNameSync("test"); } catch (error) { - console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` +### getStringByNameSync10+ -### getStringArrayValue9+ - -getStringArrayValue(resId: number): Promise<Array<string>> +getStringByNameSync(resName: string, ...args: Array): string -Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string corresponding to the specified resource name and formats the string based on **args**. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| args | Array | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| **Return value** -| Type | Description | -| ---------------------------------- | ------------- | -| Promise<Array<string>> | Promise used to return the result.| +| Type | Description | +| ------ | ---------------------------- | +| string | Formatted string.| **Error codes** @@ -553,39 +540,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | | 9001006 | If the resource re-ref too much. | +| 9001008 | If the resource obtained by resName formatting error. | **Example** ```ts try { - this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => { - let strArray = value; - }).catch(error => { - console.log("getStringArrayValue promise error is " + error); - }); + this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78); } catch (error) { - console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`); } - ``` + ``` -### getStringArrayValue9+ +### getStringValue9+ -getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<string>>): void +getStringValue(resId: number, callback: AsyncCallback<string>): void -Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result. +Obtains the string corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------- | -| resource | [Resource](#resource9) | Yes | Resource object. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -593,51 +575,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| 9001001 | If the module resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | -**Example** +**Example (stage)** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.strarray.test').id - }; try { - this.context.resourceManager.getStringArrayValue(resource, (error, value) => { + this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => { if (error != null) { - console.log("error is " + error); + console.log("error is " + error); } else { - let strArray = value; + let str = value; } }); } catch (error) { - console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringArrayValue9+ +### getStringValue9+ -getStringArrayValue(resource: Resource): Promise<Array<string>> +getStringValue(resId: number): Promise<string> -Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result. +Obtains the string corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ---------------------------------- | ------------------ | -| Promise<Array<string>> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -651,36 +626,33 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.strarray.test').id - }; try { - this.context.resourceManager.getStringArrayValue(resource).then(value => { - let strArray = value; + this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => { + let str = value; }).catch(error => { - console.log("getStringArray promise error is " + error); + console.log("getStringValue promise error is " + error); }); } catch (error) { - console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent9+ +### getStringValue9+ -getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void +getStringValue(resource: Resource, callback: AsyncCallback<string>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ------------------ | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resource | [Resource](#resource9) | Yes | Resource object. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -690,37 +662,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.string.test').id + }; try { - this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } + this.context.resourceManager.getStringValue(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } }); } catch (error) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent10+ +### getStringValue9+ -getMediaContent(resId: number, density: number, callback: AsyncCallback<Uint8Array>): void +getStringValue(resource: Resource): Promise<string> -Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string corresponding to the specified resource object. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ------------------ | -| resId | number | Yes | Resource ID. | -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -730,41 +714,85 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.string.test').id + }; try { - this.context.resourceManager.getMediaContent($r('app.media.test').id, 120, (error, value) => { - if (error != null) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getStringValue(resource).then(value => { + let str = value; + }).catch(error => { + console.log("getStringValue promise error is " + error); }); } catch (error) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent9+ +### getStringByName9+ -getMediaContent(resId: number): Promise<Uint8Array> +getStringByName(resName: string, callback: AsyncCallback<string>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + try { + this.context.resourceManager.getStringByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getStringByName9+ + +getStringByName(resName: string): Promise<string> + +Obtains the string corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| ------------------------- | -------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | ---------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -772,27 +800,28 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => { - let media = value; - }).catch(error => { - console.log("getMediaContent promise error is " + error); - }); + this.context.resourceManager.getStringByName("test").then(value => { + let str = value; + }).catch(error => { + console.log("getStringByName promise error is " + error); + }); } catch (error) { - console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent10+ +### getStringArrayValueSync10+ -getMediaContent(resId: number, density: number): Promise<Uint8Array> +getStringArrayValueSync(resId: number): Array<string> -Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string array corresponding to the specified resource ID. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -801,13 +830,12 @@ Obtains the content of the media file with the screen density corresponding to t | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | | resId | number | Yes | Resource ID.| -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | **Return value** -| Type | Description | -| ------------------------- | -------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------- | +| Array<string> | String array corresponding to the specified resource ID.| **Error codes** @@ -817,25 +845,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => { - let media = value; - }).catch(error => { - console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); - }); + this.context.resourceManager.getStringArrayValueSync($r('app.strarray.test').id); } catch (error) { - console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getStringArrayValueSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent9+ +### getStringArrayValueSync10+ -getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): void +getStringArrayValueSync(resource: Resource): Array<string> -Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result. +Obtains the string array corresponding to the specified resource object. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -843,10 +868,15 @@ Obtains the content of the media file corresponding to the specified resource ob **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ------------------ | -| resource | [Resource](#resource9) | Yes | Resource object. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| --------------------- | ----------- | +| Array<string> | String array corresponding to the specified resource object.| **Error codes** @@ -856,44 +886,36 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.strarray.test').id }; try { - this.context.resourceManager.getMediaContent(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); + this.context.resourceManager.getStringArrayValueSync(resource); } catch (error) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getStringArrayValueSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent10+ +### getStringArrayValue9+ -getMediaContent(resource: Resource, density: number, callback: AsyncCallback<Uint8Array>): void +getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): void -Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ------------------ | -| resource | [Resource](#resource9) | Yes | Resource object. | -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| **Error codes** @@ -903,48 +925,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id - }; try { - this.context.resourceManager.getMediaContent(resource, 120, (error, value) => { - if (error != null) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } }); } catch (error) { - console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent9+ +### getStringArrayValue9+ -getMediaContent(resource: Resource): Promise<Uint8Array> +getStringArrayValue(resId: number): Promise<Array<string>> -Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ------------------------- | ------------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | Promise used to return the result.| **Error codes** @@ -954,30 +970,26 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id - }; try { - this.context.resourceManager.getMediaContent(resource).then(value => { - let media = value; + this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => { + let strArray = value; }).catch(error => { - console.log("getMediaContent promise error is " + error); + console.log("getStringArrayValue promise error is " + error); }); } catch (error) { - console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContent10+ +### getStringArrayValue9+ -getMediaContent(resource: Resource, density: number): Promise<Uint8Array> +getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<string>>): void -Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses a promise to return the result. +Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -985,16 +997,10 @@ Obtains the content of the media file with the screen density corresponding to t **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | - -**Return value** - -| Type | Description | -| ------------------------- | ------------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resource | [Resource](#resource9) | Yes | Resource object. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| **Error codes** @@ -1004,39 +1010,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.strarray.test').id }; try { - this.context.resourceManager.getMediaContent(resource, 120).then(value => { - let media = value; - }).catch(error => { - console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + this.context.resourceManager.getStringArrayValue(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } }); } catch (error) { - console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase649+ +### getStringArrayValue9+ -getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void +getStringArrayValue(resource: Resource): Promise<Array<string>> -Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ------------------------ | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ------------------ | +| Promise<Array<string>> | Promise used to return the result.| **Error codes** @@ -1046,37 +1062,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.strarray.test').id + }; try { - this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); + this.context.resourceManager.getStringArrayValue(resource).then(value => { + let strArray = value; + }).catch(error => { + console.log("getStringArray promise error is " + error); + }); } catch (error) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase6410+ +### getStringArrayByName9+ -getMediaContentBase64(resId: number, density: number, callback: AsyncCallback<string>): void +getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void -Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ------------------------ | -| resId | number | Yes | Resource ID. | -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| **Error codes** @@ -1084,43 +1103,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120, (error, value) => { - if (error != null) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } - }); + this.context.resourceManager.getStringArrayByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } + }); } catch (error) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase649+ +### getStringArrayByName9+ -getMediaContentBase64(resId: number): Promise<string> +getStringArrayByName(resName: string): Promise<Array<string>> -Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| --------------------- | -------------------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ---------------------------------- | ------------ | +| Promise<Array<string>> | Promise used to return the result.| **Error codes** @@ -1128,27 +1148,28 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => { - let media = value; + this.context.resourceManager.getStringArrayByName("test").then(value => { + let strArray = value; }).catch(error => { - console.log("getMediaContentBase64 promise error is " + error); + console.log("getStringArrayByName promise error is " + error); }); } catch (error) { - console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase6410+ +### getPluralStringValueSync10+ -getMediaContentBase64(resId: number, density: number): Promise<string> +getPluralStringValueSync(resId: number, num: number): string -Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -1157,13 +1178,13 @@ Obtains the Base64 code of an image with the screen density corresponding to the | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | | resId | number | Yes | Resource ID.| -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| num | number | Yes | Number. | **Return value** -| Type | Description | -| --------------------- | -------------------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| -------- | ----------- | +| string | Singular-plural string corresponding to the specified resource ID.| **Error codes** @@ -1173,25 +1194,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => { - let media = value; - }).catch(error => { - console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); - }); + this.context.resourceManager.getPluralStringValueSync($r('app.plural.test').id, 1); } catch (error) { - console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getPluralStringValueSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase649+ +### getPluralStringValueSync10+ -getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>): void +getPluralStringValueSync(resource: Resource, num: number): string -Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result. +Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -1199,10 +1217,16 @@ Obtains the Base64 code of the image corresponding to the specified resource obj **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ------------------------ | -| resource | [Resource](#resource9) | Yes | Resource object. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resource | [Resource](#resource9) | Yes | Resource object.| +| num | number | Yes | Number. | + +**Return value** + +| Type | Description | +| --------------------- | ----------- | +| string | Singular-plural string corresponding to the specified resource object.| **Error codes** @@ -1212,43 +1236,36 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.plural.test').id }; try { - this.context.resourceManager.getMediaContentBase64(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } - }); + this.context.resourceManager.getPluralStringValueSync(resource, 1); } catch (error) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getPluralStringValueSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase6410+ +### getPluralStringValue9+ -getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback<string>): void +getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void -Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result. +Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ------------------------ | -| resource | [Resource](#resource9) | Yes | Resource object. | -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| resId | number | Yes | Resource ID. | +| num | number | Yes | Number. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -1259,48 +1276,84 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id - }; try { - this.context.resourceManager.getMediaContentBase64(resource, 120, (error, value) => { - if (error != null) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } }); } catch (error) { - console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase649+ +### getPluralStringValue9+ -getMediaContentBase64(resource: Resource): Promise<string> +getPluralStringValue(resId: number, num: number): Promise<string> -Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result. +Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| num | number | Yes | Number. | **Return value** | Type | Description | | --------------------- | ------------------------- | -| Promise<string> | Promise used to return the result.| +| Promise<string> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + +**Example** + ```ts + try { + this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => { + let str = value; + }).catch(error => { + console.log("getPluralStringValue promise error is " + error); + }); + } catch (error) { + console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getPluralStringValue9+ + +getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback<string>): void + +Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Model restriction**: This API can be used only in the stage model. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------------ | +| resource | [Resource](#resource9) | Yes | Resource object. | +| num | number | Yes | Number. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -1310,30 +1363,33 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.plural.test').id }; try { - this.context.resourceManager.getMediaContentBase64(resource).then(value => { - let media = value; - }).catch(error => { - console.log("getMediaContentBase64 promise error is " + error); + this.context.resourceManager.getPluralStringValue(resource, 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } }); } catch (error) { - console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaContentBase6410+ +### getPluralStringValue9+ -getMediaContentBase64(resource: Resource, density: number): Promise<string> +getPluralStringValue(resource: Resource, num: number): Promise<string> -Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses a promise to return the result. +Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -1344,13 +1400,13 @@ Obtains the Base64 code of an image with the screen density corresponding to the | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | Yes | Resource object.| -| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| num | number | Yes | Number. | **Return value** -| Type | Description | -| --------------------- | ------------------------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| --------------------- | ------------------------------ | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -1360,159 +1416,178 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.plural.test').id }; try { - this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => { - let media = value; + this.context.resourceManager.getPluralStringValue(resource, 1).then(value => { + let str = value; }).catch(error => { - console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.log("getPluralStringValue promise error is " + error); }); } catch (error) { - console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getConfiguration +### getPluralStringByName9+ -getConfiguration(callback: AsyncCallback<Configuration>): void +getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void -Obtains the device configuration. This API uses an asynchronous callback to return the result. +Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------- | -| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------------------- | +| resName | string | Yes | Resource name. | +| num | number | Yes | Number. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getConfiguration((error, value) => { + this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => { if (error != null) { - console.error("getConfiguration callback error is " + error); + console.log("error is " + error); } else { - let direction = value.direction; - let locale = value.locale; + let str = value; } }); } catch (error) { - console.error("getConfiguration callback error is " + error); + console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` +### getPluralStringByName9+ -### getConfiguration - -getConfiguration(): Promise<Configuration> +getPluralStringByName(resName: string, num: number): Promise<string> -Obtains the device configuration. This API uses a promise to return the result. +Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| num | number | Yes | Number. | + **Return value** -| Type | Description | -| ---------------------------------------- | ---------------- | -| Promise<[Configuration](#configuration)> | Promise used to return the result.| +| Type | Description | +| --------------------- | ---------------------- | +| Promise<string> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getConfiguration().then(value => { - let direction = value.direction; - let locale = value.locale; + this.context.resourceManager.getPluralStringByName("test", 1).then(value => { + let str = value; }).catch(error => { - console.error("getConfiguration promise error is " + error); + console.log("getPluralStringByName promise error is " + error); }); } catch (error) { - console.error("getConfiguration promise error is " + error); + console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` +### getMediaContentSync10+ -### getDeviceCapability - -getDeviceCapability(callback: AsyncCallback<DeviceCapability>): void +getMediaContentSync(resId: number, density?: number): Uint8Array -Obtains the device capability. This API uses an asynchronous callback to return the result. +Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource ID. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the result.| - -**Example** - ```ts - try { - this.context.resourceManager.getDeviceCapability((error, value) => { - if (error != null) { - console.error("getDeviceCapability callback error is " + error); - } else { - let screenDensity = value.screenDensity; - let deviceType = value.deviceType; - } - }); - } catch (error) { - console.error("getDeviceCapability callback error is " + error); - } - ``` - - -### getDeviceCapability +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| -getDeviceCapability(): Promise<DeviceCapability> +**Return value** -Obtains the device capability. This API uses a promise to return the result. +| Type | Description | +| -------- | ----------- | +| Uint8Array | Content of the media file corresponding to the specified resource ID.| -**System capability**: SystemCapability.Global.ResourceManager +**Error codes** -**Return value** +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). -| Type | Description | -| ---------------------------------------- | ------------------- | -| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getDeviceCapability().then(value => { - let screenDensity = value.screenDensity; - let deviceType = value.deviceType; - }).catch(error => { - console.error("getDeviceCapability promise error is " + error); - }); + this.context.resourceManager.getMediaContentSync($r('app.media.test').id); // Default screen density } catch (error) { - console.error("getDeviceCapability promise error is " + error); + console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`); + } + + try { + this.context.resourceManager.getMediaContentSync($r('app.media.test').id, 120); // Specified screen density + } catch (error) { + console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getPluralStringValue9+ +### getMediaContentSync10+ -getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void +getMediaContentSync(resource: Resource, density?: number): Uint8Array -Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result. +Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource object. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ------------------------------- | -| resId | number | Yes | Resource ID. | -| num | number | Yes | Number. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resource | [Resource](#resource9) | Yes | Resource object.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| + +**Return value** + +| Type | Description | +| --------------------- | ----------- | +| Uint8Array | Content of the media file corresponding to the specified resource object| **Error codes** @@ -1522,44 +1597,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); + this.context.resourceManager.getMediaContentSync(resource); // Default screen density } catch (error) { - console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`); } - ``` + try { + this.context.resourceManager.getMediaContentSync(resource, 120); // Specified screen density + } catch (error) { + console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` -### getPluralStringValue9+ +### getMediaContent9+ -getPluralStringValue(resId: number, num: number): Promise<string> +getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void -Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result. +Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| -| num | number | Yes | Number. | - -**Return value** - -| Type | Description | -| --------------------- | ------------------------- | -| Promise<string> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1569,38 +1641,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => { - let str = value; - }).catch(error => { - console.log("getPluralStringValue promise error is " + error); + this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getPluralStringValue9+ +### getMediaContent10+ -getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback<string>): void +getMediaContent(resId: number, density: number, callback: AsyncCallback<Uint8Array>): void -Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result. +Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ------------------------------------ | -| resource | [Resource](#resource9) | Yes | Resource object. | -| num | number | Yes | Number. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | Yes | Resource ID. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1610,50 +1681,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.plural.test').id - }; try { - this.context.resourceManager.getPluralStringValue(resource, 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } + this.context.resourceManager.getMediaContent($r('app.media.test').id, 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getPluralStringValue9+ +### getMediaContent9+ -getPluralStringValue(resource: Resource, num: number): Promise<string> +getMediaContent(resId: number): Promise<Uint8Array> -Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result. +Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| -| num | number | Yes | Number. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| --------------------- | ------------------------------ | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1663,41 +1725,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.plural.test').id - }; try { - this.context.resourceManager.getPluralStringValue(resource, 1).then(value => { - let str = value; + this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => { + let media = value; }).catch(error => { - console.log("getPluralStringValue promise error is " + error); + console.log("getMediaContent promise error is " + error); }); } catch (error) { - console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` +### getMediaContent10+ -### getRawFileContent9+ - -getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void +getMediaContent(resId: number, density: number): Promise<Uint8Array> -Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. +Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------------- | -| path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1705,42 +1766,38 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | If the resource not found by path. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getRawFileContent("test.xml", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let rawFile = value; - } + this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getRawFileContent9+ +### getMediaContent9+ -getRawFileContent(path: string): Promise<Uint8Array> +getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): void -Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. +Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ----------- | -| path | string | Yes | Path of the raw file.| +**Model restriction**: This API can be used only in the stage model. -**Return value** +**Parameters** -| Type | Description | -| ------------------------- | ----------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resource | [Resource](#resource9) | Yes | Resource object. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1748,36 +1805,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | If the resource not found by path. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getRawFileContent("test.xml").then(value => { - let rawFile = value; - }).catch(error => { - console.log("getRawFileContent promise error is " + error); + this.context.resourceManager.getMediaContent(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` +### getMediaContent10+ -### getRawFd9+ - -getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void +getMediaContent(resource: Resource, density: number, callback: AsyncCallback<Uint8Array>): void -Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. +Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------- | -| path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resource | [Resource](#resource9) | Yes | Resource object. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1785,44 +1852,50 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | If the resource not found by path. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getRawFd("test.xml", (error, value) => { - if (error != null) { - console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`); - } else { - let fd = value.fd; - let offset = value.offset; - let length = value.length; - } + this.context.resourceManager.getMediaContent(resource, 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getRawFd9+ +### getMediaContent9+ -getRawFd(path: string): Promise<RawFileDescriptor> +getMediaContent(resource: Resource): Promise<Uint8Array> -Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. +Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ----------- | -| path | string | Yes | Path of the raw file.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| **Return value** -| Type | Description | -| ---------------------------------------- | ------------------- | -| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| +| Type | Description | +| ------------------------- | ------------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1830,37 +1903,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | If the resource not found by path. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getRawFd("test.xml").then(value => { - let fd = value.fd; - let offset = value.offset; - let length = value.length; + this.context.resourceManager.getMediaContent(resource).then(value => { + let media = value; }).catch(error => { - console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`); + console.log("getMediaContent promise error is " + error); }); } catch (error) { - console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getRawFileList10+ +### getMediaContent10+ -getRawFileList(path: string, callback: AsyncCallback<Array\>): void; +getMediaContent(resource: Resource, density: number): Promise<Uint8Array> -Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. +Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------------- | -| path | string | Yes | Path of the **rawfile** folder. | -| callback | AsyncCallback<Array\> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1868,42 +1953,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | If the resource not found by path. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts - try { // Passing "" means to obtain the list of files in the root directory of the raw file. - this.context.resourceManager.getRawFileList("", (error, value) => { - if (error != null) { - console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let rawFile = value; - } + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; + try { + this.context.resourceManager.getMediaContent(resource, 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getRawFileList10+ +### getMediaByName9+ -getRawFileList(path: string): Promise<Array\> +getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void -Obtains the list of files in the **resources/rawfile** directory. This API uses a promise to return the result. +Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ----------- | -| path | string | Yes | Path of the **rawfile** folder.| - -**Return value** - -| Type | Description | -| ------------------------- | ----------- | -| Promise<Array\> | List of files in the **rawfile** folder.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1911,35 +1995,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | If the resource not found by path. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | **Example** ```ts - try { // Passing "" means to obtain the list of files in the root directory of the raw file. - this.context.resourceManager.getRawFileList("").then(value => { - let rawFile = value; - }).catch(error => { - console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + try { + this.context.resourceManager.getMediaByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### closeRawFd9+ +### getMediaByName10+ -closeRawFd(path: string, callback: AsyncCallback<void>): void +getMediaByName(resName: string, density: number, callback: AsyncCallback<Uint8Array>): void -Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. +Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ----------- | -| path | string | Yes | Path of the raw file.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resName | string | Yes | Resource name. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| **Error codes** @@ -1947,41 +2035,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | The resource not found by path. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | **Example** ```ts try { - this.context.resourceManager.closeRawFd("test.xml", (error, value) => { - if (error != null) { - console.log("error is " + error); - } + this.context.resourceManager.getMediaByName("test", 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` -### closeRawFd9+ +### getMediaByName9+ -closeRawFd(path: string): Promise<void> +getMediaByName(resName: string): Promise<Uint8Array> -Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. +Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ----------- | -| path | string | Yes | Path of the raw file.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| ------------------- | ---- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------------- | ------------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -1989,97 +2079,85 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001005 | If the resource not found by path. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | **Example** ```ts try { - this.context.resourceManager.closeRawFd("test.xml").then(value => { - let result = value; + this.context.resourceManager.getMediaByName("test").then(value => { + let media = value; }).catch(error => { - console.log("closeRawFd promise error is " + error); + console.log("getMediaByName promise error is " + error); }); } catch (error) { - console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`) } ``` -### release7+ +### getMediaByName10+ -release() +getMediaByName(resName: string, density: number): Promise<Uint8Array> -Releases a created **resourceManager** object. +Obtains the content of the media file (with the specified screen density) corresponding to the specified resource name. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Example** - ```ts - try { - this.context.resourceManager.release(); - } catch (error) { - console.error("release error is " + error); - } - ``` +**Parameters** -### getStringByName9+ +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | -getStringByName(resName: string, callback: AsyncCallback<string>): void +**Return value** -Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. +| Type | Description | +| ------------------------- | ------------- | +| Promise<Uint8Array> | Promise used to return the result.| -**System capability**: SystemCapability.Global.ResourceManager +**Error codes** -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------- | -| resName | string | Yes | Resource name. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result.| - -**Error codes** - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). | ID| Error Message| | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getStringByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let string = value; - } + this.context.resourceManager.getMediaByName("test", 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringByName9+ +### getMediaContentBase64Sync10+ -getStringByName(resName: string): Promise<string> +getMediaContentBase64Sync(resId: number, density?: number): string -Obtains the string corresponding to the specified resource name. This API uses a promise to return the result. +Obtains the Base64 code of the image (with the default or specified screen density) corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| **Return value** -| Type | Description | -| --------------------- | ---------- | -| Promise<string> | Promise used to return the result.| +| Type | Description | +| -------- | ----------- | +| string | Base64 code of the image corresponding to the specified resource ID.| **Error codes** @@ -2087,82 +2165,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getStringByName("test").then(value => { - let string = value; - }).catch(error => { - console.log("getStringByName promise error is " + error); - }); + this.context.resourceManager.getMediaContentBase64Sync($r('app.media.test').id); // Default screen density } catch (error) { - console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`); } - ``` - -### getStringArrayByName9+ - -getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void - -Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Global.ResourceManager - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------- | -| resName | string | Yes | Resource name. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.| - -**Error codes** - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - -| ID| Error Message| -| -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | -**Example** - ```ts try { - this.context.resourceManager.getStringArrayByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let strArray = value; - } - }); + this.context.resourceManager.getMediaContentBase64Sync($r('app.media.test').id, 120); // Specified screen density } catch (error) { - console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringArrayByName9+ +### getMediaContentBase64Sync10+ -getStringArrayByName(resName: string): Promise<Array<string>> +getMediaContentBase64Sync(resource: Resource, density?: number): string -Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result. +Obtains the Base64 code of the image (with the default or specified screen density) corresponding to the specified resource object. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resource | [Resource](#resource9) | Yes | Resource object.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| **Return value** -| Type | Description | -| ---------------------------------- | ------------ | -| Promise<Array<string>> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------- | +| string | Base64 code of the media file corresponding to the specified resource object.| **Error codes** @@ -2170,37 +2212,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getStringArrayByName("test").then(value => { - let strArray = value; - }).catch(error => { - console.log("getStringArrayByName promise error is " + error); - }); + this.context.resourceManager.getMediaContentBase64Sync(resource); // Default screen density } catch (error) { - console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`); + } + + try { + this.context.resourceManager.getMediaContentBase64Sync(resource, 120); // Specified screen density + } catch (error) { + console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaByName9+ +### getMediaContentBase649+ -getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void +getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void -Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ------------------ | -| resName | string | Yes | Resource name. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2208,39 +2256,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getMediaByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaByName10+ +### getMediaContentBase6410+ -getMediaByName(resName: string, density: number, callback: AsyncCallback<Uint8Array>): void +getMediaContentBase64(resId: number, density: number, callback: AsyncCallback<string>): void -Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ------------------ | -| resName | string | Yes | Resource name. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | Yes | Resource ID. | | [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2248,43 +2296,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getMediaByName("test", 120, (error, value) => { - if (error != null) { - console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaByName9+ +### getMediaContentBase649+ -getMediaByName(resName: string): Promise<Uint8Array> +getMediaContentBase64(resId: number): Promise<string> -Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result. +Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ------------------------- | ------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -2292,42 +2340,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getMediaByName("test").then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => { + let media = value; }).catch(error => { - console.log("getMediaByName promise error is " + error); + console.log("getMediaContentBase64 promise error is " + error); }); } catch (error) { - console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`) + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaByName10+ +### getMediaContentBase6410+ -getMediaByName(resName: string, density: number): Promise<Uint8Array> +getMediaContentBase64(resId: number, density: number): Promise<string> -Obtains the content of the media file with the screen density corresponding to the specified resource name. This API uses a promise to return the result. +Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| | [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | **Return value** -| Type | Description | -| ------------------------- | ------------- | -| Promise<Uint8Array> | Promise used to return the result.| +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -2335,35 +2383,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts try { - this.context.resourceManager.getMediaByName("test", 120).then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => { + let media = value; }).catch(error => { - console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaBase64ByName9+ +### getMediaContentBase649+ -getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void +getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>): void -Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result. +Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ------------------------ | -| resName | string | Yes | Resource name. | +| resource | [Resource](#resource9) | Yes | Resource object. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2372,37 +2422,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getMediaBase64ByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let media = value; - } + this.context.resourceManager.getMediaContentBase64(resource, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaBase64ByName10+ +### getMediaContentBase6410+ -getMediaBase64ByName(resName: string, density: number, callback: AsyncCallback<string>): void +getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback<string>): void -Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses an asynchronous callback to return the result. +Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ------------------------ | -| resName | string | Yes | Resource name. | +| resource | [Resource](#resource9) | Yes | Resource object. | | [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| @@ -2412,42 +2469,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getMediaBase64ByName("test", 120, (error, value) => { - if (error != null) { - console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); - } else { - let media = value; - } + this.context.resourceManager.getMediaContentBase64(resource, 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaBase64ByName9+ +### getMediaContentBase649+ -getMediaBase64ByName(resName: string): Promise<string> +getMediaContentBase64(resource: Resource): Promise<string> -Obtains the Base64 code of the image corresponding to the specified resource name. This API uses a promise to return the result. +Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| **Return value** -| Type | Description | -| --------------------- | ------------------- | +| Type | Description | +| --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| **Error codes** @@ -2456,41 +2520,48 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getMediaBase64ByName("test").then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64(resource).then(value => { + let media = value; }).catch(error => { - console.log("getMediaBase64ByName promise error is " + error); + console.log("getMediaContentBase64 promise error is " + error); }); } catch (error) { - console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getMediaBase64ByName10+ +### getMediaContentBase6410+ -getMediaBase64ByName(resName: string, density: number): Promise<string> +getMediaContentBase64(resource: Resource, density: number): Promise<string> -Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses a promise to return the result. +Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager +**Model restriction**: This API can be used only in the stage model. + **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---- | +| resource | [Resource](#resource9) | Yes | Resource object.| | [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | **Return value** -| Type | Description | -| --------------------- | ------------------- | +| Type | Description | +| --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| **Error codes** @@ -2499,36 +2570,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **Example** ```ts + let resource = { + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.test').id + }; try { - this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => { - let media = value; + this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => { + let media = value; }).catch(error => { - console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getPluralStringByName9+ +### getMediaBase64ByName9+ -getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void +getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void -Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result. +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ----------------------------- | -| resName | string | Yes | Resource name. | -| num | number | Yes | Number. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resName | string | Yes | Resource name. | | callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2539,44 +2614,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } + this.context.resourceManager.getMediaBase64ByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); } catch (error) { - console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` -### getPluralStringByName9+ +### getMediaBase64ByName10+ -getPluralStringByName(resName: string, num: number): Promise<string> +getMediaBase64ByName(resName: string, density: number, callback: AsyncCallback<string>): void -Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result. +Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| -| num | number | Yes | Number. | - -**Return value** - -| Type | Description | -| --------------------- | ---------------------- | -| Promise<string> | Promise used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resName | string | Yes | Resource name. | +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| **Error codes** @@ -2586,40 +2654,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getPluralStringByName("test", 1).then(value => { - let str = value; - }).catch(error => { - console.log("getPluralStringByName promise error is " + error); + this.context.resourceManager.getMediaBase64ByName("test", 120, (error, value) => { + if (error != null) { + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let media = value; + } }); } catch (error) { - console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync9+ +### getMediaBase64ByName9+ -getStringSync(resId: number): string +getMediaBase64ByName(resName: string): Promise<string> -Obtains the string corresponding to the specified resource ID. This API returns the result synchronously. +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| **Return value** -| Type | Description | -| ------ | ----------- | -| string | String corresponding to the specified resource ID.| +| Type | Description | +| --------------------- | ------------------- | +| Promise<string> | Promise used to return the result.| **Error codes** @@ -2627,81 +2696,85 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | **Example** ```ts try { - this.context.resourceManager.getStringSync($r('app.string.test').id); + this.context.resourceManager.getMediaBase64ByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaBase64ByName promise error is " + error); + }); } catch (error) { - console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync10+ +### getMediaBase64ByName10+ -getStringSync(resId: number, ...args: Array): string +getMediaBase64ByName(resName: string, density: number): Promise<string> -Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously. +Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| -| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| +| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. | **Return value** -| Type | Description | -| ------ | ---------------------------- | -| string | Formatted string.| +| Type | Description | +| --------------------- | ------------------- | +| Promise<string> | Promise used to return the result.| **Error codes** For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). | ID| Error Message| -| -------- | ----------------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | -| 9001007 | If the resource obtained by resId formatting error. | +| -------- | ---------------------------------------- | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | **Example** ```ts try { - this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 10, 98.78); + this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => { + let media = value; + }).catch(error => { + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); + }); } catch (error) { - console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync9+ +### getDrawableDescriptor10+ -getStringSync(resource: Resource): string +getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor; -Obtains the string corresponding to the specified resource object. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. - **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| **Return value** -| Type | Description | -| ------ | ---------------- | -| string | String corresponding to the specified resource object.| +| Type | Description | +| ------ | ---------- | +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** @@ -2711,27 +2784,26 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.string.test').id - }; try { - this.context.resourceManager.getStringSync(resource); + this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id); } catch (error) { - console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); + } + try { + this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getStringSync10+ +### getDrawableDescriptor10+ -getStringSync(resource: Resource, ...args: Array): string +getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; -Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -2742,13 +2814,13 @@ Obtains the string corresponding to the specified resource object and formats th | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | Yes | Resource object.| -| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| **Return value** -| Type | Description | -| ------ | ---------------------------- | -| string | Formatted string.| +| Type | Description | +| ------- | ----------------- | +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** @@ -2758,28 +2830,31 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | -| 9001007 | If the resource obtained by resId formatting error. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.string.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.media.icon').id }; try { - this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78); + this.context.resourceManager.getDrawableDescriptor(resource); } catch (error) { - console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); } - ``` + try { + this.context.resourceManager.getDrawableDescriptor(resource, 120); + } catch (error) { + console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` -### getStringByNameSync9+ +### getDrawableDescriptorByName10+ -getStringByNameSync(resName: string): string +getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor; -Obtains the string corresponding to the specified resource name. This API returns the result synchronously. +Obtains the **DrawableDescriptor** object corresponding to the specified resource name. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -2788,12 +2863,13 @@ Obtains the string corresponding to the specified resource name. This API return | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---- | | resName | string | Yes | Resource name.| +| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.| **Return value** -| Type | Description | -| ------ | ---------- | -| string | String corresponding to the specified resource name.| +| Type | Description | +| ------ | --------- | +| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| **Error codes** @@ -2803,57 +2879,20 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getStringByNameSync("test"); + this.context.resourceManager.getDrawableDescriptorByName('icon'); } catch (error) { - console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` - -### getStringByNameSync10+ - -getStringByNameSync(resName: string, ...args: Array): string - -Obtains the string corresponding to the specified resource name and formats the string based on **args**. This API returns the result synchronously. - -**System capability**: SystemCapability.Global.ResourceManager - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| -| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| string | Formatted string.| - -**Error codes** - -For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). - -| ID| Error Message| -| -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | -| 9001008 | If the resource obtained by resName formatting error. | - -**Example** - ```ts try { - this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78); + this.context.resourceManager.getDrawableDescriptorByName('icon', 120); } catch (error) { - console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`); } - ``` + ``` ### getBoolean9+ @@ -2928,9 +2967,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.boolean.boolean_test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.boolean.boolean_test').id }; try { this.context.resourceManager.getBoolean(resource); @@ -3058,9 +3097,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.integer.integer_test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.integer.integer_test').id }; try { this.context.resourceManager.getNumber(resource);// integer refers to the original value; float refers to the actual pixel value. @@ -3114,11 +3153,11 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco } ``` -### getDrawableDescriptor10+ +### getColorSync10+ -getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor; +getColorSync(resId: number) : number; -Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. This API returns the result synchronously. +Obtains the color value corresponding to the specified resource ID. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -3127,13 +3166,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | | resId | number | Yes | Resource ID.| -| [density](#screendensity) | number | No | Screen density. The default value is **0**.| **Return value** -| Type | Description | -| ------ | ---------- | -| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| +| Type | Description | +| ------ | ----------- | +| number | Color value corresponding to the resource ID (decimal).| **Error codes** @@ -3143,26 +3181,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id); - } catch (error) { - console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); - } - try { - this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120); + this.context.resourceManager.getColorSync($r('app.color.test').id); } catch (error) { - console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getDrawableDescriptor10+ +### getColorSync10+ -getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor; +getColorSync(resource: Resource): number -Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously. +Obtains the color value corresponding to the specified resource object. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -3173,13 +3207,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | Yes | Resource object.| -| [density](#screendensity) | number | No | Screen density. The default value is **0**.| **Return value** -| Type | Description | -| ------- | ----------------- | -| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| +| Type | Description | +| ------ | ---------------- | +| number | Color value corresponding to the resource object (decimal).| **Error codes** @@ -3189,31 +3222,27 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001001 | If the resId invalid. | | 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.media.icon').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id }; try { - this.context.resourceManager.getDrawableDescriptor(resource); - } catch (error) { - console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); - } - try { - this.context.resourceManager.getDrawableDescriptor(resource, 120); + this.context.resourceManager.getColorSync(resource); } catch (error) { - console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getDrawableDescriptorByName10+ +### getColorByNameSync10+ -getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor; +getColorByNameSync(resName: string) : number; -Obtains the **DrawableDescriptor** object corresponding to the specified resource name. This API returns the result synchronously. +Obtains the color value corresponding to the specified resource name. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager @@ -3222,13 +3251,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---- | | resName | string | Yes | Resource name.| -| [density](#screendensity) | number | No | Screen density. The default value is **0**.| **Return value** -| Type | Description | -| ------ | --------- | -| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.| +| Type | Description | +| ------ | ---------- | +| number | Color value corresponding to the resource name (decimal).| **Error codes** @@ -3238,18 +3266,14 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | -------- | ---------------------------------------- | | 9001003 | If the resName invalid. | | 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **Example** ```ts try { - this.context.resourceManager.getDrawableDescriptorByName('icon'); - } catch (error) { - console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`); - } - try { - this.context.resourceManager.getDrawableDescriptorByName('icon', 120); + this.context.resourceManager.getColorByNameSync("test"); } catch (error) { - console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -3280,17 +3304,17 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example (stage)** ```ts - try { - this.context.resourceManager.getColor($r('app.color.test').id, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } - }); - } catch (error) { - console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`); - } + try { + this.context.resourceManager.getColor($r('app.color.test').id, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + } catch (error) { + console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`); + } ``` ### getColor10+ @@ -3311,7 +3335,7 @@ Obtains the color value corresponding to the specified resource ID. This API use | Type | Description | | --------------------- | ----------- | -| Promise<number> | Color value corresponding to the resource ID (decimal).| +| Promise<number> | Promise used to return the result.| **Error codes** @@ -3327,9 +3351,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts try { this.context.resourceManager.getColor($r('app.color.test').id).then(value => { - let str = value; + let str = value; }).catch(error => { - console.log("getColor promise error is " + error); + console.log("getColor promise error is " + error); }); } catch (error) { console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`); @@ -3366,17 +3390,17 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.color.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id }; try { this.context.resourceManager.getColor(resource, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let str = value; - } + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } }); } catch (error) { console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`); @@ -3403,7 +3427,7 @@ Obtains the color value corresponding to the specified resource object. This API | Type | Description | | --------------------- | ---------------- | -| Promise<number> | Color value corresponding to the resource object (decimal).| +| Promise<number> | Promise used to return the result.| **Error codes** @@ -3418,9 +3442,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example** ```ts let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.color.test').id + bundleName: "com.example.myapplication", + moduleName: "entry", + id: $r('app.color.test').id }; try { this.context.resourceManager.getColor(resource).then(value => { @@ -3462,11 +3486,11 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts try { this.context.resourceManager.getColorByName("test", (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let string = value; - } + if (error != null) { + console.log("error is " + error); + } else { + let string = value; + } }); } catch (error) { console.error(`callback getColorByName failed, error code: ${error.code}, message: ${error.message}.`); @@ -3491,7 +3515,7 @@ Obtains the color value corresponding to the specified resource name. This API u | Type | Description | | --------------------- | ---------- | -| Promise<number> | Color value corresponding to the resource name (decimal).| +| Promise<number> | Promise used to return the result.| **Error codes** @@ -3507,34 +3531,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts try { this.context.resourceManager.getColorByName("test").then(value => { - let string = value; + let string = value; }).catch(error => { - console.log("getColorByName promise error is " + error); + console.log("getColorByName promise error is " + error); }); } catch (error) { console.error(`promise getColorByName failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getColorSync10+ +### getRawFileContentSync10+ -getColorSync(resId: number) : number; +getRawFileContentSync(path: string): Uint8Array -Obtains the color value corresponding to the specified resource ID. This API returns the result synchronously. +Obtains the content of the raw file in the **resources/rawfile** directory. This API returns the result synchronously. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----- | -| resId | number | Yes | Resource ID.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the raw file. | **Return value** -| Type | Description | -| ------ | ----------- | -| number | Color value corresponding to the resource ID (decimal).| +| Type | Description | +| --------------------- | ---------- | +| Uint8Array | Content of the raw file.| **Error codes** @@ -3542,40 +3566,74 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| 9001005 | If the resource not found by path. | **Example** ```ts try { - this.context.resourceManager.getColorSync($r('app.color.test').id); + this.context.resourceManager.getRawFileContentSync("test.txt"); } catch (error) { - console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getRawFileContentSync failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getColorSync10+ +### getRawFileContent9+ -getColorSync(resource: Resource): number +getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void -Obtains the color value corresponding to the specified resource object. This API returns the result synchronously. +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager -**Model restriction**: This API can be used only in the stage model. +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.getRawFileContent("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + } + }); + } catch (error) { + console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFileContent9+ + +getRawFileContent(path: string): Promise<Uint8Array> + +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---- | -| resource | [Resource](#resource9) | Yes | Resource object.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| **Return value** -| Type | Description | -| ------ | ---------------- | -| number | Color value corresponding to the resource object (decimal).| +| Type | Description | +| ------------------------- | ----------- | +| Promise<Uint8Array> | Promise used to return the result.| **Error codes** @@ -3583,43 +3641,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001001 | If the resId invalid. | -| 9001002 | If the resource not found by resId. | -| 9001006 | If the resource re-ref too much. | +| 9001005 | If the resource not found by path. | **Example** ```ts - let resource = { - bundleName: "com.example.myapplication", - moduleName: "entry", - id: $r('app.color.test').id - }; try { - this.context.resourceManager.getColorSync(resource); + this.context.resourceManager.getRawFileContent("test.xml").then(value => { + let rawFile = value; + }).catch(error => { + console.log("getRawFileContent promise error is " + error); + }); } catch (error) { - console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); } ``` -### getColorByNameSync10+ +### getRawFileListSync10+ -getColorByNameSync(resName: string) : number; +getRawFileListSync(path: string): Array\ -Obtains the color value corresponding to the specified resource name. This API returns the result synchronously. +Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---- | -| resName | string | Yes | Resource name.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the **rawfile** folder. | **Return value** -| Type | Description | -| ------ | ---------- | -| number | Color value corresponding to the resource name (decimal).| +| Type | Description | +| ------------------------- | ----------- | +| Array\ | List of files in the **resources/rawfile** directory.| **Error codes** @@ -3627,16 +3682,454 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco | ID| Error Message| | -------- | ---------------------------------------- | -| 9001003 | If the resName invalid. | -| 9001004 | If the resource not found by resName. | -| 9001006 | If the resource re-ref too much. | +| 9001005 | If the resource not found by path. | **Example** ```ts - try { - this.context.resourceManager.getColorByNameSync("test"); + try { // Passing "" means to obtain the list of files in the root directory of the raw file. + this.context.resourceManager.getRawFileListSync("") } catch (error) { - console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`getRawFileListSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFileList10+ + +getRawFileList(path: string, callback: AsyncCallback<Array\>): void; + +Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the **rawfile** folder. | +| callback | AsyncCallback<Array\> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { // Passing "" means to obtain the list of files in the root directory of the raw file. + this.context.resourceManager.getRawFileList("", (error, value) => { + if (error != null) { + console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + } else { + let rawFile = value; + } + }); + } catch (error) { + console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFileList10+ + +getRawFileList(path: string): Promise<Array\> + +Obtains the list of files in the **resources/rawfile** directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the **rawfile** folder.| + +**Return value** + +| Type | Description | +| ------------------------- | ----------- | +| Promise<Array\> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { // Passing "" means to obtain the list of files in the root directory of the raw file. + this.context.resourceManager.getRawFileList("").then(value => { + let rawFile = value; + }).catch(error => { + console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFdSync10+ + +getRawFdSync(path: string): RawFileDescriptor + +Obtains the descriptor of the raw file in the **resources/rawfile** directory. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| path | string | Yes | Path of the raw file. | + +**Return value** + +| Type | Description | +| ------------------------- | ----------- | +| [RawFileDescriptor](#rawfiledescriptor8) | Descriptor of the raw file.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.getRawFdSync("test.txt"); + } catch (error) { + console.error(`getRawFdSync failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFd9+ + +getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void + +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.getRawFd("test.xml", (error, value) => { + if (error != null) { + console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`); + } else { + let fd = value.fd; + let offset = value.offset; + let length = value.length; + } + }); + } catch (error) { + console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getRawFd9+ + +getRawFd(path: string): Promise<RawFileDescriptor> + +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------- | +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.getRawFd("test.xml").then(value => { + let fd = value.fd; + let offset = value.offset; + let length = value.length; + }).catch(error => { + console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`); + }); + } catch (error) { + console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### closeRawFdSync10+ + +closeRawFdSync(path: string): void + +Closes the descriptor of the raw file in the **resources/rawfile** directory. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------- | +| path | string | Yes | Path of the raw file.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.closeRawFdSync("test.txt"); + } catch (error) { + console.error(`closeRawFd failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### closeRawFd9+ + +closeRawFd(path: string, callback: AsyncCallback<void>): void + +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------- | +| path | string | Yes | Path of the raw file.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | The resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.closeRawFd("test.xml", (error, value) => { + if (error != null) { + console.log("error is " + error); + } + }); + } catch (error) { + console.error(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### closeRawFd9+ + +closeRawFd(path: string): Promise<void> + +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| + +**Return value** + +| Type | Description | +| ------------------- | ---- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 9001005 | If the resource not found by path. | + +**Example** + ```ts + try { + this.context.resourceManager.closeRawFd("test.xml").then(value => { + let result = value; + }).catch(error => { + console.log("closeRawFd promise error is " + error); + }); + } catch (error) { + console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`); + } + ``` + +### getConfiguration + +getConfiguration(callback: AsyncCallback<Configuration>): void + +Obtains the device configuration. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------- | +| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the result.| + +**Example** + ```ts + try { + this.context.resourceManager.getConfiguration((error, value) => { + if (error != null) { + console.error("getConfiguration callback error is " + error); + } else { + let direction = value.direction; + let locale = value.locale; + } + }); + } catch (error) { + console.error("getConfiguration callback error is " + error); + } + ``` + +### getConfiguration + +getConfiguration(): Promise<Configuration> + +Obtains the device configuration. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise<[Configuration](#configuration)> | Promise used to return the result.| + +**Example** + ```ts + try { + this.context.resourceManager.getConfiguration().then(value => { + let direction = value.direction; + let locale = value.locale; + }).catch(error => { + console.error("getConfiguration promise error is " + error); + }); + } catch (error) { + console.error("getConfiguration promise error is " + error); + } + ``` + +### getDeviceCapability + +getDeviceCapability(callback: AsyncCallback<DeviceCapability>): void + +Obtains the device capability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the result.| + +**Example** + ```ts + try { + this.context.resourceManager.getDeviceCapability((error, value) => { + if (error != null) { + console.error("getDeviceCapability callback error is " + error); + } else { + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; + } + }); + } catch (error) { + console.error("getDeviceCapability callback error is " + error); + } + ``` + +### getDeviceCapability + +getDeviceCapability(): Promise<DeviceCapability> + +Obtains the device capability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------- | +| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| + +**Example** + ```ts + try { + this.context.resourceManager.getDeviceCapability().then(value => { + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; + }).catch(error => { + console.error("getDeviceCapability promise error is " + error); + }); + } catch (error) { + console.error("getDeviceCapability promise error is " + error); + } + ``` + +### release7+ + +release() + +Releases a created **resourceManager** object. + +**System capability**: SystemCapability.Global.ResourceManager + +**Example** + ```ts + try { + this.context.resourceManager.release(); + } catch (error) { + console.error("release error is " + error); } ``` @@ -3666,9 +4159,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts let path = getContext().bundleCodeDir + "/library1-default-signed.hsp"; try { - this.context.resourceManager.addResource(path); + this.context.resourceManager.addResource(path); } catch (error) { - console.error(`addResource failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`addResource failed, error code: ${error.code}, message: ${error.message}.`); } ``` @@ -3698,9 +4191,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ```ts let path = getContext().bundleCodeDir + "/library1-default-signed.hsp"; try { - this.resmgr.removeResource(path); + this.resmgr.removeResource(path); } catch (error) { - console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index d61b8272edee9b2b522139a9976df17027be98a5..99eb42bd5720fa12a833abcc030b45d02c7aefaf 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -1,16 +1,9 @@ # @ohos.resourceschedule.backgroundTaskManager (Background Task Management) -The **BackgroundTaskManager** module provides APIs to manage background tasks. - -If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension. - -If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup. - -If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task. - -If a privileged system application needs to use certain system resources (for example, it wants to receive common events when suspended), it can request efficiency resources. +The **backgroundTaskManager** module provides APIs to request background tasks. You can use the APIs to request transient tasks, continuous tasks, or efficiency resources to prevent the application process from being terminated or suspended when your application is switched to the background. > **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -24,9 +17,11 @@ import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager' requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo -Requests delayed suspension after the application switches to the background. +Requests a transient task. -The default duration of delayed suspension is 3 minutes when the battery level is higher than or equal to the broadcast low battery level and 1 minute when the battery level is lower than the broadcast low battery level. +> **NOTE** +> +> The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](js-apis-battery-info.md), the maximum duration is decreased to 1 minute. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -34,14 +29,14 @@ The default duration of delayed suspension is 3 minutes when the battery level i | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------ | -| reason | string | Yes | Reason for delayed transition to the suspended state. | -| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.| +| reason | string | Yes | Reason for requesting the transient task. | +| callback | Callback<void> | Yes | Callback used to notify the application that the transient task is about to time out. Generally, the callback is invoked 6 seconds before the timeout.| **Return value** | Type | Description | | ------------------------------------- | --------- | -| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.| +| [DelaySuspendInfo](#delaysuspendinfo) | Information about the transient task.| **Error codes** @@ -80,7 +75,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void -Obtains the remaining duration before the application is suspended. This API uses an asynchronous callback to return the result. +Obtains the remaining time of a transient task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -88,8 +83,8 @@ Obtains the remaining duration before the application is suspended. This API use | Name | Type | Mandatory | Description | | --------- | --------------------------- | ---- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.| +| requestId | number | Yes | Request ID of the transient task. | +| callback | AsyncCallback<number> | Yes | Callback used to return the remaining time, in milliseconds.| **Error codes** @@ -129,9 +124,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er getRemainingDelayTime(requestId: number): Promise<number> -Obtains the remaining duration before the application is suspended. This API uses a promise to return the result. - - +Obtains the remaining time of a transient task. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -139,13 +132,13 @@ Obtains the remaining duration before the application is suspended. This API use | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------- | -| requestId | number | Yes | ID of the suspension delay request.| +| requestId | number | Yes | Request ID of the transient task.| **Return value** | Type | Description | | --------------------- | ---------------------------------------- | -| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.| +| Promise<number> | Promise used to return the remaining time, in milliseconds.| **Error codes** @@ -182,7 +175,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er cancelSuspendDelay(requestId: number): void -Cancels the suspension delay. +Cancels a transient task. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -190,7 +183,7 @@ Cancels the suspension delay. | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------- | -| requestId | number | Yes | ID of the suspension delay request.| +| requestId | number | Yes | Request ID of the transient task.| **Error codes** @@ -218,12 +211,11 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er } ``` - ## backgroundTaskManager.startBackgroundRunning startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void -Requests a continuous task from the system. This API uses an asynchronous callback to return the result. +Requests a continuous task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING @@ -234,9 +226,9 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| -| bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| bgMode | [BackgroundMode](#backgroundmode) | Yes | Continuous task mode. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is requested, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** @@ -301,7 +293,7 @@ export default class EntryAbility extends UIAbility { startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> -Requests a continuous task from the system. This API uses a promise to return the result. +Requests a continuous task. This API uses a promise to return the result. **Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING @@ -312,14 +304,14 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| -| bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| bgMode | [BackgroundMode](#backgroundmode) | Yes | Continuous task mode. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** | Type | Description | | -------------- | ---------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -380,7 +372,7 @@ export default class EntryAbility extends UIAbility { stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void -Requests to cancel a continuous task. This API uses an asynchronous callback to return the result. +Cancels a continuous task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -389,7 +381,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is canceled, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -434,9 +426,7 @@ export default class EntryAbility extends UIAbility { stopBackgroundRunning(context: Context): Promise<void> -Requests to cancel a continuous task. This API uses a promise to return the result. - - +Cancels a continuous task. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -450,7 +440,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Type | Description | | -------------- | ---------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Error codes** @@ -489,10 +479,9 @@ export default class EntryAbility extends UIAbility { ## backgroundTaskManager.applyEfficiencyResources -applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest)): void +applyEfficiencyResources(request: EfficiencyResourcesRequest): void -Requests efficiency resources from the system. -A process and its application can request the same type of resources at the same time, for example, CPU resources. When the application releases the resources, the same type of resources requested by the process are also released. +Requests efficiency resources. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply @@ -502,7 +491,7 @@ A process and its application can request the same type of resources at the same | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes | Necessary information carried in the request, including the resource type and timeout interval. For details, see [EfficiencyResourcesRequest](#efficiencyresourcesrequest).| +| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes | Necessary information carried in the request, including the resource type and timeout interval.| **Error codes** @@ -542,7 +531,7 @@ try { resetAllEfficiencyResources(): void -Releases all resources that have been requested. +Releases all efficiency resources. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply @@ -574,18 +563,19 @@ try { ## DelaySuspendInfo -Provides the information about the suspension delay. +Defines the information about the transient task. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask | Name | Type | Mandatory | Description | | --------------- | ------ | ---- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| - +| requestId | number | Yes | Request ID of the transient task. | +| actualDelayTime | number | Yes | Actual duration of the transient task that the application requests, in milliseconds.
The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](js-apis-battery-info.md), the maximum duration is decreased to 1 minute.| ## BackgroundMode +Enumerates the continuous task modes. + **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask | Name | Value | Description | @@ -596,9 +586,9 @@ Provides the information about the suspension delay. | LOCATION | 4 | Positioning and navigation. | | BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | | MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | -| WIFI_INTERACTION | 7 | WLAN-related (system API).| -| VOIP | 8 | Audio and video calls (system API). | -| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | +| WIFI_INTERACTION | 7 | WLAN-related.
**System API**: This is a system API.| +| VOIP | 8 |Audio and video calls.
**System API**: This is a system API.| +| TASK_KEEPING | 9 | Computing task (for specific devices only). | ## EfficiencyResourcesRequest @@ -611,10 +601,10 @@ Describes the parameters for requesting efficiency resources. | Name | Type | Mandatory | Description | | --------------- | ------ | ---- | ---------------------------------------- | | resourceTypes | number | Yes | Type of the resource to request. | -| isApply | boolean | Yes | Whether the request is used to apply for resources. The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources. | +| isApply | boolean | Yes | Whether the request is used to apply for resources.
The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources.| | timeOut | number | Yes | Duration for which the resource will be used, in milliseconds. | -| isPersist | boolean | No | Whether the resource is permanently held. If the value is **true**, **timeOut** is invalid. | -| isProcess | boolean | No | Whether the request is initiated by a process. The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. | +| isPersist | boolean | No | Whether the resource is permanently held. The default value is **false**.
The value **true** means that the resource is permanently held, and **false** means the resource is held within a given period of time.| +| isProcess | boolean | No | Whether the request is initiated by a process. The default value is **false**.
The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. | | reason | string | Yes | Reason for requesting the resource. | ## ResourceType @@ -627,12 +617,12 @@ Enumerates the efficiency resource types. | Name | Value | Description | | ----------------------- | ---- | --------------------- | -| CPU | 1 | CPU resources, which prevent the application from being suspended. | -| COMMON_EVENT | 2 | Common events are not proxied when the application is suspended.| -| TIMER | 4 | System timers are not proxied when the application is suspended.| -| WORK_SCHEDULER | 8 | Work Scheduler uses a loose control policy by default. For details about the constraints on the Work Scheduler usage, see [Constraints](../../task-management/work-scheduler.md#constraints).| -| BLUETOOTH | 16 | Bluetooth resources are not proxied when the application is suspended.| -| GPS | 32 | GPS resources are not proxied when the application is suspended.| -| AUDIO | 64 | Audio resources are not proxied when the application is suspended.| +| CPU | 1 | CPU resource. Such type of resource prevents an application from being suspended. | +| COMMON_EVENT | 2 | Common event resource. Such type of resource ensures that an application in the suspended state can receive common events.| +| TIMER | 4 | Timer resource. Such type of resource ensures that an application in the suspended state can be woken up by system timers.| +| WORK_SCHEDULER | 8 | Deferred task resource. Such type of resource provides a loose control policy for an application.| +| BLUETOOTH | 16 | Bluetooth resource. Such type of resource ensures that an application in the suspended state can be woken up by Bluetooth-related events.| +| GPS | 32 | GPS resource. Such type of resource ensures that an application in the suspended state can be woken up by GPS-related events.| +| AUDIO | 64 | Audio resource. Such type of resource prevents an application from being suspended when the application has an audio being played.| | RUNNING_LOCK10+ | 128 | RUNNING_LOCK resources are not proxied when the application is suspended.| | SENSOR10+ | 256 | Sensor callbacks are not intercepted.| diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index 85c085f6fb9ef65fb711aecbfe3610ab3d17f5d9..5fad64915cde48a0fe0150e83f1661bc0abb1aaa 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,15 +1,12 @@ # @ohos.resourceschedule.workScheduler (Deferred Task Scheduling) -The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. - -The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more. +The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. You can use the APIs to register tasks that do not have high requirements on real-time performance as deferred tasks. The system schedules and executes the deferred tasks at an appropriate time, subject to the storage space, power consumption, and more. > **NOTE** > > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > - The APIs of this module can be used only in the stage model. -> - For details about the constraints on deferred task scheduling, see [Constraints](../../task-management/work-scheduler.md#constraints). - ## Modules to Import @@ -18,9 +15,10 @@ import workScheduler from '@ohos.resourceschedule.workScheduler'; ``` ## workScheduler.startWork + startWork(work: WorkInfo): void -Instructs the WorkSchedulerService to add a task to the execution queue. +Starts a deferred task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -28,7 +26,7 @@ Instructs the WorkSchedulerService to add a task to the execution queue. | Name | Type | Mandatory | Description | | ---- | --------------------- | ---- | -------------- | -| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.| +| work | [WorkInfo](#workinfo) | Yes | Deferred task to start.| **Error codes** @@ -42,7 +40,6 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes | 9700004 | Check workInfo failed. | | 9700005 | StartWork failed. | - **Example** ```js @@ -69,9 +66,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.stopWork + stopWork(work: WorkInfo, needCancel?: boolean): void -Instructs the WorkSchedulerService to stop a task. +Stops a deferred task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -79,8 +77,8 @@ Instructs the WorkSchedulerService to stop a task. | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------- | -| work | [WorkInfo](#workinfo) | Yes | Task to stop. | -| needCancel | boolean | No | Whether to cancel the task. The default value is **false**.| +| work | [WorkInfo](#workinfo) | Yes | Deferred task to stop.| +| needCancel | boolean | No | Whether to clear the task while stopping it.
The value **true** means to clear the task while stopping it, and **false** means to stop the task only. The default value is **false**.| **Error codes** @@ -119,9 +117,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.getWorkStatus + getWorkStatus(workId: number, callback : AsyncCallback\): void -Obtains the latest task status. This API uses an asynchronous callback to return the result. +Obtains the information a deferred task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -129,8 +128,8 @@ Obtains the latest task status. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | -------- | ------------------------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.| +| workId | number | Yes | ID of the deferred task. | +| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.| **Error codes** @@ -162,9 +161,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.getWorkStatus + getWorkStatus(workId: number): Promise\ -Obtains the latest task status. This API uses a promise to return the result. +Obtains the information a deferred task. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -172,13 +172,13 @@ Obtains the latest task status. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| +| workId | number | Yes | ID of the deferred task.| **Return value** | Type | Description | | ------------------------------- | ---------------------------------------- | -| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.| +| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned.| **Error codes** @@ -208,9 +208,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.obtainAllWorks + obtainAllWorks(callback : AsyncCallback\): Array\ -Obtains all tasks associated with the application. This API uses an asynchronous callback to return the result. +Obtains all the deferred tasks. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -218,13 +219,13 @@ Obtains all tasks associated with the application. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If all the deferred tasks are obtained, **err** is **undefined**. Otherwise, **err** is an error object.| **Return value** | Type | Description | | ----------------------------- | --------------- | -| Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.| +| Array\<[WorkInfo](#workinfo)> | All the deferred tasks.| **Error codes** @@ -253,9 +254,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.obtainAllWorks + obtainAllWorks(): Promise\> -Obtains all tasks associated with the application. This API uses a promise to return the result. +Obtains all the deferred tasks. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -263,7 +265,7 @@ Obtains all tasks associated with the application. This API uses a promise to re | Type | Description | | -------------------------------------- | ------------------------------ | -| Promise> | Promise used to return all tasks associated with the application.| +| Promise> | Promise used to return all the deferred tasks.| **Error codes** @@ -290,9 +292,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.stopAndClearWorks + stopAndClearWorks(): void -Stops and cancels all tasks associated with the application. +Stops and clears all the deferred tasks. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -318,6 +321,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.isLastWorkTimeOut + isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result. @@ -328,14 +332,14 @@ Checks whether the last execution of a task timed out. This API uses an asynchro | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| workId | number | Yes | Task ID. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| workId | number | Yes | ID of the deferred task. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Return value** | Type | Description | | ------- | ---------------------------------------- | -| boolean | Returns **true** if the last execution of the task timed out; returns **false** otherwise.| +| boolean | The value **true** means that the last execution of the specified task times out, and **false** means the opposite.| **Error codes** @@ -365,6 +369,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## workScheduler.isLastWorkTimeOut + isLastWorkTimeOut(workId: number): Promise\ Checks whether the last execution of a task timed out. This API uses a promise to return the result. @@ -375,13 +380,13 @@ Checks whether the last execution of a task timed out. This API uses a promise t | Name | Type | Mandatory | Description | | ------ | ------ | ---- | -------- | -| workId | number | Yes | Task ID.| +| workId | number | Yes | ID of the deferred task.| **Return value** | Type | Description | | ----------------- | ---------------------------------------- | -| Promise\ | Promise used to return the result. If the last execution of the task timed out, **true** is returned. Otherwise, **false** is returned.| +| Promise\ | Promise used to return the result. The value **true** means that the last execution of the specified task times out, and **false** means the opposite.| **Error codes** @@ -411,31 +416,33 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ``` ## WorkInfo -Provides detailed information about the task. For details about the constraints on setting the **WorkInfo** parameter, see [Constraints](../../task-management/work-scheduler.md#constraints). + +Defines the information about the deferred task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler | Name | Type | Mandatory | Description | | --------------- | --------------------------------- | ---- | ---------------- | -| workId | number | Yes | Task ID. | +| workId | number | Yes | ID of the deferred task. | | bundleName | string | Yes | Bundle name of the application that requests the task. | | abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback.| | networkType | [NetworkType](#networktype) | No | Network type. | -| isCharging | boolean | No | Whether the device is charging. | +| isCharging | boolean | No | Whether the device needs to enter the charging state to trigger deferred task scheduling.
The value **true** means that the device needs to enter the charging state to trigger deferred task scheduling, and **false** means the opposite.| | chargerType | [ChargingType](#chargingtype) | No | Charging type. | -| batteryLevel | number | No | Battery level. | +| batteryLevel | number | No | Battery level. | | batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. | | storageRequest | [StorageRequest](#storagerequest) | No | Storage status. | -| isRepeat | boolean | No | Whether the task is repeated. | +| isRepeat | boolean | No | Whether the task is repeated.
The value** true** means that the task is repeated, and **false** means the opposite.| | repeatCycleTime | number | No | Repeat interval. | | repeatCount | number | No | Number of repeat times. | -| isPersisted | boolean | No | Whether to enable persistent storage for the task. | -| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | -| idleWaitTime | number | No | Time to wait in the idle state. | -| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. | +| isPersisted | boolean | No | Whether to enable persistent storage for the task.
The value **true** means to enable persistent storage for the task, and **false** means the opposite.| +| isDeepIdle | boolean | No | Whether the device needs to enter the idle state to trigger deferred task scheduling.
The value **true** means that the device needs to enter the idle state to trigger deferred task scheduling, and **false** means the opposite. | +| idleWaitTime | number | No | Time to wait in the idle state before triggering deferred task scheduling. | +| parameters | [key: string]: number \| string \| boolean | No | Carried parameters.| ## NetworkType -Enumerates the network types that can trigger task scheduling. + +Enumerates the network types that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -449,7 +456,8 @@ Enumerates the network types that can trigger task scheduling. | NETWORK_TYPE_ETHERNET | 5 | Ethernet. | ## ChargingType -Enumerates the charging types that can trigger task scheduling. + +Enumerates the charging types that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -461,7 +469,8 @@ Enumerates the charging types that can trigger task scheduling. | CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | ## BatteryStatus -Enumerates the battery states that can trigger task scheduling. + +Enumerates the battery statuses that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -472,7 +481,8 @@ Enumerates the battery states that can trigger task scheduling. | BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| ## StorageRequest -Enumerates the storage states that can trigger task scheduling. + +Enumerates the storage statuses that can trigger deferred task scheduling. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler @@ -480,4 +490,4 @@ Enumerates the storage states that can trigger task scheduling. | ------------------------- | ---- | ------------------------------ | | STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | | STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | -| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| +| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is insufficient, or the storage space is restored from insufficient to normal.| diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 2d97910441aa8dc3d5fe958c5424a0b449ce0620..0643de31173d0737a10431bc0bb8eb7d06428f01 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -51,21 +51,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); }) +} catch (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.pushUrl9+ @@ -146,21 +144,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushUrl({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - }) + }, router.RouterMode.Standard) +} catch (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.pushUrl9+ @@ -241,18 +237,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } }) +} catch (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceUrl9+ @@ -330,18 +324,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.replaceUrl({ - url: 'pages/detail', - params: { - data1: 'message' - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); - }) +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message' + } + }, router.RouterMode.Standard) +} catch (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceUrl9+ @@ -420,23 +412,23 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); }) +} catch (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` +For details, see [UI Development-Named Route](../../ui/arkts-routing.md#named-route). + ## router.pushNamedRoute10+ pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void @@ -515,21 +507,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.pushNamedRoute({ - name: 'myPage', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushNamedRoute({ + name: 'myPage', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + } } - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); - }) + }, router.RouterMode.Standard) +} catch (err) { + console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.pushNamedRoute10+ @@ -610,18 +600,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc **Example** ```ts -router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } -}) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); +try { + router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } }) +} catch (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceNamedRoute10+ @@ -693,24 +681,22 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | if UI execution context not found, only throw in standard system. | +| 100001 | if can not get the delegate, only throw in standard system. | | 100004 | if the named route is not exist. | **Example** ```ts -router.replaceNamedRoute({ - name: 'myPage', - params: { - data1: 'message' - } -}, router.RouterMode.Standard) - .then(() => { - // success - }) - .catch(err => { - console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); - }) +try { + router.replaceNamedRoute({ + name: 'myPage', + params: { + data1: 'message' + } + }, router.RouterMode.Standard) +} catch (err) { + console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`); +} ``` ## router.replaceNamedRoute10+ @@ -932,7 +918,7 @@ Describes the page routing options. | Name | Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | url | string | Yes | URL of the target page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URL is a slash (/), the home page is displayed.| -| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| +| params | object | No | Data that needs to be passed to the target page during redirection. The received data becomes invalid when the page is switched to another page. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.
**NOTE**
The **params** parameter cannot pass objects returned by methods and system APIs, for example, **PixelMap** objects defined and returned by media APIs. To pass such objects, extract from them the basic type attributes to be passed, and then construct objects of the object type.| > **NOTE** 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-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index fb3aa7540b8383f983436c0d713e09346ad6aa3e..cbc5ed086fff519da5b5c959304afeeac6f442d5 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -2732,7 +2732,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses an async **System API**: This is a system API. -**Required permission**: ohos.permission.GET_TELEPHONY_STATE +**Required permission**: ohos.permission.GET_PHONE_NUMBERS **System capability**: SystemCapability.Telephony.CoreService @@ -2775,7 +2775,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses a promis **System API**: This is a system API. -**Required permission**: ohos.permission.GET_TELEPHONY_STATE +**Required permission**: ohos.permission.GET_PHONE_NUMBERS **System capability**: SystemCapability.Telephony.CoreService diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 76c7829cf8fdadad378305ba795212ac10f621ea..f193ed010e3b0eb1ba6a87fad70f81b19bf9b732 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1691,7 +1691,7 @@ listen(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number. **Required permissions**: ohos.permission.INTERNET @@ -1736,7 +1736,7 @@ listen(address: NetAddress): Promise\ Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number. **Required permissions**: ohos.permission.INTERNET diff --git a/en/application-dev/reference/apis/js-apis-syscap.md b/en/application-dev/reference/apis/js-apis-syscap.md index 05439e8cd6949a8f50caec8481fae3eb908cac3c..d9e5601d2e1096f363edf984857e06ef9999ab89 100644 --- a/en/application-dev/reference/apis/js-apis-syscap.md +++ b/en/application-dev/reference/apis/js-apis-syscap.md @@ -29,12 +29,17 @@ Checks whether a SysCap is supported. **Example** ```js -import geolocation from '@ohos.geolocation' +import geoLocationManager from '@ohos.geoLocationManager' -const isLocationAvailable = canIUse('SystemCapability.Location.Location'); +const isLocationAvailable = canIUse('SystemCapability.Location.Location.Core'); if (isLocationAvailable) { - geolocation.getCurrentLocation((location) => { - console.log(location.latitude, location.longitue); + geoLocationManager.getCurrentLocation((err, location) => { + if (err) { + console.log('err=' + JSON.stringify(err)); + } + if (location) { + console.log('location=' + JSON.stringify(location)); + } }); } else { console.log('Location not by this device.'); diff --git a/en/application-dev/reference/apis/js-apis-system-date-time.md b/en/application-dev/reference/apis/js-apis-system-date-time.md index c457247270be59898c2328e95b015d442cf41382..d78f005217ddae233bedcb3c37a3284655cec0e5 100644 --- a/en/application-dev/reference/apis/js-apis-system-date-time.md +++ b/en/application-dev/reference/apis/js-apis-system-date-time.md @@ -22,6 +22,8 @@ Sets the system time. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name | Type | Mandatory| Description | @@ -57,6 +59,8 @@ Sets the system time. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name| Type | Mandatory| Description | @@ -158,7 +162,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| **Return value** @@ -253,7 +257,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| **Return value** @@ -348,7 +352,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| isNano | boolean | No | Whether the time to return is in nanoseconds. The default value is **false**.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| **Return value** @@ -380,6 +384,8 @@ Sets the system date. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name | Type | Mandatory| Description | @@ -414,6 +420,8 @@ Sets the system date. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME + **Parameters** | Name| Type| Mandatory| Description | @@ -509,6 +517,8 @@ Sets the system time zone. This API uses an asynchronous callback to return the **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME_ZONE + **Parameters** | Name | Type | Mandatory| Description | @@ -542,6 +552,8 @@ Sets the system time zone. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Time +**Required permissions**: ohos.permission.SET_TIME_ZONE + **Parameters** | Name | Type | Mandatory| Description | diff --git a/en/application-dev/reference/apis/js-apis-system-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index 0f014e6822dc9b257a7b0eaa6e802b6f7f758110..1f9f095b0516d0c2460e25c09b6000878af24434 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -50,18 +50,24 @@ Displays a notification. | options | ShowNotificationOptions | No| Notification title.| **Example** -```javascript -export default { - show() { - notification.show({ - contentTitle: 'title info', - contentText: 'text', - clickAction: { - bundleName: 'com.example.testapp', - abilityName: 'notificationDemo', - uri: '/path/to/notification' - } - }); - } +```ts +class NotificationClass { + show: Function +} + +let notificationObj: NotificationClass = { + show() { + notification.show({ + contentTitle: 'title info', + contentText: 'text', + clickAction: { + bundleName: 'com.example.testapp', + abilityName: 'notificationDemo', + uri: '/path/to/notification' + } + }); + } } + +export default notificationObj ``` diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md index cc15e7f85a4dec87d1d23f0bc10fab0514d7df5d..e0c0e3cb5768eecc8a2ece9df1d5400ac835751d 100644 --- a/en/application-dev/reference/apis/js-apis-system-timer.md +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -36,8 +36,8 @@ Defines the initialization options for **createTimer**. | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | type | number | Yes | Timer type.
**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)
**2**: wakeup type.
**4**: exact type.
**8**: idle type (not supported currently).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| +| repeat | boolean | Yes | Whether the timer is a repeating timer.
The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval.
For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| | wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)| | callback | number | Yes | Callback used to return the timer ID. | @@ -48,8 +48,6 @@ createTimer(options: TimerOptions, callback: AsyncCallback<number>): void Creates a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -89,7 +87,6 @@ createTimer(options: TimerOptions): Promise<number> Creates a timer. This API uses a promise to return the result. -**System API**: This is a system API. **System capability**: SystemCapability.MiscServices.Time @@ -133,8 +130,6 @@ startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void&g Starts a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -178,8 +173,6 @@ startTimer(timer: number, triggerTime: number): Promise<void> Starts a timer. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -226,8 +219,6 @@ stopTimer(timer: number, callback: AsyncCallback<void>): void Stops a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -271,8 +262,6 @@ stopTimer(timer: number): Promise<void> Stops a timer. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -319,8 +308,6 @@ destroyTimer(timer: number, callback: AsyncCallback<void>): void Destroys a timer. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -365,8 +352,6 @@ destroyTimer(timer: number): Promise<void> Destroys a timer. This API uses a promise to return the result. -**System API**: This is a system API. - **System capability**: SystemCapability.MiscServices.Time **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index adea4c22a9473f43b8092d0314918537ecaa98b6..d0b51d00e6ddb980ac95cdeeb8a20de3db84c1a7 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -254,20 +254,20 @@ struct WebComponent { .onClick(() => { // Use the local port to send messages to HTML5. try { - console.log("In eTS side send true start"); + console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setString("helloFromEts"); this.nativePort.postMessageEventExt(this.message); } } catch (error) { - console.log("In eTS side send message catch error:" + error.code + ", msg:" + error.message); + console.log("In ArkTS side send message catch error:" + error.code + ", msg:" + error.message); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .onPageEnd((e)=>{ - console.log("In eTS side message onPageEnd init mesaage channel"); + console.log("In ArkTS side message onPageEnd init mesaage channel"); // 1. Create a message port. this.ports = this.controller.createWebMessagePorts(true); // 2. Send port 1 to HTML5. @@ -276,10 +276,10 @@ struct WebComponent { this.nativePort = this.ports[0]; // 4. Set the callback. this.nativePort.onMessageEventExt((result) => { - console.log("In eTS side got message"); + console.log("In ArkTS side got message"); try { var type = result.getType(); - console.log("In eTS side getType:" + type); + console.log("In ArkTS side getType:" + type); switch (type) { case web_webview.WebMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); @@ -652,71 +652,71 @@ struct WebComponent { There are three methods for loading local resource files: 1. Using $rawfile - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through $rawfile. - this.controller.loadUrl($rawfile('index.html')); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through $rawfile. + this.controller.loadUrl($rawfile('index.html')); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` 2. Using the resources protocol - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through the resource protocol. - this.controller.loadUrl("resource://rawfile/index.html"); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load local resource files through the resource protocol. + this.controller.loadUrl("resource://rawfile/index.html"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` 3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web). - HTML file to be loaded: - ```html - - - - -

Hello World

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

Hello World

+ + +``` ### loadData @@ -4320,6 +4320,107 @@ export default class EntryAbility extends UIAbility { } ``` +### setCustomUserAgent10+ + +setCustomUserAgent(userAgent: string): void + +Set a custom user agent. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------| ------- | ---- | ------------- | +| userAgent | string | Yes | Information about the custom user agent.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State userAgent: string = 'test' + + build() { + Column() { + Button('setCustomUserAgent') + .onClick(() => { + try { + this.controller.setCustomUserAgent(this.userAgent); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getCustomUserAgent10+ + +getCustomUserAgent(): string + +Obtains a custom user agent. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | ------------------------- | +| string | Information about the custom user agent.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID | Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State userAgent: string = '' + + build() { + Column() { + Button('getCustomUserAgent') + .onClick(() => { + try { + this.userAgent = this.controller.getCustomUserAgent(); + console.log("userAgent: " + this.userAgent); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebCookieManager Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. diff --git a/en/application-dev/reference/arkui-ts/figures/TextInputError.png b/en/application-dev/reference/arkui-ts/figures/TextInputError.png new file mode 100644 index 0000000000000000000000000000000000000000..2738da34ffdf692cbe23ca3ce2033e4e2a640e79 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/TextInputError.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif b/en/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif new file mode 100644 index 0000000000000000000000000000000000000000..65daefb814d4f64f4e85f0d3ef8be14fa04998dc Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/arkts-progressSmoothEffect.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/borderImage.gif b/en/application-dev/reference/arkui-ts/figures/borderImage.gif index dd8d0f1a9f9a786de94abf348130c526ecb09641..b3a316a22239c267af5503df959116dae4614338 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/borderImage.gif and b/en/application-dev/reference/arkui-ts/figures/borderImage.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582844.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582844.gif deleted file mode 100644 index 639261bd9e9997074cd45491807a58bb79a5def2..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582844.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058470.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058470.gif deleted file mode 100644 index 17ae76b8141d65147f9774d130711f46bf332d02..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212058470.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001241668363.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001241668363.gif deleted file mode 100644 index fba237dad5fc43609bb5ebcf6b0310328800d9f6..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001241668363.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_action.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_action.gif new file mode 100644 index 0000000000000000000000000000000000000000..f50362a49d7e5ef58a77a6a1a0521277fa561721 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_action.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_alert.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_alert.gif new file mode 100644 index 0000000000000000000000000000000000000000..a33bc5d56a5731133fb506d4be499b9aaf0b9d00 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_alert.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_custom.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_custom.gif new file mode 100644 index 0000000000000000000000000000000000000000..7ce7ddd59482b67c26553ad04fd8df26a0af5ddb Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_custom.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/showUnit.png b/en/application-dev/reference/arkui-ts/figures/showUnit.png deleted file mode 100644 index 4b60beda19ba2c6e314dcb0632d5d5953f79a952..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/showUnit.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/span.png b/en/application-dev/reference/arkui-ts/figures/span.png index 881f4945dac79e31cb9f11216a682110de4efec7..84f2d46cba0a6abd0cf83627c984d843ffb40719 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/span.png and b/en/application-dev/reference/arkui-ts/figures/span.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index aad87a6dee2faaacf65c89482b14f35c27e887bd..1c89649f090e82b0d430c8ce15ea52ac14699f4c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -31,7 +31,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr) \| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where **[base64 data]** is a Base64 string.
- Strings with the **file://** prefix, which are used to access the images in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://** or **file://** prefix, and they do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type. | +| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr) \| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where **[base64 data]** is a Base64 string.
- Strings with the **file://** prefix, which are used to access the images in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://** or **file://** prefix, or the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| ## Attributes @@ -42,17 +42,17 @@ For details about how to use attributes, see [Setting Attributes](../../ui/arkts | alt | string \| [Resource](ts-types.md#resource) | Placeholder image displayed during loading. Local images (in PNG, JPG, BMP, SVG, or GIF format) are supported. Online images are not supported.
Default value: **null**
Since API version 9, this API is supported in ArkTS widgets.| | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.
Default value: **ImageFit.Cover**
Since API version 9, this API is supported in ArkTS widgets.| | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | How the image is repeated. When set to repeat, the image is repeated from the center to edges. The last image will be clipped if it does not fit in the component.
Default value: **ImageRepeat.NoRepeat**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| -| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images or **PixelMap** objects. | +| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image, which can alleviate aliasing that occurs when the image is zoomed.
Default value: **ImageInterpolation.None**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the image is zoomed out, high quality interpolation is not applicable. You are advised to use medium or low quality interpolation instead.
This attribute is not applicable to SVG images.| | renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image, which can be **Original** or **Template** (monochrome).
Default value: **ImageRenderMode.Original**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute is not applicable to SVG images.| | sourceSize | {
width: number,
height: number
} | Decoding size of the image. This attribute can be used to reduce the image resolution when the image display size needs to be smaller than the component size. When used together with **ImageFit.None**, it can display a small image in the component.
Unit: px
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute works only when the target size is smaller than the source size.
This attribute is not applicable to SVG images.
This attribute is not applicable to **PixelMap** objects.| | matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| -| fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color to be superimposed on the image.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.| -| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage. For example, if the size of the original image is 1920 x 1080 and the size of the display area is 200 x 200, you can set this attribute to **true** so that the image is automatically decoded to 200 x 200.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| +| fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color to be superimposed on the image.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This attribute applies only to an SVG image. Once set, the fill color will replace that of the SVG image.| +| autoResize | boolean | Whether to resize the image source based on the size of the display area during image decoding. This resizing can help reduce the memory usage. For example, if the size of the original image is 1920 x 1080 and the size of the display area is 200 x 200, you can set this attribute to **true** so that the image is downsampled to 200 x 200.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
As downsampling images results in some loss of information, it may reduce the image quality, causing issues such as aliasing. To retain the original image quality, set **autoResize** to **false**.| | syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder image is not displayed.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When loading a small image, you are advised to set **syncLoad** to **true** so that the image loading can be quickly completed on the main thread.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied.
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
SVG images cannot be copied.| -| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.
The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.
The RGBA values are floating-point numbers between 0 and 1. When the diagonal value of the matrix is 1, the original color of the image is retained.
**Calculation rule:**
If the input filter matrix is as follows:
![image-matrix-1](figures/image-matrix-1.jpg)
Wherein the color is [R, G, B, A].
Then the color after filtering is [R', G', B', A'].
![image-matrix-2](figures/image-matrix-2.jpg)
Since API version 9, this API is supported in ArkTS widgets. | -| draggable(deprecated) | boolean | Whether the image is draggable.
This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
**NOTE**
This API is supported since API version 9 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead.| +| colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.
The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.
The RGBA values are floating-point numbers between 0 and 1. When the diagonal value of the matrix is 1, the original color of the image is retained.
**Calculation rule:**
If the input filter matrix is as follows:
![image-matrix-1](figures/image-matrix-1.jpg)
Wherein the color is [R, G, B, A].
Then the color after filtering is [R', G', B', A'].
![image-matrix-2](figures/image-matrix-2.jpg)
Since API version 9, this API is supported in ArkTS widgets.| +| draggable| boolean | Whether the image is draggable. The value **true** means that the image is draggable, and **false** means the opposite.
This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
**NOTE**
This API is supported since API version 9.| > **NOTE** > @@ -66,7 +66,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Description | | ------ | ---------------------------------------------------- | | None | No image interpolation. | -| High | High quality interpolation. This mode produces the highest possible quality scaled images, but may require more image rendering time.| +| High | High quality interpolation. This mode produces scaled images of the highest possible quality, but may require more image rendering time.| | Medium | Medium quality interpolation. | | Low | Low quality interpolation. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md index d3c71096b7b39b2418be797a5d062d4b48488416..5c6288b5e19deb95ca6f5504d8c3c48248c48f9a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md @@ -28,10 +28,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | images | Array<[ImageFrameInfo](#imageframeinfo)> | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. For details, see **ImageFrameInfo**.
Default value: **[]**
**NOTE**
Dynamic update is not supported.
Since API version 10, this API is supported in ArkTS widgets.| | state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | Playback status of the animation. The default status is **Initial**.
Default value: **AnimationStatus.Initial**
Since API version 10, this API is supported in ArkTS widgets.| | duration | number | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.
Default value: **1000**
Since API version 10, this API is supported in ArkTS widgets.| -| reverse | boolean | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.
Default value: **false**
Since API version 10, this API is supported in ArkTS widgets.| +| reverse | boolean | Playback direction. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.
Default value: **false**
Since API version 10, this API is supported in ArkTS widgets.| | fixedSize | boolean | Whether the image size is the same as the component size.
**true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.
**false**: The width, height, top, and left attributes of each image must be set separately.
Default value: **true**
Since API version 10, this API is supported in ArkTS widgets.| | preDecode(deprecated) | number | Number of pre-decoded images. The value **2** indicates that two images following the currently playing page will be pre-decoded to improve performance.
This API is deprecated since API version 9.
Default value: **0** | -| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Status before and after the animation starts. For details about the options, see **FillMode**.
Default value: **FillMode.Forwards**
Since API version 10, this API is supported in ArkTS widgets.| +| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Status before and after execution of the animation in the current playback direction. For details about the options, see **FillMode**. The status after execution of the animation is jointly determined by the **fillMode** and **reverse** attributes. For example, if **fillMode** is set to **Forwards**, the target will retain the state defined by the last keyframe encountered during execution. In this case, if **reverse** is set to **false**, the target will retain the state defined by the last keyframe encountered in the forward direction, that is, the last image; if **reverse** is set to **true**, the target will retain the state defined by the last keyframe encountered in the backward direction, that is, the first image.
Default value: **FillMode.Forwards**
Since API version 10, this API is supported in ArkTS widgets.| | iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1** | ## ImageFrameInfo diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index cad8cd31309b0e6098e0ab5b521d5c6f10ce0843..110905369abcd03d58cccdab4380d31aadf03f33 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -13,44 +13,54 @@ Supported Since API version 9, it is recommended that this component be used together with the **[\](ts-basic-components-navrouter.md)** component. - ## APIs -**API 1**: Navigation() +### Navigation + +Navigation() + +### Navigation10+ -**API 2**: Navigation(pathInfos: NavPathStack)10+ +Navigation(pathInfos: NavPathStack)10+ Binds a navigation stack to the **\** component. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ------------- | -| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | ------ | +| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name | Type | Description | -| ----------------------------- | ---------------------------------------- | ---------------------------------------- | -| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| -| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| -| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| -| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| -| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| +| Name | Type | Description | +| ---------------------------------- | ---------------------------------------- | ---------------------------------------- | +| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| +| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.| +| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.| +| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**| +| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: all items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.| | toolbarConfiguration10+ | Array<[ToolbarItem](#toolbaritem10)10+> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**NOTE**
When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.
If any item contains overlong text and there are fewer than five items, the following measures are taken: 1. Increase the item's width to accommodate the text until it is as large as the screen width; 2. Scale down the text level by level; 3. Wrap the text in two lines; 4. Clip the text with an ellipsis (...).
The toolbar shows a maximum of five icons in portrait mode, with excess icons (if any) placed under the automatically generated **More** icon. In landscape mode, this attribute must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; the toolbar at the bottom is automatically hidden, and all items on the toolbar are moved to the menu in the upper right corner of the screen.
When the value type is [CustomBuilder](ts-types.md#custombuilder8), and the toolbar does not exhibit the preceding features except that items are evenly distributed on the toolbar at the bottom.| -| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| -| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| -| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| -| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| -| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| -| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| -| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| -| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| -| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| -| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| -| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| +| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.| +| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.| +| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.| +| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.| +| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.| +| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.| +| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.| +| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.| +| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.| +| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.| +| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)| + +## Events + +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| +| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| ## NavPathStack10+ @@ -64,9 +74,9 @@ Pushes the NavDestination page information specified by **info** to the stack. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ----------------------------- | ---- | -------------------- | +| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.| ### pushPathByName10+ @@ -76,10 +86,10 @@ Pushes the navigation destination page specified by **name** to the navigation s **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | Yes | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | Yes | Parameter information of the navigation destination page.| ### pop10+ @@ -89,10 +99,10 @@ Pops the top element out of the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ----------- | ------------------------ | | NavPathInfo | Returns the information about the navigation destination page at the top of the stack.| -| undefined | Returns **undefined** if the navigation stack is empty.| +| undefined | Returns **undefined** if the navigation stack is empty. | ### popToName10+ @@ -102,14 +112,14 @@ Returns the navigation stack to the first navigation destination page that match **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### popToIndex10+ @@ -120,9 +130,9 @@ Returns the navigation stack to the navigation destination page that matches the **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### moveToTop10+ @@ -132,14 +142,14 @@ Moves to the top of the navigation stack the first navigation destination page t **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| ------ | ---------------------------------------- | | number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.| ### moveIndexToTop10+ @@ -150,9 +160,9 @@ Moves to the top of the navigation stack the navigation destination page that ma **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| ### clear10+ @@ -168,8 +178,8 @@ Obtains the names of all navigation destination pages in the navigation stack. **Return value** -| Type | Description | -| ------ | -------- | +| Type | Description | +| -------------- | -------------------------- | | Array | Names of all navigation destination pages in the navigation stack.| ### getParamByIndex10+ @@ -180,16 +190,16 @@ Obtains the parameter information of the navigation destination page that matche **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| index | number | Yes | Index of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| unknown | Returns the parameter information of the matching navigation destination page.| -| undefined | Returns **undefined** if the passed index is invalid.| +| Type | Description | +| --------- | -------------------------- | +| unknown | Returns the parameter information of the matching navigation destination page.| +| undefined | Returns **undefined** if the passed index is invalid. | ### getParamByName10+ @@ -199,15 +209,15 @@ Obtains the parameter information of all the navigation destination pages that m **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Parameter information of all the matching navigation destination pages.| +| Type | Description | +| --------------- | --------------------------------- | +| Array | Parameter information of all the matching navigation destination pages.| ### getIndexByName10+ @@ -217,15 +227,15 @@ Obtains the indexes information of all the navigation destination pages that mat **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------------- | +| name | string | Yes | Name of the navigation destination page.| **Return value** -| Type | Description | -| ------ | -------- | -| Array | Indexes of all the matching navigation destination pages.| +| Type | Description | +| -------------- | --------------------------------- | +| Array | Indexes of all the matching navigation destination pages.| ### size10+ @@ -235,9 +245,9 @@ Obtains the stack size. **Return value** -| Type | Description | -| ------ | -------- | -| number | Stack size.| +| Type | Description | +| ------ | ------ | +| number | Stack size.| ## NavPathInfo10+ @@ -249,52 +259,52 @@ constructor(name: string, param: unknown) **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| name | string | Yes | Name of the navigation destination page. | -| param | unknown | No | Parameter information of the navigation destination page. | +| Name | Type | Mandatory | Description | +| ----- | ------- | ---- | --------------------- | +| name | string | Yes | Name of the navigation destination page. | +| param | unknown | No | Parameter information of the navigation destination page.| ## NavigationMenuItem -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a menu item. | -| icon | string | No | Icon path of a menu item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a menu item. | +| icon | string | No | Icon path of a menu item.| | action | () => void | No | Callback invoked when a menu item is selected. | ## object -| Name | Type | Mandatory | Description | -| ------ | ----------------------- | ---- | --------------- | -| value | string | Yes | Text of a toolbar item. | -| icon | string | No | Icon path of a toolbar item.| +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| value | string | Yes | Text of a toolbar item. | +| icon | string | No | Icon path of a toolbar item.| | action | () => void | No | Callback invoked when a toolbar item is selected. | ## ToolbarItem10+ -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- | -| value | ResourceStr | Yes | Text of a toolbar item. | -| icon | ResourceStr | No | Icon path of a toolbar item. | -| action | () => void | No | Callback invoked when a toolbar item is selected. | -| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| -| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| value | ResourceStr | Yes | Text of a toolbar item. | +| icon | ResourceStr | No | Icon path of a toolbar item. | +| action | () => void | No | Callback invoked when a toolbar item is selected. | +| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**| +| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. | ## ToolbarItemStatus10+ -| Name | Description | -| -------- | ------------------------------------------------------------ | +| Name | Description | +| -------- | ---------------------------------------- | | NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.| | DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.| | ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.| ## NavigationTitleMode -| Name| Description | -| ---- | ------------------------------------------------------------ | -| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| -| Mini | The title is fixed at mini mode. | -| Full | The title is fixed at full mode. | +| Name | Description | +| ---- | ---------------------------------------- | +| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.| +| Mini | The title is fixed at mini mode. | +| Full | The title is fixed at full mode. | ## NavigationCommonTitle @@ -322,7 +332,7 @@ constructor(name: string, param: unknown) | Name | Description | | ----- | ------------------------------------------------------------ | | Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages. | -| Split | The navigation bar and content area are displayed in different columns. | +| Split | The navigation bar and content area are displayed in different columns.
The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].
1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) > Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **maxNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) is within the value range specified by **navBarWidthRange**: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width: The value of **navBarWidth** is the set value.
3. When the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the navigation bar is shrunk until its width reaches the value defined by **minNavBarWidth**; if the component size is further decreased, the content area is further shrunk until it disappears, and then navigation bar is shrunk.
4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.
5. If only **navBarWidth** is set, the width of the navigation bar is fixed at the value of **navBarWidth**, and the divider cannot be dragged.| | Auto | In API version 9 and earlier versions: When the window width is greater than or equal to 520 vp, the Split mode is used. In other cases, the Stack mode is used.
In API version 10 and later versions: When the window width is greater than or equal to 600 vp, the Split mode is used. In other cases, the Stack mode is used. 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp).| ## TitleHeight @@ -334,17 +344,10 @@ constructor(name: string, param: unknown) > **NOTE** +> > Among the scrollable components, only **\** is supported. -## Events - -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.| -| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.| - - ## Example ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md index 060e00b1e3eca27a007342fe68ae309fe6e3d0b6..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/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md index b492893437d12229d84e45fe345b23bb5a506839..586fb45899c8baf56b77aa1f2483e7690e88744d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richeditor.md @@ -309,7 +309,7 @@ Provides the text style information. | fontSize | [Length](ts-types.md#length) \| number | No| Font size.
Default value: **16fp**| | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No| Font style.
Default value: **FontStyle.Normal**| | fontWeight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No| Font weight.
For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**.
For the string type, only strings of the number type are supported, for example, **"400"**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal**| -| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. Default value: **'HarmonyOS Sans'**.
Currently, only the default font is supported.
Default font: **'HarmonyOS Sans'**| +| fontFamily | [ResourceStr](ts-types.md#resourcestr) \| number \| string | No| Font family. The HarmonyOS Sans font and [register custom fonts](../apis/js-apis-font.md) are supported.
Default font: **'HarmonyOS Sans'**| | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | No| Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md index 41565994b98dbaa17af0697226c1571bdefac2c9..5c9fa5a862602949c3a4d7b578ea6da56ff6a630 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-span.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-span.md @@ -58,6 +58,12 @@ struct SpanExample { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { Text('Basic Usage').fontSize(9).fontColor(0xCCCCCC) + Text() { + Span('In Line') + Span(' Component') + Span(' !') + } + Text() { Span('This is the Span component').fontSize(12).textCase(TextCase.Normal) .decoration({ type: TextDecorationType.None, color: Color.Red }) @@ -118,4 +124,4 @@ struct SpanExample { } ``` -![span](figures/span.png) +![Span](figures/span.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md index 07b043411ed7ce7658cb575490e559e0dbd3aab0..daf26e98a24a303138f9f79c88c4340c73ba629a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -26,6 +26,11 @@ StepperItem() | nextLabel | string | Text label of the button on the right. The default value is **Start** for the last page and **Next** for the other pages.| | status | [ItemState](#itemstate) | Display status of **nextLabel** in the stepper. Optional.
Default value: **ItemState.Normal**| +> **NOTE** +> +> - The **\** component does not support setting of the universal width attribute. By default, its width is the same as that of the parent **\** component. +> - The **\** component does not support setting of the universal height attribute. Its height is the height of the parent **\** component minus the height of the label button. +> - The **\** component does not support setting of the **aspectRadio** or **constrainSize** attribute, which may affect the length and width. ## ItemState | Name | Description| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index bbfc708b4f22509f4499260143aa8977f2e7c2e4..b954a29e75cae3bbabf88dc1a23935655cdb8c9f 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -31,17 +31,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md) and [ | Name | Type | Description | | ----------------------- | ----------------------------------- | ------------------------------------------- | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**
**NOTE**
The text takes up the full width of the **\** component. To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. Yet, it can work with the **textAlign** attribute to jointly determine the horizontal position of the text.
Since API version 9, this API is supported in ArkTS widgets.| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines**. Otherwise, the setting does not take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**. If **overflow** is set to **TextOverflow.Marquee**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect.
Since API version 9, this API is supported in ArkTS widgets. | -| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.
Since API version 9, this API is supported in ArkTS widgets. | +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines**. Otherwise, the setting does not take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**. If **overflow** is set to **TextOverflow.Marquee**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect.
Since API version 9, this API is supported in ArkTS widgets.| +| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.
Since API version 9, this API is supported in ArkTS widgets.| | lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| -| baselineOffset | number \| string | Baseline offset of the text. The default value is **0**.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**

If this attribute is set to a percentage, the default value is used.| +| baselineOffset | number \| string | Baseline offset of the text. The default value is **0**.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If this attribute is set to a percentage, the default value is used. | | letterSpacing | number \| string | Letter spacing.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If this attribute is set to a percentage, the default value is used.
If this attribute is set to a negative value, the letters will overlap each other.| | minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.
For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings.
Since API version 9, this API is supported in ArkTS widgets. | | maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.
For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings.
Since API version 9, this API is supported in ArkTS widgets. | | textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**
Since API version 9, this API is supported in ArkTS widgets.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.
**NOTE**
When this attribute is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, a long press on the text will display a context menu that offers the copy and select-all options.| -| draggable(deprecated) | boolean | Drag effect of the selected text.
This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.
It must be used together with **copyOption**. When it is set to **true** and **copyOptions** is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, the selected text can be dragged and copied to the text box.
Default value: **false**
**NOTE**
This API is supported since API version 8 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.
**NOTE**
When this attribute is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, a long press on the text will display a context menu that offers the copy and select-all options. | +| draggable | boolean | Drag effect of the selected text.
This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.
It must be used together with **copyOption**. When it is set to **true** and **copyOptions** is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, the selected text can be dragged and copied to the text box.
Default value: **false**
**NOTE**
This API is supported since API version 9. | | textShadow10+ | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) | Text shadow.| | heightAdaptivePolicy10+ | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | How the adaptive height is determined for the text.
Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**
**NOTE**
When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the **maxLines** attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to allow for more content to be shown.
When this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**.
When this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the layout still exceeds the layout constraints after the font size is reduced to **minFontSize**, the lines that exceed the layout constraints are deleted. | | textIndent10+ | number \| string | Indentation of the first line.
Default value: **0**| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 61accc536e8ad4a8a06ed06e879a8de4ca4028ae..d159c2eac377744ee3defd0e90f4c55d45a81d9c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -46,7 +46,7 @@ Among the [universal attributes](ts-universal-attributes-size.md) and [universal | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | Caret style. | | caretPosition10+ | number | Caret position.| | showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.
By default, there is no unit.| -| showError10+ | string \| undefined | Error text displayed when an error occurs.
By default, no error text is displayed.| +| showError10+ | string \| undefined | Error message displayed when an error occurs.
By default, no error message is displayed.
**NOTE**
If the parameter type is string and the input content does not comply with specifications, the error message is displayed. If the parameter type is undefined, no error message is displayed. See [Example 2](#example-2).| | showUnderline10+ | boolean | Whether to show an underline.
Default value: **false**| | passwordIcon10+ | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.
By default, the system-provided icon is used.| | enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | @@ -249,17 +249,20 @@ struct TextInputExample { ### Example 2 ```ts -// xxx.ets @Entry @Component struct TextInputExample { - @State PassWordSrc1:Resource=$r('app.media.icon') - @State PassWordSrc2:Resource=$r('app.media.icon') + @State PassWordSrc1: Resource = $r('app.media.onIcon') + @State PassWordSrc2: Resource = $r('app.media.offIcon') + @State TextError: string = undefined + @State Text: string = '' + @State NameText: string = 'test' + @Builder itemEnd() { Select([{ value: 'KB' }, { value: 'MB' }, - { value: 'GB'}, - { value: 'TB',}]) + { value: 'GB' }, + { value: 'TB', }]) .height("48vp") .borderRadius(0) .selected(2) @@ -270,33 +273,52 @@ struct TextInputExample { .selectedOptionFont({ size: 20, weight: 400 }) .optionFont({ size: 20, weight: 400 }) .backgroundColor(Color.Transparent) - .responseRegion({height:"40vp",width:"80%",x:'10%',y:'6vp'}) + .responseRegion({ height: "40vp", width: "80%", x: '10%', y: '6vp' }) .onSelect((index: number) => { console.info('Select:' + index) }) } build() { - Column() { + Column({ space: 20 }) { // Customize the password icon. - TextInput({ placeholder: 'user define password icon' }) + TextInput({ placeholder: 'Custom password icon' }) .type(InputType.Password) - .width(400) + .width(380) .height(60) - .passwordIcon({onIconSrc:this.PassWordSrc1,offIconSrc : this.PassWordSrc2}) + .passwordIcon({ onIconSrc: this.PassWordSrc1, offIconSrc: this.PassWordSrc2 }) // Show an underline. - TextInput({ placeholder: 'underline style' }) + TextInput({ placeholder: 'Underline style' }) .showUnderline(true) - .width(400) + .width(380) .height(60) .showError('Error') .showUnit(this.itemEnd.bind(this)) + + Text (`User name: ${this.Text}`) + .width('95%') + TextInput({ placeholder: 'Enter user name', text: this.Text }) + .showUnderline(true) + .width(380) + .showError(this.TextError) + .onChange((value: string) => { + this.Text = value + }) + .onSubmit(() => {// If the entered user name is incorrect, the text box will be cleared and the error message will be displayed. + if (this.Text == this.NameText) { + this.TextError = undefined + } else { + this.TextError ='Incorrect user name.' + this.Text = '' + } + }) + }.width('100%') } } ``` -![showUnit](figures/showUnit.png) +![TextInputError](figures/TextInputError.png) ### Example 3 diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 1c4f04d875cf51f6868700329791bcd2298c7226..7b3d5620b87e6c945368f0a65a8ced5fa6ce08d0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -45,10 +45,12 @@ In addition to the [universal events](ts-universal-events-click.md), the followi ## TimePickerResult -| Name | Type | Description | -| ------ | ------ | ------- | -| hour | number | Hour portion of the selected time.| -| minute | number | Minute portion of the selected time.| +Describes a time in 24-hour format. + +| Name | Type| Description | +| ------ | -------- | ----------------------------------- | +| hour | number | Hour portion of the selected time.
Value range: [0-23]| +| minute | number | Minute portion of the selected time.
Value range: [0-59]| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index 13ec25f92964ea6f702626768a41df16498eadb2..a560989fc99950dc7a6d3133e536f63ceebceb29 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -58,14 +58,14 @@ Since API version 9, child components are supported when **type** is set to **"c > The non-UI logic written internally needs to be encapsulated in one or more functions. ## Attributes -- You can customize the content displayed in the **\**. Depending on the **type** settings, the support for the universal attributes [background](./ts-universal-attributes-background.md), [opacity](./ts-universal-attributes-opacity.md), and [image effects](./ts-universal-attributes-image-effect.md) varies: -- When **type** is set to **SURFACE("surface")**, none of these attributes is supported. For configuration, you are advised to use the APIs provided by EGL/OpenGL ES instead. -- When **type** is set to **COMPONENT("component")**, none of these attributes is supported. For configuration, you are advised to mount child components. -- When **type** is set to **TEXTURE**, only [opacity](./ts-universal-attributes-opacity.md) and **backgroundColor** in [background](./ts-universal-attributes-background.md) are supported. For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. +- You can customize the content displayed in the **\**. Depending on the **type** settings, the support for the universal attributes [background](ts-universal-attributes-background.md), [opacity](ts-universal-attributes-opacity.md), and [image effects](ts-universal-attributes-image-effect.md) varies. +- When **type** is set to **SURFACE("surface")**, only the **shadow** attribute of [image effects](ts-universal-attributes-image-effect.md). For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. +- When **type** is set to **COMPONENT("component")**, only the **shadow** attribute of [image effects](ts-universal-attributes-image-effect.md). For configuration of other attributes, you are advised to mount child components. +- When **type** is set to **TEXTURE**, only the **backgroundColor** attribute of [background](ts-universal-attributes-background.md), the **shadow** attribute of [image effects](ts-universal-attributes-image-effect.md), and [opacity](ts-universal-attributes-opacity.md) are supported. For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. ## Events -When **type** is set to **SURFACE("surface")** or **TEXTURE**, the following events are supported. The [universal events](ts-universal-events-click.md) and gestures (ts-gesture-settings.md) are not supported. +When **type** is set to **SURFACE("surface")** or **TEXTURE**, the following events are supported. The [universal events](ts-universal-events-click.md) are not supported. ### onLoad diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index 4dd9922e85fcbb464dc189c032af8a2136e44f28..38195901492db82a74671c4dcdbaff902f44e707 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ---- | ---------------------------------------- | -| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If the set value is a negative number, the default value will be used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| +| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If this parameter is set to a negative number or a value greater than or equal to the length of the list content area, the default value is used.
If this parameter is set to a value less than the width of the list divider, the width of the list divider is used as the spacing.| | initialIndex | number | No | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.| | scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| diff --git a/en/application-dev/reference/arkui-ts/ts-container-panel.md b/en/application-dev/reference/arkui-ts/ts-container-panel.md index b0359c645851f1e28e8f3ab8a3371d3f501df89d..093b3df029ae47cd1a91e5764ff79c176c1baa24 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-panel.md +++ b/en/application-dev/reference/arkui-ts/ts-container-panel.md @@ -38,8 +38,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | fullHeight | string \| number | Panel height in the **PanelMode.Full** mode.
Default value: main axis height of the panel minus 8 vp
**NOTE**
This attribute cannot be set in percentage.| | halfHeight | string \| number | Panel height in the **PanelMode.Half** mode.
Default value: half of the main axis height of the panel
**NOTE**
This attribute cannot be set in percentage.| | miniHeight | string \| number | Panel height in the **PanelMode.Mini** mode.
Default value: **48**
Unit: vp
**NOTE**
This attribute cannot be set in percentage.| -| show | boolean | Whether to show the panel.| -| backgroundMask9+|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.| +| show | boolean | Whether to show the panel.
Default value: **true**| +| backgroundMask9+|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.
Default value: **'#08182431'**| | showCloseIcon10+ | boolean | Whether to display the close icon. The value **true** means to display the close icon, and **false** means the opposite.
Default value: **false**| ## PanelType diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 0756ef290138140a62b2602cd7860d03da07929c..6abc233cabed1abe450318daa33a1b4aedf8a2ca 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -18,6 +18,8 @@ This component can contain child components. > When the **\** component's **displayMode** attribute is set to **SwiperDisplayMode.AutoLinear** or its **displayCount** attribute is set to **'auto'**, the child component whose **visibility** attribute is set to **None** does not take up space in the viewport, but this does not affect the number of navigation dots. > > If the **visibility** attribute of a child component is set to **None** or **Hidden**, it takes up space in the viewport, but is not displayed. +> +> When the number of child components is less than or equal to the total number of allowed nodes (totalDisplayCount = DisplayCount + prevMargin? (1: 0 ) + nextMargin? (1: 0 )) in the content area, the **\** component uses the non-looping mode for layout. In this case, the child components specified by **nextMargin** and **prevMargin** take up space in the viewport, but are not displayed. The specifications of the **\** component are calculated based on the value of **totalDisplayCount**. ## APIs diff --git a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md index 44ff79e8bc80a7f2c88dc380febfc916c93aa87b..6bd1b259adeacfd05ac937a421a86b06504451ed 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md @@ -12,7 +12,7 @@ An action sheet is a dialog box that displays actions a user can take. ## ActionSheet.show -show(value: { title: string | Resource, message: string | Resource, confirm?: {value: string | Resource, action:() => void}, cancel?:()=>void, sheets: Array<SheetInfo>, autoCancel?:boolean, alignment?: DialogAlignment, offset?: { dx: number | string | Resource; dy: number | string | Resource } }) +show(value: { title: string | Resource, subtitle: Resource, message: string | Resource, confirm?: {enabled?: boolean, defaultFocus?: boolean, style?: DialogButtonStyle, value: string | Resource, action:() => void}, cancel?:()=>void, sheets: Array<SheetInfo>, autoCancel?:boolean, alignment?: DialogAlignment, offset?: { dx: number | string | Resource; dy: number | string | Resource } }) Defines and shows the action sheet. @@ -21,13 +21,15 @@ Defines and shows the action sheet. | Name | Type | Mandatory | Description | | ---------- | -------------------------- | ------- | ----------------------------- | | title | [Resource](ts-types.md#resource) \| string | Yes | Title of the dialog box.| +| subtitle10+ | [ResourceStr](ts-types.md#resourcestr) | No| Subtitle of the dialog box.| | message | [Resource](ts-types.md#resource) \| string | Yes | Content of the dialog box. | | autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.
Default value: **true**
The value **true** means to close the dialog box when the overlay is clicked, and **false** means the opposite.| -| confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
action: () => void
} | No | Text content of the confirm button and callback upon button clicking.
Default value:
**value**: button text.
**action**: callback upon button clicking.| +| confirm | {
enabled10+?: boolean,
defaultFocus10+?: boolean,
style10+?: [DialogButtonStyle](#dialogbuttonstyle10),
value: [ResourceStr](ts-types.md#resourcestr),
action: () => void
} | No | Information about the confirm button.
**enabled**: whether to respond when the button is clicked.
Default value: **true**
**defaultFocus**: whether the button is the default focus.
Default value: **false**
**style**: button style.
Default value: **DialogButtonStyle.DEFAULT**
**value**: button text.
**action**: callback upon button clicking.| | cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked. | | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Bottom**| -| offset | {
dx: Length,
dy: Length
} | No | Offset of the dialog box relative to the alignment position.
Default value: {
dx: 0,
dy: 0
} | +| offset | {
dx: Length,
dy: Length
} | No | Offset of the dialog box relative to the alignment position.{
dx: 0,
dy: 0
} | | sheets | Array<SheetInfo> | Yes | Options in the dialog box. Each option supports the image, text, and callback.| +| maskRect10+ | [Rectangle](ts-methods-alert-dialog-box.md#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| ## SheetInfo @@ -37,6 +39,13 @@ Defines and shows the action sheet. | icon | [ResourceStr](ts-types.md#resourcestr) | No | Sheet icon. By default, no icon is displayed. | | action | ()=>void | Yes | Callback when the sheet is selected.| +## DialogButtonStyle10+ + +| Name | Description. | +| --------- | --------------------------------- | +| DEFAULT | Blue text on white background (black background under the dark theme).| +| HIGHLIGHT | White text on blue background. | + ## Example @@ -51,9 +60,11 @@ struct ActionSheetExample { .onClick(() => { ActionSheet.show({ title: 'ActionSheet title', + subtitle: 'ActionSheet subtitle', message: 'message', autoCancel: true, confirm: { + defaultFocus: true, value: 'Confirm button', action: () => { console.log('Get Alert Dialog handled') @@ -92,4 +103,4 @@ struct ActionSheetExample { } ``` -![en-us_image_0000001241668363](figures/en-us_image_0000001241668363.gif) +![en-us_image_action](figures/en-us_image_action.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md b/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md index 282865563a52e5e7b0d78d5387fe09898c57b31c..9ec9738b94e09d521054ee13c94ed3f86bcccb8a 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-alert-dialog-box.md @@ -14,32 +14,105 @@ You can set the text content and response callback for an alert dialog box. | Name | Type | Description| | ---- | --------------- | -------- | -| show | [AlertDialogParamWithConfirm](#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](#alertdialogparamwithbuttons) | Defines and displays the **\** component. | +| show | [AlertDialogParamWithConfirm](#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](#alertdialogparamwithbuttons) \| [AlertDialogParamWithOptions](#alertdialogparamwithoptions10) | Defines and displays the **\** component.| ## AlertDialogParamWithConfirm | Name | Type | Mandatory | Description | | ---------- | ---------------- | ---------- | ------------------------------- | | title | [ResourceStr](ts-types.md#resourcestr) | No | Title of the dialog box.| +| subtitle10+ | [ResourceStr](ts-types.md#resourcestr) | No| Subtitle of the dialog box.| | message | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the dialog box.| | autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.
Default value: **true**| -| confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void
} | No | Text content, text color, background color, and click callback of the confirm button.| +| confirm | {
enabled10+?: boolean,
defaultFocus10+?: boolean,
style10+?: [DialogButtonStyle](#dialogbuttonstyle10),
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void
} | No | Information about the confirm button.
**enabled**: whether to respond when the button is clicked.
Default value: **true**
**defaultFocus**: whether the button is the default focus.
Default value: **false**
**style**: button style.
Default value: **DialogButtonStyle.DEFAULT**
**value**: text of the button.
**fontColor**: font color of the button.
**backgroundColor**: background color of the button.
**action**: callback when the button is selected.| | cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked.| | alignment | [DialogAlignment](#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| | offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.
Default value: **{ dx: 0 , dy: 0 }**| | gridCount | number | No | Number of grid columns occupied by the width of the dialog box.
Default value: **4**| +| maskRect10+| [Rectangle](#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| + +Priorities of the **confirm** parameters: **fontColor** and **backgroundColor** > **style** > **defaultFocus** + +| backgroundColor | fontColor | style | defaultFocus | Effect | +| --------------- | --------- | --------------------------- | ------------ | -------- | +| Green | Red | - | - | Red text on green background| +| Green | - | DialogButtonStyle.HIGHLIGHT | - | White text on green background| +| Green | - | DialogButtonStyle.DEFAULT | - | Blue text on green background| +| Green | - | - | TRUE | White text on green background| +| Green | - | - | FALSE/- | Blue text on green background| +| - | Red | DialogButtonStyle.HIGHLIGHT | - | Red text on blue background| +| - | Red | DialogButtonStyle.DEFAULT | - | Red text on white background| +| - | Red | - | TRUE | Red text on blue background| +| - | Red | - | FALSE/- | Red text on white background| +| - | - | DialogButtonStyle.HIGHLIGHT | - | White text on blue background| +| - | - | DialogButtonStyle.DEFAULT | - | Blue text on white background| +| - | - | - | TRUE | White text on blue background| +| - | - | - | FALSE/- | Blue text on white background| ## AlertDialogParamWithButtons | Name | Type | Mandatory | Description | | --------------- | ---------------------- | ------------ | --------------------- | | title | [ResourceStr](ts-types.md#resourcestr) | No | Title of the dialog box. | +| subtitle10+ | [ResourceStr](ts-types.md#resourcestr) | No| Subtitle of the dialog box.| +| message | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the dialog box. | +| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.
Default value: **true** | +| primaryButton | {
enabled10+?: boolean,
defaultFocus10+?: boolean,
style10+?: [DialogButtonStyle](#dialogbuttonstyle10),
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void;
} | No| Information about the confirm button.
**enabled**: whether to respond when the button is clicked.
Default value: **true**
**defaultFocus**: whether the button is the default focus.
Default value: **false**
**style**: button style.
Default value: **DialogButtonStyle.DEFAULT**
**value**: text of the button.
**fontColor**: font color of the button.
**backgroundColor**: background color of the button.
**action**: callback when the button is selected.| +| secondaryButton | {
enabled10+?: boolean,
defaultFocus10+?: boolean,
style10+?: [DialogButtonStyle](#dialogbuttonstyle10),
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void;
} | No | Information about the confirm button.
**enabled**: whether to respond when the button is clicked.
Default value: **true**
**defaultFocus**: whether the button is the default focus.
Default value: **false**
**style**: button style.
Default value: **DialogButtonStyle.DEFAULT**
**value**: text of the button.
**fontColor**: font color of the button.
**backgroundColor**: background color of the button.
**action**: callback when the button is selected.| +| cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked. | +| alignment | [DialogAlignment](#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| +| offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.| +| gridCount | number | No | Number of grid columns occupied by the width of the dialog box.| +| maskRect10+ | [Rectangle](#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| + +## AlertDialogParamWithOptions10+ +| Name | Type | Mandatory | Description | +| --------------- | ---------------------- | ------------ | --------------------- | +| title | [ResourceStr](ts-types.md#resourcestr) | No | Title of the dialog box. | +| subtitle10+ | [ResourceStr](ts-types.md#resourcestr) | No | Subtitle of the dialog box. | | message | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the dialog box. | | autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.
Default value: **true** | -| primaryButton | {
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void;
} | No| Text content, text color, background color, and click callback of the primary button.| -| secondaryButton | {
value: [ResourceStr](ts-types.md#resourcestr),
fontColor?: [ResourceColor](ts-types.md#resourcecolor),
backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),
action: () => void;
} | No | Text content, text color, background color, and click callback of the secondary button.| | cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked. | | alignment | [DialogAlignment](#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| | offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.| | gridCount | number | No | Number of grid columns occupied by the width of the dialog box.| +| maskRect10+| [Rectangle](#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| +| buttons10+ | Array<[AlertDialogButtonOptions](#alertdialogbuttonoptions10)> | No | Buttons in the dialog box.| +|buttonDirection10+ | [DialogButtonDirection](#dialogbuttondirection10)| No | Direction in which buttons are laid out.
Default value: **DialogButtonDirection.AUTO**
When there are more than three buttons, the Auto mode (which automatically switches to the vertical layout when there are more than two buttons) is recommended. In non-Auto mode, buttons that extend beyond the display area are clipped.| + +## AlertDialogButtonOptions10+ +| Name | Type | Mandatory | Description | +| ------------------| ---------------------- | ------------ | --------------------- | +| enabled | boolean | No | Whether to respond when the button is clicked.
Default value: **true** | +| defaultFocus | boolean | No | Whether the button is the default focus.
Default value: **false** | +| style | [DialogButtonStyle](#dialogbuttonstyle10) | No | Style of the button.
Default value: **DialogButtonStyle.DEFAULT** | +| value | [ResourceStr](ts-types.md#resourcestr) | Yes | Text of the button. If the value is null, the button is not displayed. | +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the button. | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the button. | +| action | () => void | Yes | Callback when the button is selected. | + +## DialogButtonDirection10+ +| Name | Description | +| -------------------------- | --------- | +| AUTO | Buttons are laid out horizontally when there are two or fewer buttons and vertically otherwise.| +| HORIZONTAL | Buttons are laid out horizontally.| +| VERTICAL | Buttons are laid out vertically.| + +Priorities of the **confirm** parameters: **fontColor** and **backgroundColor** > **style** > **defaultFocus** + +| backgroundColor | fontColor | style | defaultFocus | Effect | +| --------------- | --------- | --------------------------- | ------------ | -------- | +| Green | Red | - | - | Red text on green background| +| Green | - | DialogButtonStyle.HIGHLIGHT | - | White text on green background| +| Green | - | DialogButtonStyle.DEFAULT | - | Blue text on green background| +| Green | - | - | TRUE | White text on green background| +| Green | - | - | FALSE/- | Blue text on green background| +| - | Red | DialogButtonStyle.HIGHLIGHT | - | Red text on blue background| +| - | Red | DialogButtonStyle.DEFAULT | - | Red text on white background| +| - | Red | - | TRUE | Red text on blue background| +| - | Red | - | FALSE/- | Red text on white background| +| - | - | DialogButtonStyle.HIGHLIGHT | - | White text on blue background| +| - | - | DialogButtonStyle.DEFAULT | - | Blue text on white background| +| - | - | - | TRUE | White text on blue background| +| - | - | - | FALSE/- | Blue text on white background| ## DialogAlignment @@ -56,6 +129,32 @@ You can set the text content and response callback for an alert dialog box. | BottomStart8+ | Bottom left alignment. | | BottomEnd8+ | Bottom right alignment. | +## Rectangle10+ + +The **Rectangle** type is used to represent a mask area of a dialog box. + +| Name | Type | Mandatory| Description | +|--------|------------------------------|----|-----------------------------------| +| x | [Length](ts-types.md#length) | No | X coordinate of the mask area of the dialog box relative to the upper left corner of the window.
Default value: **0vp**| +| y | [Length](ts-types.md#length) | No | Y coordinate of the mask area of the dialog box relative to the upper left corner of the window.
Default value: **0vp**| +| width | [Length](ts-types.md#length) | No | Width of the mask area of the dialog box.
Default value: **'100%'** | +| height | [Length](ts-types.md#length) | No | Height of the mask area of the dialog box.
Default value: **'100%'** | + +> **NOTE** +> +> **x** and **y** can be set to a positive or negative percentage value. When **x** is set to **'100%'**, the mask area is moved rightward by the window width. When **x** is set to **'-100%'**, the mask area is moved leftward by the window width. When **y** is set to **'100%'**, the mask area is moved downward by the window height. When **y** is set to **'-100%'**, the mask area is moved upward by the window height. +> +> **width** and **height** can be set in percentage and can only be set to positive values. If they are set to negative values, the default values are used instead. +> +> The percentage is calculated based on the width and height of the window. + +## DialogButtonStyle10+ + +| Name | Description | +| --------- | --------------------------------- | +| DEFAULT | Blue text on white background (black background under the dark theme).| +| HIGHLIGHT | White text on blue background. | + ## Example ```ts @@ -93,6 +192,7 @@ struct AlertDialogExample { AlertDialog.show( { title: 'title', + subtitle: 'subtitle', message: 'text', autoCancel: true, alignment: DialogAlignment.Bottom, @@ -105,6 +205,9 @@ struct AlertDialogExample { } }, secondaryButton: { + enabled: true, + defaultFocus: true, + style: DialogButtonStyle.HIGHLIGHT, value: 'ok', action: () => { console.info('Callback when the second button is clicked') @@ -116,9 +219,50 @@ struct AlertDialogExample { } ) }).backgroundColor(0x317aff) + Button('three button dialog') + .onClick(() => { + AlertDialog.show( + { + title: 'title', + subtitle: 'subtitle', + message: 'text', + autoCancel: true, + alignment: DialogAlignment.Bottom, + gridCount: 4, + offset: { dx: 0, dy: -20 }, + buttonDirection: DialogButtonDirection.HORIZONTAL, + buttons: [ + { + value: 'Button', + action: () => { + console.info('Callback when button1 is clicked') + } + }, + { + value: 'Button', + action: () => { + console.info('Callback when button2 is clicked') + } + }, + { + value: 'Button', + enabled: true, + defaultFocus: true, + style: DialogButtonStyle.HIGHLIGHT, + action: () => { + console.info('Callback when button3 is clicked') + } + }, + ], + cancel: () => { + console.info('Closed callbacks') + } + } + ) + }).backgroundColor(0x317aff) }.width('100%').margin({ top: 5 }) } } ``` -![en-us_image_0000001174582844](figures/en-us_image_0000001174582844.gif) +![en-us_image_alert](figures/en-us_image_alert.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index d1116127a919655e1ee00e8bfcc4dbe770ed75eb..859579fbab98bf9515bef2102d4528c67d167723 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -11,8 +11,7 @@ A custom dialog box is a dialog box you customize by using APIs of the **CustomD ## APIs -CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, openAnimation?: AnimateParam, closeAniamtion?: AnimateParam, showInSubWindow?: boolean}) - +CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, maskRect?: Rectangle, openAnimation?: AnimateParam, closeAniamtion?: AnimateParam, showInSubWindow?: boolean, backgroundColor?:ResourceColor, cornerRadius?:Dimension \| BorderRadiuses}) **Parameters** @@ -26,9 +25,12 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | customStyle | boolean | No | Whether to use a custom style for the dialog box.
Default value: **false**, which means that the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height; the rounded corner is 24 vp.| | gridCount8+ | number | No | Number of [grid columns](../../ui/arkts-layout-development-grid-layout.md) occupied by the dialog box.
The default value is subject to the window size, and the maximum value is the maximum number of columns supported by the system. If this parameter is set to an invalid value, the default value is used.| | maskColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Custom mask color.
Default value: **0x33000000** | +| maskRect10+ | [Rectangle](ts-methods-alert-dialog-box.md#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| | openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the open animation of the dialog box.
**NOTE**
**iterations**: The default value is **1**, indicating that the animation is played once; any other value evaluates to the default value.
**playMode**: The default value is **PlayMode.Normal**; any other value evaluates to the default value.| | closeAniamtion10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the close animation of the dialog box.
**NOTE**
**iterations**: The default value is **1**, indicating that the animation is played once; any other value evaluates to the default value.
**playMode**: The default value is **PlayMode.Normal**; any other value evaluates to the default value. | -| showInSubWindow10+ | boolean | No | Whether to display a dialog box in a subwindow.
Default value: **false**, indicating that the dialog box is not displayed in the subwindow
**NOTE**
A dialog box whose **showInSubWindow** attribute is **true** cannot trigger the display of another dialog box whose **showInSubWindow** attribute is also **true**.| +| showInSubWindow10+ | boolean | No | Whether to show the dialog box in a sub-window when the dialog box needs to be displayed outside the main window.
Default value: **false**, indicating that the dialog box is not displayed in the subwindow
**NOTE**
A dialog box whose **showInSubWindow** attribute is **true** cannot trigger the display of another dialog box whose **showInSubWindow** attribute is also **true**.| +| backgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the dialog box. | +| cornerRadius10+ | [BorderRadiuses](ts-types.md#borderradiuses9) \| [Dimension](ts-types.md#dimension10) | No | Radius of the rounded corners of the background.
You can set separate radiuses for the four rounded corners.
Default value: **{ topLeft: '24vp', topRight: '24vp', bottomLeft: '24vp', bottomRight: '24vp' }**
**NOTE**
This attribute must be used together with the [borderRadius](ts-universal-attributes-border.md) attribute.| ## CustomDialogController @@ -89,8 +91,8 @@ struct CustomDialogExample { this.confirm() }).backgroundColor(0xffffff).fontColor(Color.Red) }.margin({ bottom: 10 }) - } - // The default value of borderRadius is 24vp. The border attribute must be used together with the borderRadius attribute. + }.borderRadius(10) + // When using the border or cornerRadius attribute, use it together with the borderRadius attribute. } } @@ -111,13 +113,15 @@ struct CustomDialogUser { alignment: DialogAlignment.Default, offset: { dx: 0, dy: -20 }, gridCount: 4, - customStyle: false + customStyle: false, + backgroundColor: 0xd9ffffff, + cornerRadius: 10, }) // Delete the dialogController instance and set it to undefined when the custom component is about to be destroyed. aboutToDisappear() { delete this.dialogController, // Delete the dialogController instance. - this.dialogController = undefined // Set dialogController to undefined. + this.dialogController = undefined //Set dialogController to undefined. } onCancel() { @@ -145,4 +149,4 @@ struct CustomDialogUser { } ``` -![en-us_image_0000001212058470](figures/en-us_image_0000001212058470.gif) +![en-us_image_custom](figures/en-us_image_custom.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index a13af458a12ee903e11a7a6c4f2bb4079fa122c3..f6294e602662e64ff0548248c98dd3b9b9c40f3d 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -29,6 +29,9 @@ Shows a date picker dialog box. | disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | | textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | | selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | +| alignment10+ | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| +| offset10+ | [Offset](ts-types.md#offset) | No | Offset of the dialog box based on the **alignment** settings.
Default value: **{ dx: 0 , dy: 0 }**| +| maskRect10+| [Rectangle](ts-methods-alert-dialog-box.md#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| | onAccept(deprecated) | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.
**NOTE**
This API is supported since API version 8 and deprecated since API version 10. You are advised to use **onDateAccept** instead.| | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| | onChange(deprecated) | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| Callback invoked when the selected item in the picker changes.
**NOTE**
This API is supported since API version 8 and deprecated since API version 10. You are advised to use **onDateChange** instead.| diff --git a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 77fa5b3113ea4d9885d7771460488b2294e75459..9ea19b5b40ebf7b1de9158fda5602610d6ce1ad1 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -26,6 +26,9 @@ Shows a time picker dialog box. | disappearTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width for the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | | textStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | | selectedTextStyle10+ | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | No| Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | +| alignment10+ | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| +| offset10+ | [Offset](ts-types.md#offset) | No | Offset of the dialog box based on the **alignment** settings.
Default value: **{ dx: 0 , dy: 0 }**| +| maskRect10+| [Rectangle](ts-methods-alert-dialog-box.md#rectangle10) | No | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**| | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.| diff --git a/en/application-dev/reference/arkui-ts/ts-types.md b/en/application-dev/reference/arkui-ts/ts-types.md index 00799c76b97e399281f1593d182fea925bee3c23..436456b5e4c60d9808fe4b16e5dffba036bccdda 100644 --- a/en/application-dev/reference/arkui-ts/ts-types.md +++ b/en/application-dev/reference/arkui-ts/ts-types.md @@ -158,7 +158,7 @@ The **Font** type is used to set the text style. | ------ | ---------------------------------------- | ---- | ---------------------------------------- | | size | [Length](#length) | No | Font size. If the value is of the number type, the unit fp is used. The value cannot be a percentage.
Default value: **16.0** | | weight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a thicker font.
Default value: **400** \| **FontWeight.Normal** | -| family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, HarmonyOS Sans'**. Currently, only the **'HarmonyOS Sans'** font is supported.| +| family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, HarmonyOS Sans'**. The HarmonyOS Sans font and [register custom fonts](../apis/js-apis-font.md) are supported.| | style | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style.
Default value: **FontStyle.Normal** | ## Area8+ diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index 0814773979c1fb7964b4f032a57addd1de6614eb..6191f29c57ebef1ac6280035fd5894aca2fac4d9 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -16,14 +16,14 @@ You can draw an image around a component. This API is supported in ArkTS widgets. -| Name | Type | Description | -| ------ | ---------------------------------------- | ---------------------------------------- | +| Name | Type | Description | +| ------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.
**NOTE**
The border image source applies only to container components, such as **\**, **\**, and **\**.| -| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.
Default value: **0** | -| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.
Default value: **0** | -| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.
Default value: **0** | -| repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.
Default value: **RepeatMode.Stretch** | -| fill | boolean | Whether to fill the center of the border image.
Default value: **false** | +| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the upper left corner, upper right corner, lower left corner, and lower right corner of the border image.
Default value: **0**
**NOTE**
If this parameter is set to a negative value, the default value is used.
When this parameter is set to a value of the [Length](ts-types.md#length) type, the value applies to the four corners in a unified manner.
When this parameter is set to a value of the [EdgeWidths](ts-types.md#edgewidths9) type:
- **Top**: slice height of the upper left or upper right corner of the image.
- **Bottom**: slice height of the lower left or lower right corner of the image.
- **Left**: slice width of the upper left or lower left corner of the image.
- **Right**: slice width of the upper right or lower right corner of the image.| +| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.
Default value: **0**
**NOTE**
If this parameter is set to a negative value, the default value is used.
When this parameter is set to a value of the [Length](ts-types.md#length) type, the value applies to the four corners in a unified manner.
When this parameter is set to a value of the [EdgeWidths](ts-types.md#edgewidths9) type:
- **Top**: width of the top edge of the border image.
- **Bottom**: width of the bottom edge of the border image.
- **Left**: width of the left edge of the border image.
- **Right**: width of the right edge of the border image.
If this parameter is set to a negative value, the value **1** is used.| +| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.
Default value: **0**
**NOTE**
If this parameter is set to a negative value, the default value is used.
When this parameter is set to a value of the [Length](ts-types.md#length) type, the value applies to the four corners in a unified manner.
When this parameter is set to a value of the [EdgeWidths](ts-types.md#edgewidths9) type:
- **Top**: amount by which the top edge of the border image is extended beyond the border box.
- **Bottom**: amount by which the bottom edge of the border image is extended beyond the border box.
- **Left**: amount by which the left edge of the border image is extended beyond the border box.
- **Right**: amount by which the right edge of the border image is extended beyond the border box.| +| repeat | [RepeatMode](#repeatmode) | Repeat mode of the source image's slices on the border.
Default value: **RepeatMode.Stretch**| +| fill | boolean | Whether to fill the center of the border image.
Default value: **false** | ## RepeatMode @@ -32,9 +32,9 @@ This API is supported in ArkTS widgets. | Name | Description | | ------- | ----------------------------------- | | Repeat | The source image's slices are tiled. Tiles beyond the border box will be clipped. | -| Stretch | The source image's slices stretched to fill the border box. | +| Stretch | The source image's slices are stretched to fill the border box. | | Round | The source image's slices are tiled to fill the border box. Tiles may be compressed when needed.| -| Space | The source image's slices are tiled to fill the border box. Extra space will be filled in between tiles. | +| Space | The source image's slices are tiled to fill the border box. Extra space will be distributed in between tiles. | ## Example @@ -77,35 +77,88 @@ struct Index { // xxx.ets @Entry @Component -struct Index { - @State outSetValue: number = 40 +struct BorderImage { + @State WidthValue: number = 0 + @State SliceValue: number = 0 + @State OutSetValue: number = 0 + @State RepeatValue: RepeatMode[] = [RepeatMode.Repeat, RepeatMode.Stretch, RepeatMode.Round, RepeatMode.Space] + @State SelectIndex: number = 0 + @State SelectText: string = 'Repeat' + @State FillValue: boolean = false build() { Row() { - Column() { + Column({ space: 20 }) { Row() { Text('This is borderImage.').textAlign(TextAlign.Center).fontSize(50) } .borderImage({ source: $r('app.media.icon'), - slice: `${this.outSetValue}%`, - width: `${this.outSetValue}px`, - outset: '5px', - repeat: RepeatMode.Repeat, - fill: false + slice: this.SliceValue, + width: this.WidthValue, + outset: this.OutSetValue, + repeat: this.RepeatValue[this.SelectIndex], + fill: this.FillValue }) - Slider({ - value: this.outSetValue, - min: 0, - max: 100, - style: SliderStyle.OutSet - }) - .margin({ top: 30 }) - .onChange((value: number, mode: SliderChangeMode) => { - this.outSetValue = value - console.info('value:' + value + 'mode:' + mode.toString()) + Column() { + Text(`borderImageSlice = ${this.SliceValue}px`) + Slider({ + value: this.SliceValue, + min: 0, + max: 100, + style: SliderStyle.OutSet + }) + .onChange((value: number, mode: SliderChangeMode) => { + this.SliceValue = value + }) + } + + Column() { + Text(`borderImageWidth = ${this.WidthValue}px`) + Slider({ + value: this.WidthValue, + min: 0, + max: 100, + style: SliderStyle.OutSet + }) + .onChange((value: number, mode: SliderChangeMode) => { + this.WidthValue = value + }) + } + + Column() { + Text(`borderImageOutSet = ${this.OutSetValue}px`) + Slider({ + value: this.OutSetValue, + min: 0, + max: 100, + style: SliderStyle.OutSet }) + .onChange((value: number, mode: SliderChangeMode) => { + this.OutSetValue = value + }) + } + + Row() { + Text('borderImageRepeat: ') + Select([{ value: 'Repeat' }, { value: 'Stretch' }, { value: 'Round' }, { value: 'Space' }]) + .value(this.SelectText) + .selected(this.SelectIndex) + .onSelect((index: number, text: string) => { + this.SelectIndex = index + this.SelectText = text + }) + } + + Row() { + Text(`borderImageFill: ${this.FillValue} `) + Toggle({ type: ToggleType.Switch, isOn: this.FillValue }) + .onChange((isOn: boolean) => { + this.FillValue = isOn + }) + } + } .width('100%') } @@ -114,4 +167,4 @@ struct Index { } ``` -![zh-cn_image_borderImage](figures/borderImage.gif) +![borderImage](figures/borderImage.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index 3344dfa1bbd18b706c1a2318e907063555800c7e..160a2b9608ba5ca045f3e946efbbeccc2e3a8f1f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -17,8 +17,8 @@ Universal text attributes include text style attributes applicable to text conta | fontSize | [Length](ts-types.md#length) | Font size. If the value is of the number type, the unit fp is used. The default font size is 16. This attribute cannot be set in percentage.
Since API version 9, this API is supported in ArkTS widgets.| | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.
Default value: **FontStyle.Normal**
Since API version 9, this API is supported in ArkTS widgets.| | fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal**
Since API version 9, this API is supported in ArkTS widgets.| -| fontFamily | string \| [Resource](ts-types.md#resource) | Font family.
Default value: **'HarmonyOS Sans'**. Currently, only the default font is supported.
Since API version 9, this API is supported in ArkTS widgets.| -| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| +| fontFamily | string \| [Resource](ts-types.md#resource) | Font family.
The HarmonyOS Sans font and [register custom fonts](../apis/js-apis-font.md) are supported.
Since API version 9, this API is supported in ArkTS widgets.| +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index da1bd4a6ee06dd4726613d9a40521bf6dbbf8d02..a6682753afd52af7f2844484ce483bfbb2f9150c 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -6,18 +6,23 @@ A drag event is triggered when a component is dragged. > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > -> The following components support drag and drop actions by default: **\**, **\**, **\