diff --git a/en/application-dev/ability-deprecated/stage-formextension.md b/en/application-dev/ability-deprecated/stage-formextension.md index 65555c40964c90c8d1e48a73aebe60eceec63b0b..d7abb35881e99620daa888b6e4a97bd8697b2521 100644 --- a/en/application-dev/ability-deprecated/stage-formextension.md +++ b/en/application-dev/ability-deprecated/stage-formextension.md @@ -135,7 +135,7 @@ To create a widget in the stage model, you need to implement lifecycle callbacks | Name | Description | Data Type | Default Value Allowed | | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | | name | Name of the Extension ability. This field must be specified. | String | No | - | srcEnty | Path of the Extension ability lifecycle code. This field must be specified.| String | No | + | srcEnty | 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)| @@ -242,7 +242,7 @@ You should override **onDestroy** to implement widget data deletion. } ``` -For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). +For details about how to implement persistent data storage, see [Persisting Preferences Data](../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. diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index 05cdc41e5d2027e9e3bfba373ed14916b3e790a1..270c50cd7be93f369e8b75512d5b99b36ae9545a 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -20,7 +20,7 @@ - [AccessibilityExtensionAbility](accessibilityextensionability.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [InputMethodExtensionAbility](inputmethodextentionability.md) - - [WindowExtensionAbility](windowextensionability.md) + - [WindowExtensionAbility (for System Applications Only)](windowextensionability.md) - Service Widget Development in Stage Model - [Service Widget Overview](service-widget-overview.md) - Developing an ArkTS Widget @@ -36,9 +36,10 @@ - [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md) - Widget Event Development - [Widget Event Capability Overview](arkts-ui-widget-event-overview.md) - - [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) - - [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md) - - [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md) + - [Redirecting to a UIAbility Through the router Event](arkts-ui-widget-event-router.md) + - [Launching a UIAbility in the Background Through the call Event](arkts-ui-widget-event-call.md) + - [Updating Widget Content Through the message Event](arkts-ui-widget-event-formextensionability.md) + - [Updating Widget Content Through the router or call Event](arkts-ui-widget-event-uiability.md) - Widget Data Interaction - [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md) - [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md) @@ -52,7 +53,7 @@ - [Want Overview](want-overview.md) - [Matching Rules of Explicit Want and Implicit Want](explicit-implicit-want-mappings.md) - [Common action and entities Values](actions-entities.md) - - [Using Explicit Want to Start an Ability](ability-startup-with-explicit-want.md) + - [Using Explicit Want to Start an Application Component](ability-startup-with-explicit-want.md) - [Using Implicit Want to Open a Website](ability-startup-with-implicit-want.md) - [Using Want to Share Data Between Applications](data-share-via-want.md) - [Component Startup Rules](component-startup-rules.md) @@ -78,10 +79,10 @@ - [Using Worker for Inter-Thread Communication](itc-with-worker.md) - Mission Management - [Mission Management Scenarios](mission-management-overview.md) - - [Mission Management and Launch Type](mission-management-launch-type.md) + - [Mission and Launch Type](mission-management-launch-type.md) - [Page Stack and MissionList](page-mission-stack.md) - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - - [Application Configuration File (Stage Model)](config-file-stage.md) + - [Application Configuration File](config-file-stage.md) - FA Model Development - [FA Model Development Overview](fa-model-development-overview.md) - FA Mode Application Components diff --git a/en/application-dev/application-models/ability-startup-with-explicit-want.md b/en/application-dev/application-models/ability-startup-with-explicit-want.md index 80b96ce801bed7d8ae79aa2b3ddc566f10fc2bcf..36d41c555bd8d4a5cd0d4d0b7bd291bb2569cee3 100644 --- a/en/application-dev/application-models/ability-startup-with-explicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-explicit-want.md @@ -1,5 +1,7 @@ -# Using Explicit Want to Start an Ability +# Using Explicit Want to Start an Application Component -When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used. Using Explicit Want +When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, then the explicit Want is used. + +## Using Explicit Want The user touches a button in the application to start the UIAbility component to complete a specific task. To start the UIAbility component in explicit Want mode, the **abilityName** and **bundleName** parameters must be specified. For details, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application). diff --git a/en/application-dev/application-models/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md index e3c94b2963e73aaa896eb5691a2af1932aba7d3c..1f3732b00d6b0a9446d18b4c45019f0820f21be4 100644 --- a/en/application-dev/application-models/ability-startup-with-implicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md @@ -5,21 +5,21 @@ This section uses the operation of using a browser to open a website as an examp ```json { "module": { - // ... + ... "abilities": [ { - // ... + ... "skills": [ { "entities": [ "entity.system.home", "entity.system.browsable" - // ... + ... ], "actions": [ "action.system.home", "ohos.want.action.viewData" - // ... + ... ], "uris": [ { @@ -31,9 +31,9 @@ This section uses the operation of using a browser to open a website as an examp }, { "scheme": "http", - // ... + ... } - // ... + ... ] } ] @@ -59,20 +59,19 @@ function implicitStartAbility() { 'uri': 'https://www.test.com:8080/query/student' } context.startAbility(wantInfo).then(() => { - // ... + ... }).catch((err) => { - // ... + ... }) } ``` The matching process is as follows: -1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the ability to match, the matching is successful. -2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the ability to match, the matching is successful. -3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful. -4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful. +1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills** of the application component to match, the matching is successful. +2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills** of the application component to match, the matching is successful. +3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the application component to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful. -If there are multiple matching applications, the system displays a dialog box for you to select one of them. The following figure shows an example. +If there are multiple matching applications, the system displays a dialog box for you to select one of them. The following figure shows an example. -![stage-want1](figures/stage-want1.png) +![](figures/ability-startup-with-implicit-want1.png) \ No newline at end of file diff --git a/en/application-dev/application-models/abilitystage.md b/en/application-dev/application-models/abilitystage.md index 2f44f69d5810bbddf8128777f63360a1cb196fa3..da764a445a6d1a79a601719f069798191641a986 100644 --- a/en/application-dev/application-models/abilitystage.md +++ b/en/application-dev/application-models/abilitystage.md @@ -24,20 +24,20 @@ AbilityStage is not automatically generated in the default project of DevEco Stu // When the HAP of the application is loaded for the first time, initialize the module. } onAcceptWant(want) { - // Triggered only for the ability with the specified launch type. + // Triggered only for the UIAbility with the specified launch type. return "MyAbilityStage"; } } ``` -4. Set **srcEntry** in the [module.json5 file](../quick-start/module-configuration-file.md) to the code path of the module. +4. In the [module.json5 file](../quick-start/module-configuration-file.md), set **srcEntry** to specify the code path of the module as the entry for loading the HAP. ```json { "module": { "name": "entry", "type": "entry", "srcEntry": "./ets/myabilitystage/MyAbilityStage.ts", - // ... + ... } } ``` diff --git a/en/application-dev/application-models/accessibilityextensionability.md b/en/application-dev/application-models/accessibilityextensionability.md index 688eaefa4bc10723d23f880dfbb4c1502cb42053..5e88bb69d8fec4fc1abd5488a5998930a6a894ad 100644 --- a/en/application-dev/application-models/accessibilityextensionability.md +++ b/en/application-dev/application-models/accessibilityextensionability.md @@ -12,13 +12,27 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca This document is organized as follows: -- [AccessibilityExtensionAbility Development](#accessibilityextensionability-development) - - [Creating an Accessibility Extension Service](#creating-an-accessibility-extension-service) - - [Creating a Project](#creating-a-project) - - [Creating an AccessibilityExtAbility File](#creating-an-accessibilityextability-file) - - [Processing an Accessibility Event](#processing-an-accessibility-event) - - [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services) - - [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service) +- [AccessibilityExtensionAbility Overview](#accessibilityextensionability-overview) +- [Creating an Accessibility Extension Service](#creating-an-accessibility-extension-service) +- [Processing an Accessibility Event](#processing-an-accessibility-event) +- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services) +- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service) + +## AccessibilityExtensionAbility Overview + +Accessibility is about giving equal access to everyone so that they can access and use information equally and conveniently under any circumstances. It helps narrow the digital divide between people of different classes, regions, ages, and health status in terms of information understanding, information exchange, and information utilization, so that they can participate in social life more conveniently and enjoy the benefits of technological advances. + +AccessibilityExtensionAbility is an accessibility extension service framework. It allows you to develop your own extension services and provides a standard mechanism for exchanging information between applications and extension services. You can make use of the provided capabilities and APIs to develop accessibility features for users with disabilities or physical limitations. For example, you can develop a screen reader for users with vision impairments. + +Below shows the AccessibilityExtensionAbility framework. + +![AccessibilityFramework](figures/AccessibilityFramework.png) + +1. Accessibility app: extension service application developed based on the AccessibilityExtensionAbility framework, for example, a screen reader application. +2. Target app: application assisted by the accessibility app. +3. AccessibilityAbilityManagerService (AAMS): main service of the AccessibilityExtensionAbility framework, which is used to manage the lifecycle of accessibility apps and provide a bridge for information exchange between accessibility apps and target apps. +4. AccessibilityAbility (AAkit): ability that is used by the accessibility app to build an extension service ability operating environment and that provides interfaces for the accessibility app to query and operate the target app, including performing click/long press operations. +5. AccessibilitySystemAbilityClient (ASACkit): used by the target app to send accessibility events, such as content change events, to AAMS, and respond to the instructions (such as performing click/long press operations) sent by the accessibility app through AAMS. ## Creating an Accessibility Extension Service @@ -40,15 +54,15 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens class AccessibilityExtAbility extends AccessibilityExtensionAbility { onConnect() { - console.log('AccessibilityExtAbility onConnect'); + console.info('AccessibilityExtAbility onConnect'); } onDisconnect() { - console.log('AccessibilityExtAbility onDisconnect'); + console.info('AccessibilityExtAbility onDisconnect'); } onAccessibilityEvent(accessibilityEvent) { - console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); + console.info('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); } } @@ -69,9 +83,9 @@ You can process the service logic for accessibility events in the **onAccessibil ```typescript onAccessibilityEvent(accessibilityEvent) { - console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); + console.info('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); if (accessibilityEvent.eventType === 'pageStateUpdate') { - console.log('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate'); + console.info('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate'); // TODO: Develop custom logic. } } @@ -119,3 +133,4 @@ To enable or disable an accessibility extension service, run the following comma In the preceding commands, **AccessibilityExtAbility** indicates the name of the accessibility extension service, **com.example.demo** indicates the bundle name, and **rg** indicates the capabilities (**r** is short for retrieve). If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed. + diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md index 85dfb9523ca117e691480bcbd2321b5fb3b22304..38119a1b1fe16067f7e89629811327ad079a5d15 100644 --- a/en/application-dev/application-models/actions-entities.md +++ b/en/application-dev/application-models/actions-entities.md @@ -1,9 +1,8 @@ # Common action and entities Values -The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. +The **action** field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit [Want](../reference/apis/js-apis-app-ability-want.md), you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the application component that supports website viewing is matched. Declaring the **action** field in [Want](../reference/apis/js-apis-app-ability-want.md) indicates that the invoked application is expected to support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. - -**Common action Values** +The following **action** values are available: - **ACTION_HOME**: action of starting the application entry component. It must be used together with **ENTITY_HOME**. The application icon on the home screen is an explicit entry component. Users can touch the icon to start the entry component. Multiple entry components can be configured for an application. @@ -14,14 +13,13 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio - **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records. -The [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) field specifies the additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. - +The **entities** field specify the category information (such as browser and video player) of the target application component. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. -**Common entities Values** +The following **entities** values are available: - **ENTITY_DEFAULT**: default category, which is meaningless. -- **ENTITY_HOME**: abilities with an icon displayed on the home screen. +- **ENTITY_HOME**: application components with an icon displayed on the home screen. - **ENTITY_BROWSABLE**: browser type. diff --git a/en/application-dev/application-models/app-deviceconfig-switch.md b/en/application-dev/application-models/app-deviceconfig-switch.md index 1092c21081cd9a8d62c92a1a68ba434efee7c8c9..6c872f0c167bd4779516d611ee07d9036ca550ee 100644 --- a/en/application-dev/application-models/app-deviceconfig-switch.md +++ b/en/application-dev/application-models/app-deviceconfig-switch.md @@ -22,7 +22,7 @@ OpenHarmony has reconstructed the [deviceConfig](../quick-start/deviceconfig-str | deviceConfig in the FA Model| Description| Stage Model| Difference| | -------- | -------- | -------- | -------- | | deviceConfig| Device information.| / | This tag is no longer available in the stage model. In the stage model, device information is configured under the **app** tag.| -| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process.| / | The stage model does not support the configuration of process names.| +| process | Name of the process running the application or UIAbility. If the **process** attribute is configured in the **deviceConfig** tag, all UIAbilities of the application run in this process. You can set the **process** attribute for a specific UIAbility in the **abilities** attribute, so that the UIAbility can run in the particular process.| / | The stage model does not support the configuration of process names.| | keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications.| / | The stage model does not support changing of the model control mode for system applications.| | supportBackup | Whether the application supports data backup and restore.| / | This configuration is not supported in the stage model.| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.| / | This configuration is not supported in the stage model.| diff --git a/en/application-dev/application-models/application-component-configuration-fa.md b/en/application-dev/application-models/application-component-configuration-fa.md index 4cc1c9ad6831f0e54ae4c70f4f7229a7abc7c62f..336ad698d0f2298045b00fe0af1563574bccfd24 100644 --- a/en/application-dev/application-models/application-component-configuration-fa.md +++ b/en/application-dev/application-models/application-component-configuration-fa.md @@ -22,7 +22,7 @@ When developing an application, you may need to configure certain tags to identi "actions": ["action.system.home"] } ] - // ... + ... } ``` diff --git a/en/application-dev/application-models/application-component-configuration-stage.md b/en/application-dev/application-models/application-component-configuration-stage.md index bcf9b095464ba0110c35be9cfef44b078a091ffb..b50d40b4a694ecdf55338d249a20ff458d36ba20 100644 --- a/en/application-dev/application-models/application-component-configuration-stage.md +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -1,10 +1,12 @@ # Application- or Component-Level Configuration (Stage Model) +When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. -When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. +Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). +The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and entry labels. When you touch one of them, the corresponding UIAbility page is displayed. - **Figure 1** Icons and labels +**Figure 1** Icons and labels ![application-component-configuration-stage](figures/application-component-configuration-stage.png) @@ -22,13 +24,13 @@ When developing an application, you may need to configure certain tags to identi The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. ```json - { - "app": { - "icon": "$media:app_icon", - "label": "$string:app_name" - // ... - } + { + "app": { + "icon": "$media:app_icon", + "label": "$string:app_name" + ... } + } ``` - **Configuring the entry icon and label** @@ -40,7 +42,7 @@ When developing an application, you may need to configure certain tags to identi ```json { "module": { - // ... + ... "abilities": [ { // The information starting with $ is the resource value. @@ -61,6 +63,35 @@ When developing an application, you may need to configure certain tags to identi } } ``` + OpenHarmony strictly controls applications without icons to prevent malicious applications from deliberately configuring no icon to block uninstall attempts. + + To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). The rules for displaying the entry icon and entry label are as follows: + + 1. The HAP file contains UIAbility configuration. + * An entry icon is set in the **abilities** field of the **module.json5** file. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon configured for the UIAbility as the entry icon and displays it on the home screen. Touching this icon will direct the user to the home page of the UIAbility. + * The system uses the label configured for the UIAbility as the entry label and displays it on the home screen. If no label is configured, the system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + * No entry icon is set in the **abilities** field of the **module.json5** file. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. + * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + + 2. The HAP file does not contain UIAbility configuration. + * The application does not have the privilege to hide its icon from the home screen. + * The system uses the icon specified in the **app.json5** file as the entry icon and displays it on the home screen. Touching this icon will direct the user to the application details page, as shown below. + * The system uses the label specified in the **app.json5** file as the entry label and displays it on the home screen. + * The application has the privilege to hide its icon from the home screen. + * The application information is not returned when the home screen queries the information, and the entry icon and label of the application are not displayed on the home screen. + + **Figure 2** Application details page + + ![Application details page](figures/application_details.jpg) + - **Configuring application version declaration** To declare the application version, configure the **versionCode** and **versionName** fields in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. **versionCode** specifies the version number of the application. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version. **versionName** provides the text description of the version number. diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index e009f360037580700cc6fe2c74a80db3f899a504..2063eee286c25e360a1700d3e1771d865b875f1c 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -1,19 +1,16 @@ # Context (Stage Model) - ## Overview [Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. - The figure below illustrates the inheritance relationship of contexts. - ![context-inheritance](figures/context-inheritance.png) - + - The figure below illustrates the holding relationship of contexts. - ![context-holding](figures/context-holding.png) -- The following describes the information provided by different contexts. +The following describes the information provided by different contexts. - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more. ```ts @@ -21,7 +18,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let uiAbilityContext = this.context; - // ... + ... } } ``` @@ -36,7 +33,7 @@ export default class MyService extends ServiceExtensionAbility { onCreate(want) { let serviceExtensionContext = this.context; - // ... + ... } } ``` @@ -47,7 +44,7 @@ export default class MyAbilityStage extends AbilityStage { onCreate() { let abilityStageContext = this.context; - // ... + ... } } ``` @@ -58,7 +55,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let applicationContext = this.context.getApplicationContext(); - // ... + ... } } ``` @@ -85,12 +82,12 @@ The following table describes the application development paths obtained from co | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. | -| cacheDir | string | Yes| No| Path for storing the application's cache files, that is, cache directory of the application on the internal storage.
It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| -| filesDir | string | Yes | No | Path for storing the application's common files, that is, file directory of the application on the internal storage.
Files in this directory may be synchronized to other directories during application migration or backup.| -| preferencesDir | string | Yes | Yes | Path for storing the application's preference files, that is, preferences directory of the application. | -| tempDir | string | Yes | No | Path for storing the application's temporary files.
Files in this directory are deleted after the application is uninstalled.| +| cacheDir | string | Yes| No| Path for storing the cache files, that is, cache directory of the application on the internal storage.
It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| +| filesDir | string | Yes | No | Path for storing the common files, that is, file directory of the application on the internal storage.
Files in this directory may be synchronized to other directories during application migration or backup.| +| preferencesDir | string | Yes | Yes | Path for storing the preference files, that is, preferences directory of the application. | +| tempDir | string | Yes | No | Path for storing the temporary files.
Files in this directory are deleted after the application is uninstalled.| | databaseDir | string | Yes | No | Path for storing the application's database, that is, storage directory of the local database. | -| distributedFilesDir | string | Yes| No| Path for storing the application's distributed files.| +| distributedFilesDir | string | Yes| No| Path for storing the distributed files.| The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below. @@ -135,7 +132,7 @@ export default class EntryAbility extends UIAbility { let bundleCodeDir = this.context.bundleCodeDir; let distributedFilesDir = this.context.distributedFilesDir; let preferencesDir = this.context.preferencesDir; - // ... + ... } } ``` @@ -148,7 +145,7 @@ export default class EntryAbility extends UIAbility { Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in a directory with the device-level encryption (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in a directory with the user-level encryption (EL2). -In practice, you need to select a proper encrypted level based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security. +In practice, you need to select a proper encryption level based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security. > **NOTE** > @@ -187,13 +184,13 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ > **NOTE** > > To obtain the context of another application: - > + > > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - > + > > - This is a system API and cannot be called by third-party applications. For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -202,7 +199,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ let bundleName2 = 'com.example.application'; let context2 = this.context.createBundleContext(bundleName2); let label2 = context2.applicationInfo.label; - // ... + ... } } ``` @@ -224,7 +221,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ let bundleName2 = 'com.example.application'; let moduleName2 = 'module1'; let context2 = this.context.createModuleContext(bundleName2, moduleName2); - // ... + ... } } ``` @@ -238,7 +235,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../ onCreate(want, launchParam) { let moduleName2 = 'module1'; let context2 = this.context.createModuleContext(moduleName2); - // ... + ... } } ``` @@ -266,53 +263,53 @@ export default class EntryAbility extends UIAbility { let abilityLifecycleCallback = { // Called when a UIAbility is created. onAbilityCreate(uiAbility) { - console.log(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when a window is created. onWindowStageCreate(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window becomes active. onWindowStageActive(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window becomes inactive. onWindowStageInactive(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the window is destroyed. onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) { - console.log(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); - console.log(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); + console.info(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`); }, // Called when the UIAbility is destroyed. onAbilityDestroy(uiAbility) { - console.log(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when the UIAbility is switched from the background to the foreground. onAbilityForeground(uiAbility) { - console.log(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when the UIAbility is switched from the foreground to the background. onAbilityBackground(uiAbility) { - console.log(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); }, // Called when UIAbility is continued on another device. onAbilityContinue(uiAbility) { - console.log(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); + console.info(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`); } } // Obtain the application context. let applicationContext = this.context.getApplicationContext(); // Register the application lifecycle callback. this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); - console.log(TAG, `register callback number: ${this.lifecycleId}`); + console.info(TAG, `register callback number: ${this.lifecycleId}`); } - // ... + ... onDestroy() { // Obtain the application context. diff --git a/en/application-dev/application-models/application-model-description.md b/en/application-dev/application-models/application-model-description.md index 0cdfa7323c6ef367a47a44e2c30104d3201ca159..20fa9019d10c8d242e34b309debec78e722e6c27 100644 --- a/en/application-dev/application-models/application-model-description.md +++ b/en/application-dev/application-models/application-model-description.md @@ -12,10 +12,9 @@ Along its evolution, OpenHarmony has provided two application models: The stage model is designed based on the following considerations, which make it become the recommended model: 1. **Designed for complex applications** - - In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory. - The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale. - + 2. **Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level** The stage model decouples application components from User Interfaces (UIs). @@ -38,7 +37,7 @@ The stage model is designed based on the following considerations, which make it The stage model redefines the boundary of application capabilities to well balance application capabilities and system management costs. - - Diverse application components (such as widgets and input methods) for specific scenarios. + - Diverse application components (such as service widgets and input methods) for specific scenarios. - Standardized background process management. To deliver a better user experience, the stage model manages background application processes in a more orderly manner. Applications cannot reside in the background randomly, and their background behavior is strictly managed to minimize malicious behavior. @@ -52,8 +51,8 @@ The table below describes their differences in detail. | Item| FA model| Stage model| | -------- | -------- | -------- | -| **Application component**| 1. Component classification
![fa-model-component](figures/fa-model-component.png)
- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).
- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).
- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).
2. Development mode
Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion. | 1. Component classification
![stage-model-component](figures/stage-model-component.png)
- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).
- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).
2. Development mode
The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion. | -| **Process model**| There are two types of processes:
1. Main process
2. Rendering process
For details, see [Process Model (FA Model)](process-model-fa.md).| There are three types of processes:
1. Main process
2. ExtensionAbility process
3. Rendering process
For details, see [Process Model (Stage Model)](process-model-stage.md).| -| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model (FA Model)](thread-model-fa.md).| 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model (Stage Model)](thread-model-stage.md).| +| **Application component**| 1. Component classification
![fa-model-component](figures/fa-model-component.png)
- PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md).
- ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).
- DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md).
2. Development mode
Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion.| 1. Component classification
![stage-model-component](figures/stage-model-component.png)
- UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md).
- ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md).
2. Development mode
The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion.| +| **Process model**| There are two types of processes:
1. Main process
2. Rendering process
For details, see [Process Model Overview (FA Model)](process-model-fa.md). | There are three types of processes:
1. Main process
2. ExtensionAbility process
3. Rendering process
For details, see [Process Model Overview (Stage Model)](process-model-stage.md). | +| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model Overview (FA Model)](thread-model-fa.md). | 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model Overview (Stage Model)](thread-model-stage.md). | | **Mission management model**| - A mission is created for each PageAbility component instance.
- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.
- PageAbility components do not form a stack structure.
For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance.
- Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions.
- UIAbility components do not form a stack structure.
For details, see [Mission Management Scenarios](mission-management-overview.md).| | **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information.
For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information.
For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).| 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 new file mode 100644 index 0000000000000000000000000000000000000000..842c418ba64a8fd3b01b8d981c209ad1c7d769cf --- /dev/null +++ b/en/application-dev/application-models/arkts-ui-widget-event-call.md @@ -0,0 +1,89 @@ +# Launching a UIAbility in the Background Through the call Event + + +There may be cases you want to provide in a widget access to features available in your application when it is 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. + + +Generally, buttons are used to trigger the **call** event. Below is an example. + + +- In this example, two buttons are laid out on the widget page. When one button is clicked, the **postCardAction** API is called to send a **call** event to the target UIAbility. Note that the **method** parameter in the API indicates the method to call in the target UIAbility. It is mandatory and of the string type. + + ```ts + @Entry + @Component + struct WidgetCard { + build() { + Column() { + Button ('Feature A') + .margin('20%') + .onClick(() => { + console.info('call EntryAbility funA'); + postCardAction(this, { + 'action': 'call', + 'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed. + 'params': { + 'method': 'funA' // Set the name of the method to call in the EntryAbility. + } + }); + }) + + Button ('Feature B') + .margin('20%') + .onClick(() => { + console.info('call EntryAbility funB'); + postCardAction(this, { + 'action': 'call', + 'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed. + 'params': { + 'method': 'funB', // Set the name of the method to call in the EntryAbility. + 'num': 1 // Set other parameters to be transferred. + } + }); + }) + } + .width('100%') + .height('100%') + } + } + ``` + +- 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. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + function FunACall(data) { + // Obtain all parameters transferred in the call event. + console.log('FunACall param:' + JSON.stringify(data.readString())); + return null; + } + + function FunBCall(data) { + console.log('FunACall param:' + JSON.stringify(data.readString())); + return null; + } + + export default class CameraAbility extends UIAbility { + // If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the call event is received. + onCreate(want, launchParam) { + try { + // Listen for the method required by the call event. + this.callee.on('funA', FunACall); + this.callee.on('funB', FunBCall); + } catch (error) { + console.log('register failed with error. Cause: ' + JSON.stringify(error)); + } + } + + // Deregister the listener when the process exits. + onDestroy() { + try { + this.callee.off('funA'); + this.callee.off('funB'); + } catch (error) { + console.log('register failed with error. Cause: ' + JSON.stringify(error)); + } + } + }; + ``` 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 861f5ca66eea9a06ee50c7b1448e1f6ed040c01a..be7761d8d78da5102afadd2c37043c228dfcd53e 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,7 +1,7 @@ -# Updating Widget Content Through FormExtensionAbility +# Updating Widget Content Through the message Event -On the widget page, the **postCardAction** API can be used to trigger a message event to the FormExtensionAbility, which then updates the widget content. The following is an example of this widget update mode. +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. @@ -57,10 +57,10 @@ On the widget page, the **postCardAction** API can be used to trigger a message }) } - // ... + ... } ``` The figure below shows the effect. - + ![WidgetUpdatePage](figures/WidgetUpdatePage.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 fbc77b97a27b52b0f7b2a3b0cebc5b5cb5940f72..ed029fc3017d00a7d4c2cf14e1b905139bd7eb49 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,40 +1,31 @@ # Widget Event Capability Overview - The ArkTS widget provides the **postCardAction()** API for interaction between the widget internal and the provider application. Currently, this API supports the router, message, and call events and can be called only in the widget. - ![WidgetPostCardAction](figures/WidgetPostCardAction.png) +**Definition**: postCardAction(component: Object, action: Object): void -Definition: postCardAction(component: Object, action: Object): void - - -Parameters: - +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | component | Object | Yes| Instance of the current custom component. Generally, **this** is transferred.| | action | Object | Yes| Action description. For details, see the following table.| +**Description of the action parameter** -Description of the action parameter - - -| **Key** | **Value** | Description| +| Key | Value | Description| | -------- | -------- | -------- | -| "action" | string | Action type.
- **"router"**: application redirection. If this type of action is triggered, the corresponding UIAbility is displayed. Only the UIAbility of the current application can be displayed.
- **"message"**: custom message. If this type of action is triggered, the [onFormEvent()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) lifecycle callback of the provider FormExtensionAbility is called.
- **"call"**: application startup in the background. If this type of action is triggered, the corresponding UIAbility is started but does not run in the foreground. The target application must have the permission to run in the background ([ohos.permission.KEEP_BACKGROUND_RUNNING](../security/permission-list.md#ohospermissionkeep_background_running)).| +| "action" | string | Action type.
- **"router"**: redirection to the specified UIAbility of the widget provider.
- **"message"**: custom message. If this type of action is triggered, the [onFormEvent()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) lifecycle callback of the provider FormExtensionAbility is called.
- **"call"**: launch of the widget provider in the background. If this type of action is triggered, the specified UIAbility of the widget provider is started in the background, but not displayed in the foreground. This action type requires that the widget provider should have the [ohos.permission.KEEP_BACKGROUND_RUNNING](../security/permission-list.md#ohospermissionkeep_background_running) permission.| | "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.| +| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. For the **"call"** action type, the **method** parameter must be set and its value type must be string. This parameter is mandatory.| Sample code of the **postCardAction()** API: - - ```typescript Button ('Jump') .width('40%') @@ -45,18 +36,26 @@ Button ('Jump') 'bundleName': 'com.example.myapplication', 'abilityName': 'EntryAbility', 'params': { - 'message': 'testForRouter' // Customize the message to be sent. + 'message': 'testForRouter' // Customize the message to send. } }); }) -``` - - -The following are typical widget development scenarios that can be implemented through widget events: +Button ('Start in Background') + .width('40%') + .height('20%') + .onClick(() => { + postCardAction(this, { + 'action': 'call', + 'bundleName': 'com.example.myapplication', + 'abilityName': 'EntryAbility', + 'params': { + 'method': 'fun', // Set the name of the method to call. It is mandatory. + 'message': 'testForcall' // Customize the message to send. + } + }); + }) +``` -- [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md) - -- [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md) -- [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) +Read on to learn the typical widget development scenarios that can be implemented through widget events. 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 371cbc6b2729a7985ed2fd183297ed771fddb11d..733ff7f59b57ec4295fa21cb4d83ae8a5b2b8eb4 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 @@ -1,8 +1,6 @@ -# Redirecting to a Specified Page Through the Router Event - - -The **router** capability of the **postCardAction** API can be used in a widget to quickly start the widget provider application. An application can provide different buttons through the widget so that users can jump to different pages at the touch of a button. For example, a camera widget provides the buttons that direct the user to respective pages, such as the page for taking a photo and the page for recording a video. +# Redirecting to a UIAbility Through the router Event +The **router** capability of the **postCardAction** API can be used in a widget to quickly start a specific UIAbility of the widget provider. By leveraging this capability, an application can provide in the widget multiple buttons, each of which targets a different target UIAbility. For example, a camera widget can provide the buttons that redirect the user to the UIAbility for taking a photo and the UIAbility for recording a video. ![WidgerCameraCard](figures/WidgerCameraCard.png) 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 0d6cb33a3749c81b6b41dd4904ba64c89a7942ae..a9e0ca1544a3f22e8c6460c992459a182bf142b0 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 @@ -1,10 +1,11 @@ -# Updating Widget Content Through UIAbility +# Updating Widget Content Through the router or call Event -On the widget page, the **postCardAction** API can be used to trigger a router or call event to start the UIAbility, which then updates the widget content. The following is an example of this widget update mode. +On the widget page, the **postCardAction** API can be used to trigger a router or call event to start a UIAbility, which then updates the widget content. The following is an example of this widget update mode. +## 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 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 **router** event to the FormExtensionAbility. ```ts let storage = new LocalStorage(); @@ -84,3 +85,104 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ... } ``` + +## Updating Widget Content Through the call Event + +- When using the **call** event of the **postCardAction** API, the value of **formId** must be updated in the **onAddForm** callback of the FormExtensionAbility. + + ```ts + import formBindingData from '@ohos.app.form.formBindingData'; + import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + + export default class EntryFormAbility extends FormExtensionAbility { + onAddForm(want) { + let formId = want.parameters["ohos.extra.param.key.form_identity"]; + let dataObj1 = { + "formId": formId + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } + + ... + }; + ``` + +- 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. + + ```ts + let storage = new LocalStorage(); + @Entry(storage) + @Component + struct WidgetCard { + @LocalStorageProp('detail') detail: string = 'init'; + @LocalStorageProp('formId') formId: string = '0'; + + build() { + Column() { + Button ('Start in Background') + .margin('20%') + .onClick(() => { + console.info('postCardAction to EntryAbility'); + postCardAction(this, { + 'action': 'call', + 'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed. + 'params': { + 'method': 'funA', + 'formId': this.formId, + 'detail': 'CallFromCard' + } + }); + }) + Text(`${this.detail}`).margin('20%') + } + .width('100%') + .height('100%') + } + } + ``` + +- Listen for the method required by the **call** event in the **onCreate** callback of the UIAbility, and then call the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) API in the corresponding method to update the widget. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import formBindingData from '@ohos.app.form.formBindingData'; + import formProvider from '@ohos.app.form.formProvider'; + import formInfo from '@ohos.app.form.formInfo'; + + const MSG_SEND_METHOD: string = 'funA' + + // After the call event is received, the method listened for by the callee is triggered. + function FunACall(data) { + // Obtain all parameters transferred in the call event. + let params = JSON.parse(data.readString()) + if (params.formId !== undefined) { + let curFormId = params.formId; + let message = params.detail; + console.info(`UpdateForm formId: ${curFormId}, message: ${message}`); + let formData = { + "detail": message + }; + 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)); + }) + } + return null; + } + export default class EntryAbility extends UIAbility { + // If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the call event is received. + onCreate(want, launchParam) { + console.info('Want:' + JSON.stringify(want)); + try { + // Listen for the method required by the call event. + this.callee.on(MSG_SEND_METHOD, FunACall); + } catch (error) { + console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + } + ... + } + ``` diff --git a/en/application-dev/application-models/arkts-ui-widget-image-update.md b/en/application-dev/application-models/arkts-ui-widget-image-update.md index 4862fbf747c0275d179eb4a2f988280379f2d262..dfe6dbf0e9249c66c3fb1d0723f1c7b296443381 100644 --- a/en/application-dev/application-models/arkts-ui-widget-image-update.md +++ b/en/application-dev/application-models/arkts-ui-widget-image-update.md @@ -1,10 +1,10 @@ # Updating Local and Online Images in the Widget -Generally, local images or online images downloaded from the network need to be displayed on a widget. To obtain local and online images, use the FormExtensionAbility. The following exemplifies how to show local and online images on a widget. +Typically, a widget includes local images or online images downloaded from the network. To obtain local and online images, use the FormExtensionAbility. The following exemplifies how to show local and online images on a widget. -1. Internet access is required for downloading online images. Therefore, you need to apply for the **ohos.permission.INTERNET** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md). +1. For the widget to download online images, declare the **ohos.permission.INTERNET** permission for the widget. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md). 2. Update local files in the **onAddForm** lifecycle callback of the EntryFormAbility. @@ -44,7 +44,7 @@ Generally, local images or online images downloaded from the network need to be } ``` -3. Update online files in the onFormEvent lifecycle callback of the EntryFormAbility. +3. Update online images in the **onFormEvent** lifecycle callback of the EntryFormAbility. ```ts import formBindingData from '@ohos.app.form.formBindingData'; @@ -60,8 +60,8 @@ Generally, local images or online images downloaded from the network need to be 'text': 'Updating...' }) formProvider.updateForm(formId, formInfo) - // Note: The FormExtensionAbility is started when the lifecycle callback is triggered. It can run in the background for only 5 seconds. - // When possible, limit the size of the image to download. If an image cannot be downloaded within 5 seconds, it cannot be updated to the widget page. + // Note: After being started with the triggering of the lifecycle callback, the FormExtensionAbility can run in the background for only 5 seconds. + // When possible, limit the size of the image to download. If an image cannot be downloaded within 5 seconds, it will not be updated to the widget page. let netFile = 'https://xxxx/xxxx.png'; // Specify the URL of the image to download. let tempDir = this.context.getApplicationContext().tempDir; let fileName = 'file' + Date.now(); @@ -161,6 +161,6 @@ Generally, local images or online images downloaded from the network need to be ``` > **NOTE** -> - The **\** component displays images in the remote memory based on the **memory://** identifier in the input parameter (**memory://fileName**). The **fileName** value must be consistent with the key in the object (**'formImages': {key: fd}**) passed by the EntryFormAbility. +> - The **\** component displays images in the remote memory based on the **memory://** identifier in the input parameter (**memory://fileName**). The value of **fileName** must be consistent with the key in the object (**'formImages': {key: fd}**) passed by the EntryFormAbility. > -> - The **\** component determines whether to update the image based on whether the input parameter is changed. Therefore, the value of **imgName** passed by the EntryFormAbility each time must be different. If the two values of **imgName** passed consecutively are identical, the image is not updated. +> - The **\** component determines whether to update the image by comparing the values of **imgName** consecutively passed by the EntryFormAbility. It updates the image only when the values are different. 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 4cb68536312e26e0f7c98546839134c0ab435a8c..fb25fd362f67646d65853b870a6a9cb518c4d760 100644 --- a/en/application-dev/application-models/arkts-ui-widget-lifecycle.md +++ b/en/application-dev/application-models/arkts-ui-widget-lifecycle.md @@ -92,4 +92,5 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( > **NOTE** -> The FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. The FormExtensionAbility persists for 5 seconds after the lifecycle callback is completed and will exit if no new lifecycle callback is invoked during this time frame. For the service logic that may take more than 5 seconds to complete, it is recommended that you [start the application](arkts-ui-widget-event-uiability.md). After the processing is complete, use the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) to notify the widget of the update. +> +> The FormExtensionAbility cannot reside in the background. It persists for 5 seconds after the lifecycle callback is completed and exist if no new lifecycle callback is invoked during this time frame. This means that continuous tasks cannot be processed in the widget lifecycle callbacks. For the service logic that may take more than 5 seconds to complete, it is recommended that you [start the application](arkts-ui-widget-event-uiability.md) for processing. After the processing is complete, use [updateForm()](../reference/apis/js-apis-app-form-formProvider.md#updateform) to notify the widget of the update. 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 5084b7ea5045002759ca57f10c055ef5623eb7d0..b9a411426db84a4c1af12e70eab956adc8f25806 100644 --- a/en/application-dev/application-models/arkts-ui-widget-modules.md +++ b/en/application-dev/application-models/arkts-ui-widget-modules.md @@ -1,7 +1,7 @@ # ArkTS Widget Related Modules +**Figure 1** ArkTS widget related modules - **Figure 1** ArkTS widget related modules ![WidgetModules](figures/WidgetModules.png) @@ -15,10 +15,10 @@ - [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. - - [ArkTS widget capabilities](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): lists the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets. +- [Page layout (Card.ets)](arkts-ui-widget-page-overview.md): provides APIs for a declarative paradigm UI. + - [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. - [Widget configuration](arkts-ui-widget-configuration.md): includes FormExtensionAbility configuration and widget configuration. - - Configure FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). + - Configure the FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). - Configure the widget configuration information (**WidgetCard.ets**) in the [form_config.json](arkts-ui-widget-configuration.md) file in **resources/base/profile**. diff --git a/en/application-dev/application-models/arkts-ui-widget-page-animation.md b/en/application-dev/application-models/arkts-ui-widget-page-animation.md index 9a940aeecb62682a185ba8c0529adc38017c8e2d..0cb8e356c61155d367e55c0f39bbf491d03e2e12 100644 --- a/en/application-dev/application-models/arkts-ui-widget-page-animation.md +++ b/en/application-dev/application-models/arkts-ui-widget-page-animation.md @@ -1,10 +1,10 @@ # Using Animations in the Widget -To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [attribute animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Note the following restrictions when using the animations in ArkTS widgets. +To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [attribute animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Just note the following restrictions when using the animations in ArkTS widgets. - **Table 1** Restrictions on animation parameters +**Table 1** Restrictions on animation parameters | Name| Description| Description| | -------- | -------- | -------- | @@ -13,14 +13,10 @@ To make your ArkTS widget more engaging, you can apply animations to it, includi | delay | Animation delay duration.| Do not set this parameter in the widget. Use the default value 0.| | iterations | Number of times that the animation is played.| Do not set this parameter in the widget. Use the default value 1.| - The following sample code implements the animation effect of button rotation: - ![WidgetAnimation](figures/WidgetAnimation.gif) - - ```ts @Entry @Component diff --git a/en/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md b/en/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md index 49523d60af886db40b55fc90d80c9bd5027cade8..a55cb9cd17cda67cc2989e5916db19c5cf36cc47 100644 --- a/en/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md +++ b/en/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md @@ -1,9 +1,9 @@ # Applying Custom Drawing in the Widget - You can apply custom drawing in your ArkTS widget to create a more vibrant experience. Use the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to create a canvas on the widget, and then use the [CanvasRenderingContext2D](../reference/arkui-ts/ts-canvasrenderingcontext2d.md) object to draw custom graphics on the canvas. The following code shows how to draw a smiling face in the center of the canvas. +You can apply custom drawing in your ArkTS widget to create a more vibrant experience. Use the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to create a canvas on the widget, and then use the [CanvasRenderingContext2D](../reference/arkui-ts/ts-canvasrenderingcontext2d.md) object to draw custom graphics on the canvas. The following code snippet draws a smiling face in the center of a canvas. -```typescript +```ts @Entry @Component struct Card { @@ -30,41 +30,41 @@ struct Card { this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight); // Draw a red circle in the center of the canvas. this.context.beginPath(); - let radius = this.context.width / 3 - let circleX = this.context.width / 2 - let circleY = this.context.height / 2 + let radius = this.context.width / 3; + let circleX = this.context.width / 2; + let circleY = this.context.height / 2; this.context.moveTo(circleX - radius, circleY); this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true); this.context.closePath(); this.context.fillStyle = 'red'; this.context.fill(); // Draw the left eye of the smiling face. - let leftR = radius / 4 - let leftX = circleX - (radius / 2) - let leftY = circleY - (radius / 3.5) + let leftR = radius / 4; + let leftX = circleX - (radius / 2); + let leftY = circleY - (radius / 3.5); this.context.beginPath(); this.context.arc(leftX, leftY, leftR, 0, Math.PI, true); - this.context.strokeStyle = '#ffff00' - this.context.lineWidth = 10 - this.context.stroke() + this.context.strokeStyle = '#ffff00'; + this.context.lineWidth = 10; + this.context.stroke(); // Draw the right eye of the smiling face. - let rightR = radius / 4 - let rightX = circleX + (radius / 2) - let rightY = circleY - (radius / 3.5) + let rightR = radius / 4; + let rightX = circleX + (radius / 2); + let rightY = circleY - (radius / 3.5); this.context.beginPath(); this.context.arc(rightX, rightY, rightR, 0, Math.PI, true); - this.context.strokeStyle = '#ffff00' - this.context.lineWidth = 10 - this.context.stroke() + this.context.strokeStyle = '#ffff00'; + this.context.lineWidth = 10; + this.context.stroke(); // Draw the mouth of the smiling face. - let mouthR = radius / 2.5 - let mouthX = circleX - let mouthY = circleY + (radius / 3) + let mouthR = radius / 2.5; + let mouthX = circleX; + let mouthY = circleY + (radius / 3); this.context.beginPath(); this.context.arc(mouthX, mouthY, mouthR, Math.PI, 0, true); - this.context.strokeStyle = '#ffff00' - this.context.lineWidth = 10 - this.context.stroke() + this.context.strokeStyle = '#ffff00'; + this.context.lineWidth = 10; + this.context.stroke(); }) } }.height('100%').width('100%') @@ -72,8 +72,6 @@ struct Card { } ``` - The figure below shows the effect. - -![WidgetCanvasDemo](figures/WidgetCanvasDemo.jpeg) +![WidgetCanvasDemo](figures/WidgetCanvasDemo.png) \ No newline at end of file diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-status.md b/en/application-dev/application-models/arkts-ui-widget-update-by-status.md index 8952b8dff4ecdd3acad6b1a65513d8e529c4dc70..b27958c66d3e174a66c80c90e46cdd71f5ecf668 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-status.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-status.md @@ -1,7 +1,7 @@ # Updating Widget Content by State -Multiple widgets of the same application can be configured to implement different features. For example, two weather widgets can be added to the home screen: one for displaying the weather of London, and the other Beijing. The widget is set to be updated at 07:00 every morning. It needs to detect the configured city, and then updates the city-specific weather information. The following example describes how to dynamically update the widget content based on the state. +There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented. In the following example, two weather widgets are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets. - Widget configuration file: Configure the widget to be updated at 07:00 every morning. @@ -74,7 +74,7 @@ Multiple widgets of the same application can be configured to implement differen } Row() {// Content that is updated only in state A - Text('State A: ') + Text ('State A:') Text(this.textA) } @@ -167,4 +167,5 @@ Multiple widgets of the same application can be configured to implement differen > **NOTE** +> > When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis/js-apis-app-form-formInfo.md#formparam) be used to determine whether the currently added widget is a normal one in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion. 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 5b27a636f83f144110c5533a3d43baf0087c3716..2c2643c802aff436656f5855d67c00e1a3c38dcd 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 @@ -5,7 +5,7 @@ Before configuring a widget to update periodically, enable the periodic update f The widget framework provides the following modes of updating widgets periodically: -- Set the update interval: The widget will be updated at the specified interval. You can specify the interval by setting the [updateDuration](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update once an hour. +- Set the update interval: The widget will be updated at the specified interval by calling [onUpdateForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onupdateform). You can specify the interval by setting the [updateDuration](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update once an hour. > **NOTE** > diff --git a/en/application-dev/application-models/common-event-overview.md b/en/application-dev/application-models/common-event-overview.md index e8be9abaa3015a5512c47af55d2f364be0de79ad..3f532865e686592282b9080f234c088ee24a64f8 100644 --- a/en/application-dev/application-models/common-event-overview.md +++ b/en/application-dev/application-models/common-event-overview.md @@ -7,8 +7,7 @@ OpenHarmony provides Common Event Service (CES) for applications to subscribe to Common events are classified into system common events and custom common events. -- System common events: defined in CES. Only system applications and system services can publish system common events, such as HAP installation, update, and uninstall. For details about the supported system common events, see [Support](../reference/apis/js-apis-commonEventManager.md#support). - +- System common events: defined in CES. Currently, only system applications and system services can publish system common events, such as HAP installation, update, and uninstall. For details about the supported system common events, see [System Common Events](../reference/apis/commonEventManager-definitions.md). - Custom common events: customized by applications to implement cross-process event communication. @@ -16,9 +15,7 @@ Common events are also classified into unordered, ordered, and sticky common eve - Unordered common events: common events that CES forwards regardless of whether subscribers receive the events and when they subscribe to the events. - -- Ordered common events: common events that CES forwards based on the subscriber priority. CES forwards common events to the subscriber with lower priority only after receiving a reply from the previous subscriber with higher priority. Subscribers with the same priority receive common events in a random order. - +- Ordered common events: common events that CES forwards based on the subscriber priority. CES preferentially forwards an ordered common event to the subscriber with higher priority, waits until the subscriber receives the event, and then forwards the events to the subscriber with lower priority. Subscribers with the same priority receive common events in a random order. - Sticky common events: common events that can be sent to a subscriber before or after they initiate a subscription. Only system applications and system services can send sticky common events, which remain in the system after being sent. The sends must first request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). diff --git a/en/application-dev/application-models/common-event-static-subscription.md b/en/application-dev/application-models/common-event-static-subscription.md index a545f6464b052cb20bd931b21820d623ad13f9c6..86a3b593d63e49c4b3bd8f66f49b3e39d156d535 100644 --- a/en/application-dev/application-models/common-event-static-subscription.md +++ b/en/application-dev/application-models/common-event-static-subscription.md @@ -2,38 +2,46 @@ ## When to Use -A static subscriber is started once it receives a target event published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. Note that this subscribing mode has negative impact on system power consumption. Therefore, exercise caution when using this mode. +A static subscriber is started once it receives a target event published by the system or application. At the same time, the [onReceiveEvent()](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback is triggered. + +You can implement the service logic in the [onReceiveEvent()](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. + +Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md). + +> **NOTE** +> +> The static subscription mode has negative impact on system power consumption. Therefore, exercise caution when using this mode. ## How to Develop -1. Declaring a Static Subscriber +1. Declaring a static subscriber. - To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows: + To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. + + You can implement service logic in the **onReceiveEvent()** callback. ```ts import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' export default class StaticSubscriber extends StaticSubscriberExtensionAbility { - onReceiveEvent(event) { - console.log('onReceiveEvent, event:' + event.event); - } + onReceiveEvent(event) { + console.info('onReceiveEvent, event: ' + event.event); + } } ``` - You can implement service logic in the **onReceiveEvent** callback. - -2. Project Configuration for a Static Subscriber +2. Configure static subscriber settings. - After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows: + After writing the static subscriber code, configure the subscriber in the [module.json5](../quick-start/module-configuration-file.md) file. ```ts { "module": { - ...... + ... "extensionAbilities": [ { "name": "StaticSubscriber", - "srcEntry": "./ets/StaticSubscriber/StaticSubscriber.ts", + "srcEntry": "./ets/staticsubscriber/StaticSubscriber.ts", "description": "$string:StaticSubscriber_desc", "icon": "$media:icon", "label": "$string:StaticSubscriber_label", @@ -47,14 +55,14 @@ A static subscriber is started once it receives a target event published by the ] } ] - ...... + ... } } ``` - Pay attention to the following fields in the JSON file: + Some fields in the file are described as follows: - - **srcEntry**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2. + - **srcEntry **: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2. - **type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**. @@ -62,39 +70,49 @@ A static subscriber is started once it receives a target event published by the - **name**: name of the ExtensionAbility. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. - **resource**: path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**. - A level-2 configuration file pointed to by **metadata** must be in the following format: - ```ts - { - "commonEvents": [ - { - "name": "xxx", - "permission": "xxx", - "events":[ - "xxx" - ] - } - ] - } - ``` +3. Configure the level-2 configuration file to which the metadata points. - If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows: + ```json + { + "commonEvents": [ + { + "name": "xxx", + "permission": "xxx", + "events":[ + "xxx" + ] + } + ] + } + ``` - - **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**. + If the level-2 configuration file is not declared in this format, the file cannot be identified. Some fields in the file are described as follows: - - **permission**: permission required for the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published. + - **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**. + - **permission**: permission required for the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published. + - **events**: list of target events to subscribe to. - - **events**: list of target events to subscribe to. +4. Modify the [preset configuration file](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) of the device, that is, the **/system/etc/app/install_list_permission.json** file on the device. When the device is started, this file is read. During application installation, the common event type specified by **allowCommonEvent** in the file is authorized. The **install_list_permission.json** file contains the following fields: -3. Device System Configuration + - **bundleName**: bundle name of the application. + - **app_signature**: fingerprint information of the application. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install_list_capabilityjson). + - **allowCommonEvent**: type of common event that can be started by static broadcast. - In the device system configuration file **/etc/static_subscriber_config.json**, add the bundle name of the static subscriber. + > **NOTE** + > + > The **install_list_permissions.json** file is available only for preinstalled applications. - ```json - { - "xxx", - "ohos.extension.staticSubscriber", - "xxx" - } + ```json + [ + ... + { + "bundleName": "com.example.myapplication", // Bundle name of the application. + "app_signature": ["****"], // Fingerprint information of the application. + "allowCommonEvent": ["usual.event.A", "usual.event.B"], // Type of common event that can be started by static broadcast. + ] + } + ] ``` + \ No newline at end of file diff --git a/en/application-dev/application-models/common-event-subscription-overview.md b/en/application-dev/application-models/common-event-subscription-overview.md index 20064af92d3df2e6f7ab7d62c4f71f911848057a..262f30c87e6018fed4e417a196dcaeeb58e42ae2 100644 --- a/en/application-dev/application-models/common-event-subscription-overview.md +++ b/en/application-dev/application-models/common-event-subscription-overview.md @@ -1,7 +1,7 @@ # Common Event Subscription Overview -​The common event service provides two subscription modes: dynamic and static. The biggest difference between these two modes is that dynamic subscription requires the application to be running, while static subscription does not. +The common event service provides two subscription modes: dynamic and static. The biggest difference between these two modes is that dynamic subscription requires the application to be running, while static subscription does not. - In dynamic subscription mode, a subscriber subscribes to common events by calling an API during the running period. For details, see [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md). -- In static subscription mode, a subscriber subscribes to common events by configuring a declaration file and implementing a class that inherits from StaticSubscriberExtensionAbility. For details, see [Subscribing to Common Events in Static Mode](common-event-static-subscription.md). +- In static subscription mode, a subscriber subscribes to common events by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. For details, see [Subscribing to Common Events in Static Mode](common-event-static-subscription.md). diff --git a/en/application-dev/application-models/common-event-subscription.md b/en/application-dev/application-models/common-event-subscription.md index 031a9358101e6b1310c0dbeb9f0f7a4c416791e3..c3e3ebfa52415d5e0ebade26973f78a589fb348f 100644 --- a/en/application-dev/application-models/common-event-subscription.md +++ b/en/application-dev/application-models/common-event-subscription.md @@ -8,7 +8,7 @@ In dynamic subscription mode, an application subscribes to a common event when i ## Available APIs -For details about the APIs, see [API Reference](../reference/apis/js-apis-commonEvent.md#commoneventcreatesubscriber). +For details about the APIs, see [API Reference](../reference/apis/js-apis-commonEventManager.md#commoneventmanagersubscribe). | API| Description| | -------- | -------- | @@ -19,10 +19,10 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common ## How to Develop -1. Import the **commonEvent** module. +1. Import the **commonEventManager** module. ```ts - import commonEvent from '@ohos.commonEventManager'; + import commonEventManager from '@ohos.commonEventManager'; ``` 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo). @@ -32,7 +32,7 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common let subscriber = null; // Subscriber information. let subscribeInfo = { - events: ["usual.event.SCREEN_OFF"], // Subscribe to the common event screen-off. + events: ["usual.event.SCREEN_OFF"], // Subscribe to the common event screen-off. } ``` @@ -40,14 +40,14 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common ```ts // Callback for subscriber creation. - commonEvent.createSubscriber(subscribeInfo, (err, data) => { - if (err) { - console.error(`[CommonEvent] CreateSubscriberCallBack err=${JSON.stringify(err)}`); - } else { - console.info(`[CommonEvent] CreateSubscriber success`); - subscriber = data; - // Callback for common event subscription. - } + commonEventManager.createSubscriber(subscribeInfo, (err, data) => { + if (err) { + console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`); + return; + } + console.info('Succeeded in creating subscriber.'); + subscriber = data; + // Callback for common event subscription. }) ``` @@ -56,14 +56,13 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common ```ts // Callback for common event subscription. if (subscriber !== null) { - commonEvent.subscribe(subscriber, (err, data) => { - if (err) { - console.error(`[CommonEvent] SubscribeCallBack err=${JSON.stringify(err)}`); - } else { - console.info(`[CommonEvent] SubscribeCallBack data=${JSON.stringify(data)}`); - } - }) + commonEventManager.subscribe(subscriber, (err, data) => { + if (err) { + console.error(`Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`); + return; + } + }) } else { - console.error(`[CommonEvent] Need create subscriber`); + console.error(`Need create subscriber`); } ``` diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index 26b2446893aea096611f896e878ef15888830afa..bddf63dbc69ea243733e6f60f67f92a854833bf7 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -23,8 +23,8 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol - **Before starting a component of another application, verify the visible field of the target component.** - - If the **visible** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities). + - If the **exported** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details, see [Component exported Configuration](../quick-start/module-configuration-file.md#abilities). - **Before starting a component of a background application, verify the BACKGROUND permission.** - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. @@ -37,8 +37,8 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol > **NOTE** > > - Component startup control has been implemented since OpenHarmony v3.2 Release. -> -> - The new component startup rules are more strict than the original ones. You must be familiar with the new startup rules to prevent service exceptions. +> +> - The new component startup rules are more strict than the original ones. You must be familiar with the new startup rules to prevent service exceptions. ## Intra-Device Component Startup Rules diff --git a/en/application-dev/application-models/create-pageability.md b/en/application-dev/application-models/create-pageability.md index d33b7af946dd0e935a149ebb11ef1ecbedf05ca8..d0f308ebc08e035d5568ee0e127a9739e400d124 100644 --- a/en/application-dev/application-models/create-pageability.md +++ b/en/application-dev/application-models/create-pageability.md @@ -30,7 +30,7 @@ export default { ``` -After the PageAbility is created, its abilities-related configuration items are displayed in the **config.json** file. The following is an example **config.json** file of an ability named MainAbility: +After the PageAbility is created, its abilities-related configuration items are displayed in the **config.json** file. The following is an example **config.json** file of an ability named EntryAbility: ```json { @@ -48,13 +48,13 @@ After the PageAbility is created, its abilities-related configuration items are ], "orientation": "unspecified", "visible": true, - "srcPath": "MainAbility", - "name": ".MainAbility", + "srcPath": "EntryAbility", + "name": ".EntryAbility", "srcLanguage": "ets", "icon": "$media:icon", - "description": "$string:MainAbility_desc", + "description": "$string:EntryAbility_desc", "formsEnabled": false, - "label": "$string:MainAbility_label", + "label": "$string:EntryAbility_label", "type": "page", "launchType": "singleton" } diff --git a/en/application-dev/application-models/data-share-via-want.md b/en/application-dev/application-models/data-share-via-want.md index 05da4e529947cf62a98fa81a4b6ed4578c9e0346..28184edbc9304e7c6fbfbfe673cf1b8deca7d635 100644 --- a/en/application-dev/application-models/data-share-via-want.md +++ b/en/application-dev/application-models/data-share-via-want.md @@ -48,9 +48,9 @@ function implicitStartAbility() { } } context.startAbility(wantInfo).then(() => { - // ... + ... }).catch((err) => { - // ... + ... }) } ``` @@ -66,9 +66,8 @@ In the preceding code, under the custom field **parameters**, the following **ab - **ability.picker.fileSizes**: file size, in bytes. - **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping. -The following figure shows an example. - -![stage-want2](figures/stage-want2.png) +The following figure shows an example. +![](figures/ability-startup-with-implicit-want2.png) ## Shared Party @@ -77,17 +76,17 @@ To enable the shared party to identify the shared content, configure **skills** ```json { "module": { - // ... + ... "abilities": [ { - // ... + ... "skills": [ { - // ... + ... "actions": [ "action.system.home", "ohos.want.action.sendData" - // ... + ... ], "uris": [ { @@ -102,7 +101,7 @@ To enable the shared party to identify the shared content, configure **skills** } ``` -After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. The UIAbility of the shared party, after being started, can call [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to obtain the passed Want. +After the user selects an application, the Want nested in the **ability.want.params.INTENT** field is passed to that application. After the UIAbility of the application starts, the application obtains **want** information from [**onCreate()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [**onNewWant()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant). The following is an example of the Want obtained. You can use the FD of the shared file to perform required operations. diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md index b0d98063c24ae630d2e26b8067f6cddddfeff57b..454fc89d718fb4adfe84c0eab67ebc332117ed26 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -1,23 +1,28 @@ # Matching Rules of Explicit Want and Implicit Want -Both explicit Want and implicit Want can be used to match an ability to start based on certain rules. These rules determine how the parameters set in Want match the configuration file declared by the target ability. +Both explicit [Want](../reference/apis/js-apis-app-ability-want.md) and implicit [Want](../reference/apis/js-apis-app-ability-want.md) can be used to match an application component to start based on certain rules. These rules determine how the parameters set in [want](../reference/apis/js-apis-app-ability-want.md) match the configuration file declared by the target application component. ## Matching Rules of Explicit Want + +The table below describes the matching rules of explicit [Want](../reference/apis/js-apis-app-ability-want.md). + | Name| Type| Matching Item| Mandatory| Rule Description| | -------- | -------- | -------- | -------- | -------- | -| deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.| +| deviceId | string | Yes| No| If this field is unspecified, only application components on the local device are matched.| | bundleName | string | Yes| Yes| If **abilityName** is specified but **bundleName** is unspecified, the matching fails.| -| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first ability is matched by default.| +| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first application component is matched by default.| | abilityName | string | Yes| Yes| To use explicit Want, this field must be specified.| -| uri | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| type | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| action | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| -| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| uri | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| type | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| action | string | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| +| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| | flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| -| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target application component as a parameter.| + +## Matching Rules for Implicit Want -## Matching Rules of Implicit Want +The table below describes the matching rules of implicit [Want](../reference/apis/js-apis-app-ability-want.md). | Name | Type | Matching Item| Mandatory| Rule Description | | ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ | @@ -30,31 +35,32 @@ Both explicit Want and implicit Want can be used to match an ability to start ba | action | string | Yes | No | | | entities | Array<string> | Yes | No | | | flags | number | No | No | This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| -| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target ability as a parameter. | +| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target application component as a parameter. | - -## Interpretation of Implicit Want Matching Rules Get familiar with the following about implicit Want: + - The **want** parameter passed by the caller indicates the operation to be performed by the caller. It also provides data and application type restrictions. -- The **skills** field declares the capabilities of the target ability. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md). +- The **skills** field declares the capabilities of the target application component. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md). -The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the abilities one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application. +The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the application components one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application. ### Matching Rules of action in the want Parameter -The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities. +The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the application components. + +- If **action** in the passed **want** parameter is unspecified and **actions** under **skills** of an application component is unspecified, the matching fails. -- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. +- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an application component is unspecified, the matching fails. -- If **action** in the passed **want** parameter is unspecified but **actions** under **skills** of an ability is specified, the matching is successful. +- If **action** in the passed **want** parameter is unspecified but **actions** under **skills** of an application component is specified, the matching is successful. -- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified and contains **action** in the passed **want** parameter, the matching is successful. +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an application component is specified and contains **action** in the passed **want** parameter, the matching is successful. -- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified but does not contain **action** in the passed **want** parameter, the matching fails. +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an application component is specified but does not contain **action** in the passed **want** parameter, the matching fails. **Figure 1** Matching rules of action in the want parameter @@ -63,55 +69,56 @@ The system matches the **action** attribute in the **want** parameter passed by ### Matching Rules of entities in the want Parameter -The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities. +The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the application components. -- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an application component is specified, the matching is successful. -- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is unspecified, the matching is successful. +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an application component is unspecified, the matching is successful. -- If **entities** in the passed **want** parameter is specified but **entities** under **skills** of an ability is unspecified, the matching fails. +- If **entities** in the passed **want** parameter is specified but **entities** under **skills** of an application component is unspecified, the matching fails. -- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified and contains **entities** in the passed **want** parameter, the matching is successful. +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an application component is specified and contains **entities** in the passed **want** parameter, the matching is successful. -- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails. +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an application component is specified but does not contain **entities** in the passed **want** parameter, the matching fails. - **Figure 2** Matching rule of entities in the want parameter + **Figure 2** Matching rules of entities in the want parameter ![want-entities](figures/want-entities.png) ### Matching Rules of uri and type in the want Parameter -When the **uri** and **type** parameters are specified in the **want** parameter to initiate a component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the abilities one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. +When the **uri** and **type** parameters are specified in the **want** parameter to initiate an application component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the application components one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. There are four combinations of **uri** and **type** settings. The matching rules are as follows: - Neither **uri** or **type** is specified in the **want** parameter. - - If the **uris** array under **skills** of an ability is unspecified, the matching is successful. - - If the **uris** array under **skills** of an ability contains an URI element whose **scheme** and **type** are unspecified, the matching is successful. + - If the **uris** array under **skills** of an application component is unspecified, the matching is successful. + - If the **uris** array under **skills** of an application component contains an URI element whose **scheme** and **type** are unspecified, the matching is successful. - In other cases, the matching fails. - Only **uri** is specified in the **want** parameter. - - If the **uris** array under **skills** of an ability is unspecified, the matching fails. - - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and **type** is unspecified, the matching is successful. Otherwise, the matching fails. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an element whose [uri is matched](#matching-rules-of-uri) and **type** is unspecified, the matching is successful. Otherwise, the matching fails. - Only **type** is specified in the **want** parameter. - - If the **uris** array under **skills** of an ability is unspecified, the matching fails. - - If the **uris** array under **skills** of an ability contains an URI element whose **scheme** is unspecified and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an URI element whose **scheme** is unspecified and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. -- Both **uri** and **type** are specified in the **want** parameter, as shown in Figure 3. - - If the **uris** array under **skills** of an ability is unspecified, the matching fails. - - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. +- Both **uri** and **type** are specified in the **want** parameter, as shown below. + - If the **uris** array under **skills** of an application component is unspecified, the matching fails. + - If the **uris** array under **skills** of an application component contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. -Leftmost URI matching: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the **uris** array under **skills** of the ability, -the matching is successful only if the leftmost URI in the passed **want** parameter matches **scheme**, the combination of **scheme** and **host**, or the combination of **scheme**, **host**, and **port**. +Leftmost URI matching: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the **uris** array under **skills** of the application component, the matching is successful only if the leftmost URI in the passed **want** parameter matches **scheme**, the combination of **scheme** and **host**, or the combination of **scheme**, **host**, and **port**. **Figure 3** Matching rules when uri and type are specified in the want parameter - ![want-uri-type1](figures/want-uri-type1.png) +![want-uri-type1](figures/want-uri-type1.png) +To simplify the description: -To simplify the description, **uri** and **type** passed in the **want** parameter are called **w_uri** and **w_type**, respectively; the **uris** array under **skills** of an ability to match is called **s_uris**; each element in the array is called **s_uri**. Matching is performed from top to bottom. +- **uri** in the **want** parameter passed in by the caller is called **w_uri**; each element in the **uris** array under **skills** of the application component to match is called **s_uri**. +- **type** in the **want** parameter passed in by the caller is called **w_type**; the type in the **uris** array under **skills** of the application component to match is called **s_type**. **Figure 4** Matching rules of uri and type in the want parameter @@ -120,7 +127,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet ### Matching Rules of uri -To simplify the description, **uri** in the passed **want** parameter is called **w_uri**; **uri** under **skills** of an ability to match is called **s_uri**. The matching rules are as follows: +The rules are as follows: - If **scheme** of **s_uri** is unspecified and **w_uri** is unspecified, the matching is successful. Otherwise, the matching fails. @@ -138,18 +145,15 @@ To simplify the description, **uri** in the passed **want** parameter is called > **NOTE** > -> The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an ability are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions: -> -> - **Full path expression**: scheme://host:port/path -> -> - **Prefix expression**: scheme://host:port/pathStartWith -> -> - **Regular expression**: scheme://host:port/pathRegex +> The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an application component are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions: > > - **Prefix URI expression**: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the configuration file, the matching is successful if a URI prefixed with the configuration file is passed in. > * `scheme://` > * `scheme://host` > * `scheme://host:port` +> - **Full path expression**: `scheme://host:port/path` +> - **Prefix expression**: `scheme://host:port/pathStartWith` +> - **Regular expression**: `scheme://host:port/pathRegex` ### Matching Rules of type @@ -158,7 +162,7 @@ To simplify the description, **uri** in the passed **want** parameter is called > > The matching rules of **type** described in this section are based on the fact that **type** in the **want** parameter is specified. If **type** is unspecified, follow the [matching rules of uri and type in the want parameter](#matching-rules-of-uri-and-type-in-the-want-parameter). -To simplify the description, **uri** in the passed **want** parameter is called **w_type**, and **type** of **uris** under **skills** of an ability to match is called **s_type**. The matching rules are as follows: +The matching rules are as follows: - If **s_type** is unspecified, the matching fails. diff --git a/en/application-dev/application-models/extensionability-overview.md b/en/application-dev/application-models/extensionability-overview.md index cbc50b7f1bc439b156644712531da7128409c476..719a451c6b6b468925174d5be187ae3be82e71c5 100644 --- a/en/application-dev/application-models/extensionability-overview.md +++ b/en/application-dev/application-models/extensionability-overview.md @@ -9,9 +9,9 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab - [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets. -- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides APIs for registering, canceling, and querying Work Scheduler tasks. +- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks. -- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. +- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which is used to develop input method applications. - [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md): ExtensionAbility component of the service type, which provides APIs related to background service scenarios. @@ -33,6 +33,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab > > 3. Third-party applications can use other types of ExtensionAbility components that have been defined. + ## Using ExtensionAbility of the Specified Type All types of ExtensionAbility components are started by the corresponding system management service, rather than applications, so that their lifecycles are under control by the system. The caller of the ExtensionAbility component does not need to care about its lifecycle. @@ -49,20 +50,17 @@ The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-input The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](service-widget-overview.md). You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are scheduled and managed by FormManagerService. - ![form_extension](figures/form_extension.png) > **NOTE** > > For an application, all ExtensionAbility components of the same type run in an independent process, whereas UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in another independent process. For details, see [Process Model (Stage Model)](process-model-stage.md). -> +> > For example, an application has one UIAbility component, one ServiceExtensionAbility, one DataShareExtensionAbility, two FormExtensionAbility, and one ImeExtensionAbility. When the application is running, there are three processes: -> +> > - UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in an independent process. -> +> > - The two FormExtensionAbility components run in an independent process. -> +> > - The two ImeExtensionAbility components run in an independent process. - - \ No newline at end of file diff --git a/en/application-dev/application-models/fa-model-development-overview.md b/en/application-dev/application-models/fa-model-development-overview.md index f26280e2cc96cac5601b29db322affcbb323f570..db48ff10046f5277a06c80633153a0efb6124f79 100644 --- a/en/application-dev/application-models/fa-model-development-overview.md +++ b/en/application-dev/application-models/fa-model-development-overview.md @@ -3,12 +3,13 @@ During application development based on the Feature Ability (FA) model, the following tasks are involved in the application model. -**Table 1** FA model development process + + **Table 1** FA model development process | Task| Introduction| Guide| | -------- | -------- | -------- | -| Application component development| Use the PageAbility, ServiceAbility, DataAbility, and widgets of the FA model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- [PageAbility Component](pageability-overview.md)
- [ServiceAbility Component](serviceability-overview.md)
- [DataAbility Component](dataability-overview.md)
- [Widget Development](Widget-development-fa.md)
- [Context](application-context-fa.md)
- [Want](want-fa.md) | -| Inter-process communication (IPC)| Learn the process model and common IPC modes of the FA model.| [Common Events](common-event-fa.md)
[Background Services](rpc.md) | -| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the FA model.| [Inter-Thread Communication](itc-fa-overview.md)| +| Application component development| Use the PageAbility, ServiceAbility, DataAbility, and widgets of the FA model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- [PageAbility Component](pageability-overview.md)
- [ServiceAbility Component](serviceability-overview.md)
- [DataAbility Component](dataability-overview.md)
- [Widget Development](widget-development-fa.md)
- [Context](application-context-fa.md)
- [Want](want-fa.md)| +| Process model| Learn the process model and common IPC modes of the FA model.| [Common Events](common-event-fa.md)
[Background Services](rpc.md)| +| Thread model| Learn the thread model and common inter-thread communication modes of the FA model.| [Inter-Thread Communication](itc-fa-overview.md)| | Mission management| Learn the basic concepts and typical scenarios of mission management in the FA model.| [Mission Management](mission-management-fa.md)| -| Application configuration file| Learn the requirements for developing application configuration files in the FA model.| [Application Configuration File](../quick-start/application-configuration-file-overview-fa.md) | +| Application configuration file| Learn the requirements for developing application configuration files in the FA model.| [Application Configuration File](../quick-start/application-configuration-file-overview-fa.md)| diff --git a/en/application-dev/application-models/figures/AccessibilityFramework.png b/en/application-dev/application-models/figures/AccessibilityFramework.png new file mode 100644 index 0000000000000000000000000000000000000000..786233e6ac160972f62b9786397eb077f7ee767c Binary files /dev/null and b/en/application-dev/application-models/figures/AccessibilityFramework.png differ diff --git a/en/application-dev/application-models/figures/WidgetCanvasDemo.jpeg b/en/application-dev/application-models/figures/WidgetCanvasDemo.jpeg deleted file mode 100644 index 9c797ff4575ae0aaf9aad27ae5d4d701181faf97..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/WidgetCanvasDemo.jpeg and /dev/null differ diff --git a/en/application-dev/application-models/figures/WidgetCanvasDemo.png b/en/application-dev/application-models/figures/WidgetCanvasDemo.png new file mode 100644 index 0000000000000000000000000000000000000000..c09c82dd88cf002020990b5b8327701c445eeaaf Binary files /dev/null and b/en/application-dev/application-models/figures/WidgetCanvasDemo.png differ diff --git a/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png b/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png new file mode 100644 index 0000000000000000000000000000000000000000..3f871f4816dfcf60a5c30e39b6d0ead2f8eb711e Binary files /dev/null and b/en/application-dev/application-models/figures/ability-startup-with-implicit-want1.png differ diff --git a/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png b/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png new file mode 100644 index 0000000000000000000000000000000000000000..4f1656a3c20e472e260e8e125c42b47c11a35abb Binary files /dev/null and b/en/application-dev/application-models/figures/ability-startup-with-implicit-want2.png differ diff --git a/en/application-dev/application-models/figures/application_details.jpg b/en/application-dev/application-models/figures/application_details.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e849a47b3d10faefafbf76a7b6309da305a2e9b0 Binary files /dev/null and b/en/application-dev/application-models/figures/application_details.jpg differ diff --git a/en/application-dev/application-models/figures/stage-concepts.png b/en/application-dev/application-models/figures/stage-concepts.png index 42e99447a780b167adaf6ddd196bea4437dfa1a7..9d753f27fca4d507da20b5d5060f9b3d28e616b0 100644 Binary files a/en/application-dev/application-models/figures/stage-concepts.png and b/en/application-dev/application-models/figures/stage-concepts.png differ diff --git a/en/application-dev/application-models/figures/stage-want1.png b/en/application-dev/application-models/figures/stage-want1.png deleted file mode 100644 index 558f0a8588d7785eaad1402e68d6ba60c3118f27..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/stage-want1.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/stage-want2.png b/en/application-dev/application-models/figures/stage-want2.png deleted file mode 100644 index 72829adade52ee11419d726f19e218ec4de15220..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/stage-want2.png and /dev/null differ diff --git a/en/application-dev/application-models/figures/start-uiability-floating-window.png b/en/application-dev/application-models/figures/start-uiability-floating-window.png new file mode 100644 index 0000000000000000000000000000000000000000..6857c9b31692419dd7937737d53424dd2b79aaed Binary files /dev/null and b/en/application-dev/application-models/figures/start-uiability-floating-window.png differ diff --git a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png index 92292f2c6ef4c9cbd06da2a523f27b571a957e2b..344cf05e96c539ca73fdb9282625a1d1cb8584e7 100644 Binary files a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png and b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png differ diff --git a/en/application-dev/application-models/figures/want-action.png b/en/application-dev/application-models/figures/want-action.png index 0d8e18ce5870bea777c26b832d3f29674c2fa261..b907e8158bd9fd183ceabb181a13aa813f01e77e 100644 Binary files a/en/application-dev/application-models/figures/want-action.png and b/en/application-dev/application-models/figures/want-action.png differ diff --git a/en/application-dev/application-models/figures/widget-development-stage.png b/en/application-dev/application-models/figures/widget-development-stage.png deleted file mode 100644 index 795e96171e6d890e72a09382906302dd0fa45fab..0000000000000000000000000000000000000000 Binary files a/en/application-dev/application-models/figures/widget-development-stage.png and /dev/null differ diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md index 714698d002237cf3c2d45267596089c1317c66af..418eac519cb62c7339048df4f8663e20df8ef185 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -47,67 +47,42 @@ The table below describes the main APIs used for cross-device migration. For det ## How to Develop -1. Configure the data synchronization permission in the **module.json5** file. The sample code is as follows: - +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). + +3. Configure the fields related to cross-device migration in the configuration file. + + Configure the application to support migration. + 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 the target device. + + ```json { "module": { - "requestPermissions":[ - { - "name" : "ohos.permission.DISTRIBUTED_DATASYNC", + ... + "abilities": [ + { + ... + "continuable": true, } ] } } ``` -2. Configure the fields related to cross-device migration in the configuration file. - - Configure the application to support migration. - - - 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 the target device. - ```json - { - "module": { - // ... - "abilities": [ - { - // ... - "continuable": true, - } - ] - } - } - ``` - - - Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). - -3. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: - - ```ts - requestPermission() { - let context = this.context - let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] - context.requestPermissionsFromUser(permissions).then((data) => { - console.info("Succeed to request permission from user with data: "+ JSON.stringify(data)) - }).catch((error) => { - console.info("Failed to request permission from user with error: "+ JSON.stringify(error)) - }) - } - ``` + Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). 4. Implement [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator. - [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision. - - Saving migrated data: You can save the data to be migrated in key-value pairs in **wantParam**. - Checking application compatibility: You can obtain the version number of the target application from **wantParam** and check the compatibility between the target application and the current application. - Making a migration decision: You can determine whether to support the migration based on the return value of **onContinue()**. For details about the return value, see [Available APIs](#available-apis). - The sample code is as follows: - + The sample code is as follows: + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import AbilityConstant from '@ohos.app.ability.AbilityConstant'; diff --git a/en/application-dev/application-models/inputmethodextentionability.md b/en/application-dev/application-models/inputmethodextentionability.md index 2b3910707ecdb6f964822380a85b14857ec8fd29..2e8371d7e7b9514003295ad4f57b1b8fd678ad3b 100644 --- a/en/application-dev/application-models/inputmethodextentionability.md +++ b/en/application-dev/application-models/inputmethodextentionability.md @@ -1,11 +1,11 @@ # InputMethodExtensionAbility Development -[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) is an ExtensionAbility component of the inputMethod type that provides extension capabilities for the input method framework. +## When to Use +[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md), inherited from [ExtensionAbility](extensionability-overview.md), is used for developing input method applications. -InputMethodExtensionAbility can be started or connected by other application components to process transactions in the background based on the request of the caller. +The entire lifecycle of the [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) instance and the owning ExtensionAbility process is scheduled and managed by the input method framework. The input method framework provides the [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) base class. Derive this base class to implement initialization and resource clearing. - -InputMethodExtensionAbility provides related capabilities through the [InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md). +[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) provides related capabilities through [InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md). ## Implementing an Input Method Application @@ -13,15 +13,13 @@ InputMethodExtensionAbility provides related capabilities through the [InputMeth InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** callbacks, as described below. Override them as required. - **onCreate** - This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. - + > **NOTE** > > If a service has been created, starting it again does not trigger the **onCreate()** callback. - + - **onDestroy** - This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener. @@ -29,7 +27,7 @@ InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** call To implement an input method application, manually create an InputMethodExtensionAbility component in DevEco Studio. The procedure is as follows: -In the **ets** directory of the target module, right-click and choose **New** > **Extention Ability** > **InputMethod** to a minimum template of InputMethodExtensionAbility. +In the **ets** directory of the target module, right-click and choose **New** > **Extension Ability** > **InputMethod** to a minimum template of InputMethodExtensionAbility. > **NOTE** > @@ -70,7 +68,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth onDestroy() { console.log("onDestroy."); - this.context.destroy(); + this.keyboardController.onDestroy(); // Destroy the window and deregister the event listener. } } ``` @@ -109,7 +107,6 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth this.unRegisterListener(); // Deregister the event listener. let win = windowManager.findWindow(this.windowName); win.destroyWindow(); // Destroy the window. - this.mContext.terminateSelf(); // Terminate the InputMethodExtensionAbility service. } private initWindow(): void // Initialize the window. @@ -159,7 +156,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth }) globalThis.inputAbility.on('inputStop', (imeId) => { if (imeId == "Bundle name/Ability name") { - this.onDestroy(); + this.mContext.destroy(); // Destroy the InputMethodExtensionAbility service. } }); } @@ -233,7 +230,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth Add the path to this file to the **src** field in the **resources/base/profile/main_pages.json** file. - ```ts + ```ets import { numberSourceListData, sourceListType } from './keyboardKeyData' @Component @@ -342,12 +339,12 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth } ``` - Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the target module. Set **type** to **"inputMethod"** and **srcEntry** to the code path of the InputMethodExtensionAbility component. +5. Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"inputMethod"** and **srcEntry** to the code path of the InputMethodExtensionAbility component. ```ts { "module": { - // ... + ... "extensionAbilities": [ { "description": "inputMethod", @@ -363,4 +360,3 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth ``` - diff --git a/en/application-dev/application-models/itc-with-emitter.md b/en/application-dev/application-models/itc-with-emitter.md index 2966bd8eea41e04893814f20a3c5b2f9e4e456c9..36a259d52b691459e55be502d3071135be67eb00 100644 --- a/en/application-dev/application-models/itc-with-emitter.md +++ b/en/application-dev/application-models/itc-with-emitter.md @@ -1,5 +1,6 @@ # Using Emitter for Inter-Thread Communication + [Emitter](../reference/apis/js-apis-emitter.md) provides APIs for sending and processing events between threads, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. @@ -13,12 +14,12 @@ To develop the Emitter mode, perform the following steps: // Define an event with eventId 1. let event = { - eventId: 1 + eventId: 1 }; // Trigger the callback after the event with eventId 1 is received. let callback = (eventData) => { - console.info('event callback'); + console.info('event callback'); }; // Subscribe to the event with eventId 1. @@ -29,21 +30,21 @@ To develop the Emitter mode, perform the following steps: ```ts import emitter from "@ohos.events.emitter"; - + // Define an event with eventId 1 and priority Low. let event = { - eventId: 1, - priority: emitter.EventPriority.LOW + eventId: 1, + priority: emitter.EventPriority.LOW }; - + let eventData = { - data: { - "content": "c", - "id": 1, - "isEmpty": false, - } + data: { + "content": "c", + "id": 1, + "isEmpty": false, + } }; - + // Emit the event with eventId 1 and event content eventData. emitter.emit(event, eventData); ``` diff --git a/en/application-dev/application-models/itc-with-worker.md b/en/application-dev/application-models/itc-with-worker.md index 996ab941b0244571dff6116a45ab5e2165cf1184..677483dbb2f4d4a6925995da680c0c18c80b8efc 100644 --- a/en/application-dev/application-models/itc-with-worker.md +++ b/en/application-dev/application-models/itc-with-worker.md @@ -1,5 +1,6 @@ # Using Worker for Inter-Thread Communication + [Worker](../reference/apis/js-apis-worker.md) is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The script file passed in during worker creation is executed in the worker thread. Generally, time-consuming operations are processed in the worker thread. However, pages cannot be directly updated in the worker thread. @@ -9,13 +10,13 @@ To develop the Worker mode, perform the following steps: 1. Configure the **buildOption** field in the [module-level build-profile.json5](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-building-configuration-0000001218440654#section6887184182020) file of the project. ```ts - "buildOption": { - "sourceOption": { - "workers": [ - "./src/main/ets/workers/worker.ts" - ] - } + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] } + } ``` 2. Create the **worker.ts** file based on the configuration in **build-profile.json5**. @@ -27,9 +28,9 @@ To develop the Worker mode, perform the following steps: // Process messages from the main thread. parent.onmessage = function(message) { - console.info("onmessage: " + message) - // Send a message to the main thread. - parent.postMessage("message from worker thread.") + console.info("onmessage: " + message) + // Send a message to the main thread. + parent.postMessage("message from worker thread.") } ``` @@ -46,10 +47,10 @@ To develop the Worker mode, perform the following steps: // Process messages from the worker thread. wk.onmessage = function(message) { - console.info("message from worker: " + message) + console.info("message from worker: " + message) - // Stop the worker thread based on service requirements. - wk.terminate() + // Stop the worker thread based on service requirements. + wk.terminate(); } ``` @@ -57,23 +58,22 @@ To develop the Worker mode, perform the following steps: ```ts import worker from '@ohos.worker'; - + let wk = new worker.ThreadWorker("../workers/worker.ts"); - + // Send a message to the worker thread. wk.postMessage("message from main thread.") - + // Process messages from the worker thread. wk.onmessage = function(message) { - console.info("message from worker: " + message) - - // Stop the worker thread based on service requirements. - wk.terminate() + console.info("message from worker: " + message) + + // Stop the worker thread based on service requirements. + wk.terminate(); } ``` > **NOTE** -> +> > - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.ts** when creating a worker thread in the FA model. -> > - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types). diff --git a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md index c98d39ff8348f330d58138db89afcc2a0d5995ca..51e2c75c72caa10f56cc21ad2057f9f7a94a8c12 100644 --- a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md +++ b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md @@ -5,7 +5,6 @@ Setting a unique icon and name for each mission snapshot of an application helps By default, the **icon** and **label** fields in the [abilities tag](../quick-start/module-configuration-file.md#abilities) of the [module.json5 file](../quick-start/module-configuration-file.md) are used to set the icon and label. Figure 1 Mission snapshot of a UIAbility - ![](figures/mission-list-recent.png) You can also use [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) and [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to customize the icon and name for a mission snapshot. For example, for a UIAbility instance in multiton mode, you can configure the icon and name for each mission snapshot based on different functions. @@ -21,15 +20,16 @@ Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-applica ```ts let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information. -this.context.setMissionIcon(imagePixelMap, (err) => { - console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); +context.setMissionIcon(imagePixelMap, (err) => { + if (err.code) { + console.error(`Failed to set mission icon. Code is ${err.code}, message is ${err.message}`); + } }) ``` The display effect is shown below. Figure 2 Mission snapshot icon - ![](figures/mission-set-task-snapshot-icon.png) ## Setting a Mission Snapshot Name @@ -38,14 +38,13 @@ Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-applic ```ts this.context.setMissionLabel('test').then(() => { - console.info('setMissionLabel succeeded.'); + console.info('Succeeded in seting mission label.'); }).catch((err) => { - console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); + console.error(`Failed to set mission label. Code is ${err.code}, message is ${err.message}`); }); ``` The display effect is shown below. Figure 3 Mission snapshot name - ![](figures/mission-set-task-snapshot-label.png) diff --git a/en/application-dev/application-models/module-switch.md b/en/application-dev/application-models/module-switch.md index f86d416597febe296adf6bd38b6a3d87a86fdda7..8adf2dbb7608da48131c9402f4ea3b0ac09a525d 100644 --- a/en/application-dev/application-models/module-switch.md +++ b/en/application-dev/application-models/module-switch.md @@ -3,7 +3,7 @@ When switching an application from the FA model to the stage model, you must migrate the configurations under the **module** tag in the **config.json** file to the **module** tag in the **module.json5** file. -### Table 1 module Comparison +**Table 1** module comparison | Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | @@ -15,8 +15,8 @@ When switching an application from the FA model to the stage model, you must mig | moduleType in the distro object| Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this field to **har**.| type | The field name is changed.| | installationFree in the distro object| Whether the HAP file supports the installation-free feature.| installationFree | The field name is changed.| | deliveryWithInstall in the distro object| Whether the HAP file is installed with the application.| deliveryWithInstall | The field name is changed.| -| metaData | Metadata of the HAP file.| metadata | See [Table 2](#table-2-metadata-comparison).| -| abilities | All abilities in the current module.| abilities | See [Table 5](#table-5-abilities-comparison).| +| metaData | Metadata of the HAP file.| metadata | For details, see Table 2.| +| abilities | All abilities in the current module.| abilities | For details, see Table 5.| | js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module.| pages | The stage model retains **pages** under the **module** tag. The window configuration is the lower level of **pages**.| | shortcuts | Shortcuts of the application.| shortcut_config.json| In the stage model, the **shortcut_config.json** file is defined in **resources/base/profile** in the development view.| | reqPermissions | Permissions that the application requests from the system when it is running.| requestPermissions | The field name is changed.| @@ -27,38 +27,38 @@ When switching an application from the FA model to the stage model, you must mig | entryTheme | Keyword of an OpenHarmony internal theme.| / | This configuration is not supported in the stage model.| -### Table 2 metaData Comparison +**Table 2** metaData comparison -| Field Name Under metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | parameters | Metadata of the parameters to be passed for calling the ability.| / | This configuration is not supported in the stage model.| | results | Metadata of the ability return value.| / | This configuration is not supported in the stage model.| -| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| metadata | See [Table 3](#table-3-comparison-between-customizedata-under-metadata-in-the-fa-model-and-metadata-in-the-stage-model).| +| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| metadata | **For details**, see Table 3.| -### Table 3 Comparison Between customizeData Under metaData in the FA Model and metadata in the Stage Model +**Table 3** Comparison between customizeData under metaData in the FA model and metadata in the stage Model -| Field Name Under customizeData in metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes.| name | None.| | value | Value of the data item. The value is a string with a maximum of 255 bytes.| value | None.| -| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see [Table 4](#table 4-metadata-examples).| +| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see Table 4.| -### Table 4 metaData Examples +**Table 4** metaData examples | Example in the FA Model| Example in the Stage Model| | -------- | -------- | | "meteData": {
"customizeDate": [{
"name": "label",
"value": "string",
"extra": "$string:label",
}]
} | "meteData": [{
"name": "label",
"value": "string",
"resource": "$string:label",
}] | -### Table 5 abilities Comparison +**Table 5** abilities comparison | Field Name Under abilities in the FA Model| Field Description| Field Name Under abilities in the Stage Model| Difference| | -------- | -------- | -------- | -------- | | process | Name of the process running the application or ability.| / | The stage model does not support configuration of **process** under **abilities**. The configuration of **process** is available under the **module** tag.| | uri | URI of the ability.| / | This configuration is not supported in the stage model.| | deviceCapability | Device capabilities required to run the ability.| / | This configuration is not supported in the stage model.| -| metaData | Metadata of the ability.| metadata | See [Table 2](#table-2-metadata-comparison).| +| metaData | Metadata of the ability.| metadata | For details, see Table 2.| | type | Ability type.| / | This configuration is not supported in the stage model.| | grantPermission | Whether permissions can be granted for any data in the ability.| / | The stage model does not support such a configuration under **abilities**.| | readPermission | Permission required for reading data in the ability. This field applies only to the ability using the Data template.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.| @@ -71,5 +71,5 @@ When switching an application from the FA model to the stage model, you must mig | formsEnabled | Whether the ability can provide widgets.| / | This configuration is not supported in the stage model.| | forms | Information about the widgets used by the ability. This field is valid only when **formsEnabled** is set to **true**.| form_config.json| In the stage model, the **form_config.json** file is defined in **resources/base/profile** in the development view.| | srcLanguage | Programming language used to develop the ability.| / | This configuration is not supported in the stage model.| -| srcPath | Path of the JS component code corresponding to the ability.| srcEnty | Path of the JS code corresponding to the ability.| +| srcPath | Path of the JS component code corresponding to the ability.| srcEntry | Path of the JS code corresponding to the ability.| | uriPermission | Application data that the ability can access.| / | This configuration is not supported in the stage model.| diff --git a/en/application-dev/application-models/page-mission-stack.md b/en/application-dev/application-models/page-mission-stack.md index 702cb9ba928d5266ce6720d10538df6109b0cbeb..cdb7ce724f2a29c711d4d056bcda5716f265ba48 100644 --- a/en/application-dev/application-models/page-mission-stack.md +++ b/en/application-dev/application-models/page-mission-stack.md @@ -5,7 +5,8 @@ A single UIAbility component can implement multiple pages and redirection between these pages. The redirection relationship inside the UIAbility component is called page stack, which is managed by the ArkUI framework. For example, Page1 -> Page2 -> Page3 of UIAbility1 and PageA -> PageB -> PageC of UIAbility2 in the figure below are two page stacks. - **Figure 1** Page stack +**Figure 1** Page stack + ![mission-record](figures/mission-record.png) - A page stack is formed as follows (Steps 2, 3, 5, and 6 are page redirection and managed by ArkUI): diff --git a/en/application-dev/application-models/pageability-launch-type.md b/en/application-dev/application-models/pageability-launch-type.md index 3b75ff6a60899f19f08aad5235fb3dc49632cb01..524f693c3d8c5586217d3264dedd9bde0daa16ff 100644 --- a/en/application-dev/application-models/pageability-launch-type.md +++ b/en/application-dev/application-models/pageability-launch-type.md @@ -5,7 +5,7 @@ Depending on the launch type, the action performed when the PageAbility starts d **Table 1** PageAbility launch types -| Launch Type| Meaning | Description| +| Launch Type| Meaning| Description | | -------- | -------- | -------- | | singleton | Singleton mode| Each time **startAbility()** is called, if an ability instance of this type already exists in the application process, the instance is reused. There is only one ability instance of this type in **Recents**.
A typical scenario is as follows: When a user opens a video playback application and watches a video, returns to the home screen, and opens the video playback application again, the video that the user watched before returning to the home screen is still played.| | standard | Multiton mode| Default type. Each time **startAbility()** is called, a new ability instance is created in the application process. Multiple ability instances of this type are displayed in **Recents**.
A typical scenario is as follows: When a user opens a document application and touches **New**, a new document task is created. Multiple new document missions are displayed in **Recents**.| @@ -16,13 +16,13 @@ You can set **launchType** in the **config.json** file to configure the launch t ```json { "module": { - // ... + ... "abilities": [ { // singleton means the singleton mode. // standard means the multiton mode. "launchType": "standard", - // ... + ... } ] } @@ -32,7 +32,6 @@ You can set **launchType** in the **config.json** file to configure the launch t When the PageAbility is started in multiton mode or it is started in singleton mode for the first time, the [PageAbility lifecycle callbacks](pageability-lifecycle.md#table13118194914476) are triggered. When it is not started for the first time in singleton mode, the **onNewWant()** callback (as described in the table below) is triggered, but the **onCreate()** callback is not. - **Table 2** Callbacks specific to the singleton mode | API| Description| diff --git a/en/application-dev/application-models/redirection-rules.md b/en/application-dev/application-models/redirection-rules.md index 12926c13985dbc2a535206aa4f998df2c44b2ecb..19c74c605cd7ca1451cef6809f6ec5238cec36df 100644 --- a/en/application-dev/application-models/redirection-rules.md +++ b/en/application-dev/application-models/redirection-rules.md @@ -7,14 +7,13 @@ Generally, UI redirection within an application is triggered by users. However, The PageAbility has a UI. It can use **startAbility()** to start an ability that has a UI and is visible to users. -The **exported** field under **abilities** in the **config.json** file specifies whether an ability can be started by other application components. +The **visible** field under **abilities** in the **config.json** file specifies whether an ability can be started by other application components. - -**Table 1** Description of exported +**Table 1** Description of visible | Name| Description| Initial Value Allowed| | -------- | -------- | -------- | -| exported | Whether the ability can be called by other applications.
**true**: The ability can be called by any application.
**false**: The ability can be called only by other components of the same application.| Yes (initial value: **false**)| +| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by any application.
**false**: The ability can be called only by other components of the same application.| Yes (initial value: **false**)| To enable an ability to be called by any application, configure the **config.json** file as follows: @@ -22,11 +21,11 @@ To enable an ability to be called by any application, configure the **config.jso ```ts { "module": { - // ... + ... "abilities": [ { - "exported": "true", - // ... + "visible": "true", + ... } ] } @@ -34,4 +33,4 @@ To enable an ability to be called by any application, configure the **config.jso ``` -If the ability contains **skills**, you are advised to set **exported** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **exported** set to **false** are home screen, voice assistant, or search assistant. +If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant. diff --git a/en/application-dev/application-models/request-permissions.md b/en/application-dev/application-models/request-permissions.md index 670860d87dbb56adceb02f4ca350c24b61260d30..a29b793c9949d1080c8322681ba27cf6495f29ac 100644 --- a/en/application-dev/application-models/request-permissions.md +++ b/en/application-dev/application-models/request-permissions.md @@ -9,37 +9,7 @@ During application development, you must declare the required permission in the To declare a permission in **config.json**, add **reqPermissions** under **module** and list the permission. +For example, to request the permission to access the calendar, perform the following steps: -For example, to declare the permission to access the calendar, request the **ohos.permission.READ_CALENDAR** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - - -The sample code in the **config.json** file is as follows: - -```json -{ - "module": { - // ... - "reqPermissions": [ - { - "name": "ohos.permission.READ_CALENDAR" - // ... - } - ] - } -} -``` - - -Request the permission from uses in the form of a dialog box: - -```ts -import featureAbility from '@ohos.ability.featureAbility'; - -let context = featureAbility.getContext(); -let permissions: Array = ['ohos.permission.READ_CALENDAR'] -context.requestPermissionsFromUser(permissions, 1).then((data) => { - console.info("Succeed to request permission from user with data: " + JSON.stringify(data)) -}).catch((error) => { - console.info("Failed to request permission from user with error: " + JSON.stringify(error)) -}) -``` +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). +2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). diff --git a/en/application-dev/application-models/service-widget-overview.md b/en/application-dev/application-models/service-widget-overview.md index 3739129f2a07765b2ebe015910d1d6e3d8d721d0..528d9d4c134107c30de75f7f9e84ab42be514224 100644 --- a/en/application-dev/application-models/service-widget-overview.md +++ b/en/application-dev/application-models/service-widget-overview.md @@ -6,7 +6,7 @@ A service widget (also called widget) is a set of UI components that display imp ## Service Widget Architecture - **Figure 1** Service widget architecture +**Figure 1** Service widget architecture ![WidgetArchitecture](figures/WidgetArchitecture.png) @@ -24,7 +24,7 @@ Before you get started, it would be helpful if you have a basic understanding of Below is the typical procedure of using the widget: - **Figure 2** Typical procedure of using the widget +**Figure 2** Typical procedure of using the widget ![WidgetUse](figures/WidgetUse.png) @@ -55,4 +55,4 @@ ArkTS widgets and JS widgets have different implementation principles and featur | Custom drawing| Not supported| Supported| | Logic code execution (excluding the import capability)| Not supported| Supported| -As can be seen above, ArkTS widgets have more capabilities and use cases than JS widgets. Therefore, ArkTS widgets are always recommended, except for the case where the widget consists of only static pages. +As can be seen above, ArkTS widgets provide more capabilities and use cases than JS widgets. Therefore, ArkTS widgets are always recommended, except for the case where the widget consists of only static pages. diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index 2e9aaeb48100d86d0cd1c7a0e69ea01bf4ef2340..555a288f4726a2bfbb9db9cf0c26b1cb8e799b04 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -29,6 +29,7 @@ Note the following: [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility. **Figure 1** ServiceExtensionAbility lifecycle + ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) - **onCreate** @@ -109,7 +110,7 @@ export default class ServiceExtImpl extends IdlServiceExtStub { insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } @@ -175,7 +176,7 @@ To manually create a ServiceExtensionAbility in the DevEco Studio project, perfo ```json { "module": { - // ... + ... "extensionAbilities": [ { "name": "ServiceExtAbility", @@ -201,41 +202,43 @@ A system application uses the [startServiceExtensionAbility()](../reference/apis 1. Start a new ServiceExtensionAbility in a system application. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts + let context = ...; // UIAbilityContext let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; - this.context.startServiceExtensionAbility(want).then(() => { - console.info('startServiceExtensionAbility success'); - }).catch((error) => { - console.info('startServiceExtensionAbility failed'); + context.startServiceExtensionAbility(want).then(() => { + console.info('Succeeded in starting ServiceExtensionAbility.'); + }).catch((err) => { + console.error(`Failed to start ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); }) ``` 2. Stop ServiceExtensionAbility in the system application. ```ts + let context = ...; // UIAbilityContext let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; - this.context.stopServiceExtensionAbility(want).then(() => { - console.info('stopServiceExtensionAbility success'); - }).catch((error) => { - console.info('stopServiceExtensionAbility failed'); + context.stopServiceExtensionAbility(want).then(() => { + console.info('Succeeded in stoping ServiceExtensionAbility.'); + }).catch((err) => { + console.error(`Failed to stop ServiceExtensionAbility. Code is ${err.code}, message is ${err.message}`); }) ``` 3. ServiceExtensionAbility stops itself. ```ts - // this is the current ServiceExtensionAbility component. - this.context.terminateSelf().then(() => { - console.info('terminateSelf success'); - }).catch((error) => { - console.info('terminateSelf failed'); + let context = ...; // ServiceExtensionContext + context.terminateSelf().then(() => { + console.info('Succeeded in terminating self.'); + }).catch((err) => { + console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -257,27 +260,27 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec ```ts let want = { - "deviceId": "", - "bundleName": "com.example.myapplication", - "abilityName": "ServiceExtAbility" + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" }; let options = { - onConnect(elementName, remote) { - /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback. - * This object is used for communication with ServiceExtensionAbility. For details, see the section below. - */ - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + /* The input parameter remote is the object returned by ServiceExtensionAbility in the onConnect lifecycle callback. + * This object is used for communication with ServiceExtensionAbility. For details, see the section below. + */ + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection. let connectionId = this.context.connectServiceExtensionAbility(want, options); @@ -288,9 +291,9 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec ```ts // connectionId is returned when connectServiceExtensionAbility is called and needs to be manually maintained. this.context.disconnectServiceExtensionAbility(connectionId).then((data) => { - console.info('disconnectServiceExtensionAbility success'); + console.info('disconnectServiceExtensionAbility success'); }).catch((error) => { - console.error('disconnectServiceExtensionAbility failed'); + console.error('disconnectServiceExtensionAbility failed'); }) ``` @@ -305,27 +308,27 @@ After obtaining the [rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteo import IdlServiceExtProxy from '../IdlServiceExt/idl_service_ext_proxy'; let options = { - onConnect(elementName, remote) { - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - let serviceExtProxy = new IdlServiceExtProxy(remote); - // Communication is carried out by interface calling, without exposing RPC details. - serviceExtProxy.processData(1, (errorCode, retVal) => { - console.log(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); - }); - serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { - console.log(`insertDataToMap, errorCode: ${errorCode}`); - }) - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + let serviceExtProxy = new IdlServiceExtProxy(remote); + // Communication is carried out by interface calling, without exposing RPC details. + serviceExtProxy.processData(1, (errorCode, retVal) => { + console.info(`processData, errorCode: ${errorCode}, retVal: ${retVal}`); + }); + serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => { + console.info(`insertDataToMap, errorCode: ${errorCode}`); + }) + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } ``` @@ -333,40 +336,40 @@ After obtaining the [rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteo ```ts import rpc from '@ohos.rpc'; - + const REQUEST_CODE = 1; let options = { - onConnect(elementName, remote) { - console.info('onConnect callback'); - if (remote === null) { - console.info(`onConnect remote is null`); - return; - } - // Directly call the RPC interface to send messages to the server. The client needs to serialize the input parameters and deserialize the return values. The process is complex. - let option = new rpc.MessageOption(); - let data = new rpc.MessageSequence(); - let reply = new rpc.MessageSequence(); - data.writeInt(100); - - // @param code Indicates the service request code sent by the client. - // @param data Indicates the {@link MessageSequence} object sent by the client. - // @param reply Indicates the response message object sent by the remote service. - // @param options Specifies whether the operation is synchronous or asynchronous. - // - // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. - remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => { - let msg = reply.readInt(); - console.info(`sendMessageRequest ret:${ret} msg:${msg}`); - }).catch((error) => { - console.info('sendMessageRequest failed'); - }); - }, - onDisconnect(elementName) { - console.info('onDisconnect callback') - }, - onFailed(code) { - console.info('onFailed callback') + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; } + // Directly call the RPC interface to send messages to the server. The client needs to serialize the input parameters and deserialize the return values. The process is complex. + let option = new rpc.MessageOption(); + let data = new rpc.MessageSequence(); + let reply = new rpc.MessageSequence(); + data.writeInt(100); + + // @param code Indicates the service request code sent by the client. + // @param data Indicates the {@link MessageSequence} object sent by the client. + // @param reply Indicates the response message object sent by the remote service. + // @param options Specifies whether the operation is synchronous or asynchronous. + // + // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. + remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => { + let msg = reply.readInt(); + console.info(`sendMessageRequest ret:${ret} msg:${msg}`); + }).catch((error) => { + console.info('sendMessageRequest failed'); + }); + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } } ``` @@ -381,8 +384,8 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i ```ts import rpc from '@ohos.rpc'; import bundleManager from '@ohos.bundle.bundleManager'; - import {processDataCallback} from './i_idl_service_ext'; - import {insertDataToMapCallback} from './i_idl_service_ext'; + import { processDataCallback } from './i_idl_service_ext'; + import { insertDataToMapCallback } from './i_idl_service_ext'; import IdlServiceExtStub from './idl_service_ext_stub'; const ERR_OK = 0; @@ -397,7 +400,7 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i bundleManager.getBundleNameByUid(callerUid).then((callerBundleName) => { console.info(TAG, 'getBundleNameByUid: ' + callerBundleName); // Identify the bundle name of the client. - if (callerBundleName != 'com.example.connectextapp') { // The verification fails. + if (callerBundleName != 'com.example.connectextapp') { // The verification fails. console.info(TAG, 'The caller bundle is not in whitelist, reject'); return; } @@ -409,7 +412,7 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } @@ -425,15 +428,15 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i import {processDataCallback} from './i_idl_service_ext'; import {insertDataToMapCallback} from './i_idl_service_ext'; import IdlServiceExtStub from './idl_service_ext_stub'; - + const ERR_OK = 0; const ERR_DENY = -1; const TAG: string = "[IdlServiceExtImpl]"; - + export default class ServiceExtImpl extends IdlServiceExtStub { processData(data: number, callback: processDataCallback): void { console.info(TAG, `processData: ${data}`); - + let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); let accessManger = abilityAccessCtrl.createAtManager(); // The permission to be verified varies depending on the service requirements. ohos.permission.SET_WALLPAPER is only an example. @@ -446,10 +449,10 @@ When ServiceExtensionAbility is used to provide sensitive services, the client i } callback(ERR_OK, data + 1); // The verification is successful, and service logic is executed normally. } - + insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void { // Implement service logic. - console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`); + console.info(TAG, `insertDataToMap, key: ${key} val: ${val}`); callback(ERR_OK); } } diff --git a/en/application-dev/application-models/stage-model-development-overview.md b/en/application-dev/application-models/stage-model-development-overview.md index cfd6cd6a96b79b03541e01b3af4fa5667c315289..d4ad1d87c602c169e13b9ff99b8b491a33babd0a 100644 --- a/en/application-dev/application-models/stage-model-development-overview.md +++ b/en/application-dev/application-models/stage-model-development-overview.md @@ -12,7 +12,7 @@ The following figure shows the basic concepts used in the stage model. The stage model provides two types of application components: UIAbility and ExtensionAbility. Both have specific classes and support object-oriented development. - - UIAbility has the UI and is mainly used for user interaction. For example, with UIAbility, the Gallery application can display images in the liquid layout. After a user selects an image, it uses a new UI to display the image details. The user can touch the **Back** button to return to the liquid layout. The lifecycle of the UIAbility component contains the creation, destruction, foreground, and background states. Display-related states are exposed through WindowStage events. + - UIAbility is a type of application component that provides the UI for user interaction. For example, with UIAbility, the Gallery application can display images in the liquid layout. After a user selects an image, it uses a new UI to display the image details. The user can touch the **Back** button to return to the liquid layout. The lifecycle of the UIAbility component contains the creation, destruction, foreground, and background states. Display-related states are exposed through WindowStage events. - ExtensionAbility is oriented to specific scenarios. You cannot derive directly from ExtensionAbility. Instead, use the derived classes of ExtensionAbility for your scenarios, such as FormExtensionAbility for widget scenarios, InputMethodExtensionAbility for input method scenarios, and WorkSchedulerExtensionAbility for Work Scheduled task scenarios. For example, to enable a user to create an application widget on the home screen, you must derive FormExtensionAbility, implement the callback functions, and configure the capability in the configuration file. The derived class instances are created by developers and their lifecycles are managed by the system. In the stage model, you must use the derived classes of ExtensionAbility to develop custom services based on your service scenarios. - [WindowStage](../windowmanager/application-window-stage.md) @@ -21,7 +21,7 @@ The following figure shows the basic concepts used in the stage model. - [Context](application-context-stage.md) - In the stage model, Context and its derived classes provide a variety of capabilities that can be called during the runtime. The UIAbility component and ExtensionAbility derived classes have different Context classes. These classes, which all inherit from the base class Context, provide different capabilities. + In the stage model, Context and its derived classes provide a variety of resources and capabilities that can be called during the runtime. The UIAbility component and ExtensionAbility derived classes have different Context classes. These classes, which all inherit from the base class Context, provide different capabilities. - [AbilityStage](abilitystage.md) @@ -37,7 +37,7 @@ During application development based on the stage model, the following tasks are | Task| Introduction| Guide| | -------- | -------- | -------- | | Application component development| Use the UIAbility and ExtensionAbility components of the stage model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-stage.md)
- [UIAbility Component](uiability-overview.md)
- [ExtensionAbility Component](extensionability-overview.md)
- [AbilityStage Container Component](abilitystage.md)
- [Context](application-context-stage.md)
- [Component Startup Rules](component-startup-rules.md)| -| Inter-process communication (IPC)| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)
- [Background Services](background-services.md)| -| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)
- [Worker](itc-with-worker.md)| +| Process model| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)
- [Background Services](background-services.md)| +| Thread model| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)
- [Worker](itc-with-worker.md)| | Mission management| Learn the basic concepts and typical scenarios of mission management in the stage model.| - [Mission Management Scenarios](mission-management-overview.md)
- [Mission Management and Launch Type](mission-management-launch-type.md)
- [Page Stack and Mission List](page-mission-stack.md)| -| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](../quick-start/application-configuration-file-overview-stage.md)| +| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](config-file-stage.md)| diff --git a/en/application-dev/application-models/start-page.md b/en/application-dev/application-models/start-page.md index 4296d832fdaafaba67544e8e62b5c7c08395ecdf..1def472cd5fa2567fda123fc272542787b1f985c 100644 --- a/en/application-dev/application-models/start-page.md +++ b/en/application-dev/application-models/start-page.md @@ -12,7 +12,7 @@ import featureAbility from '@ohos.ability.featureAbility'; async function restartAbility() { let wantInfo = { bundleName: "com.sample.MyApplication", - abilityName: "MainAbility", + abilityName: "EntryAbility", parameters: { page: "pages/second" } @@ -83,13 +83,13 @@ struct Index { @State message: string = 'Hello World' build() { - // ... + ... Button("startAbility") .onClick(() => { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page1" } } }).then((data) => { @@ -98,13 +98,13 @@ struct Index { console.info("startAbility failed errcode:" + err.code) }) }) - // ... + ... Button("page2") .onClick(() => { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page2" } } }).then((data) => { @@ -113,7 +113,7 @@ struct Index { console.info("startAbility failed errcode:" + err.code) }) }) - // ... + ... } } ``` @@ -136,7 +136,7 @@ export default { }) }, onDestroy() { - // ... + ... }, } ``` diff --git a/en/application-dev/application-models/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md index 9d1b7ed27f6780ce56d1e90b3be5d196cf3b1187..bd6a11187fdfbc81c63bcc6601f8a8e82b0dbe4c 100644 --- a/en/application-dev/application-models/start-pageability-from-stage.md +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -21,7 +21,7 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { - // ... + ... }); let want = { bundleName: "com.ohos.fa", @@ -66,7 +66,7 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { - // ... + ... }); let want = { bundleName: "com.ohos.fa", diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md index 36ee305b49698c1f6e6cf216174f77212f1d53e4..a52378af306c9719b086b23f0909f87d7bf376b3 100644 --- a/en/application-dev/application-models/start-remote-pageability.md +++ b/en/application-dev/application-models/start-remote-pageability.md @@ -83,28 +83,31 @@ After obtaining the data synchronization permission, obtain the trusted device l The following sample code shows how to use **getTrustedDeviceListSync()** to obtain the trusted device list. ```ts -import deviceManager from '@ohos.distributedHardware.deviceManager'; -let dmClass; +import deviceManager from '@ohos.distributedHardware.deviceManager'; + +let dmClass; + function getDeviceManager() { - deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => { - if (error) { - console.info('create device manager failed with ' + error) - } - dmClass = dm; - }) + deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => { + if (error) { + console.info('create device manager failed with ' + error) + } + dmClass = dm; + }) } -function getRemoteDeviceId() { - if (typeof dmClass === 'object' && dmClass != null) { - let list = dmClass.getTrustedDeviceListSync(); - if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); - return; - } - console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; - } else { - console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); - } + +function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass != null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); + return; + } + console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + return list[0].deviceId; + } else { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + } } ``` @@ -116,21 +119,22 @@ The following sample code shows how to explicitly start a remote PageAbility thr ```ts import featureAbility from '@ohos.ability.featureAbility'; -function onStartRemoteAbility() { - console.info('onStartRemoteAbility begin'); - let params; - let wantValue = { - bundleName: 'ohos.samples.etsDemo', - abilityName: 'ohos.samples.etsDemo.RemoteAbility', - deviceId: getRemoteDeviceId(), // getRemoteDeviceId is defined in the preceding sample code. - 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'); + +function onStartRemoteAbility() { + console.info('onStartRemoteAbility begin'); + let params; + let wantValue = { + bundleName: 'ohos.samples.etsDemo', + abilityName: 'ohos.samples.etsDemo.RemoteAbility', + deviceId: getRemoteDeviceId(), // getRemoteDeviceId is defined in the preceding sample code. + 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'); } ``` diff --git a/en/application-dev/application-models/start-serviceability.md b/en/application-dev/application-models/start-serviceability.md index f3b0f6aeabc8a3ea35c1f6c390ec53239730443c..e07428f13a5ce3a3981b7881387dc8498f1380d1 100644 --- a/en/application-dev/application-models/start-serviceability.md +++ b/en/application-dev/application-models/start-serviceability.md @@ -27,7 +27,7 @@ async function startServiceAbility() { ``` -In the preceding code, **startAbility()** is used to start the ServiceAbility. +In the preceding code, [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is used to start the ServiceAbility. - If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility. diff --git a/en/application-dev/application-models/subscribe-system-environment-variable-changes.md b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md index c231f483e9bcd8f83faf49d40007730d0f854de5..4eecf15808da492ca69d933fdabf39aa82347ce5 100644 --- a/en/application-dev/application-models/subscribe-system-environment-variable-changes.md +++ b/en/application-dev/application-models/subscribe-system-environment-variable-changes.md @@ -54,7 +54,7 @@ In OpenHarmony, you can subscribe to system environment variable changes in the // Page display. build() { - // ... + ... } } ``` @@ -77,7 +77,7 @@ In OpenHarmony, you can subscribe to system environment variable changes in the // Page display. build() { - // ... + ... } } ``` @@ -99,19 +99,19 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; let systemLanguage: string; // System language in use. export default class MyAbilityStage extends AbilityStage { - onCreate() { - systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time. - console.info(`systemLanguage is ${systemLanguage} `); - } + onCreate() { + systemLanguage = this.context.config.language; // Obtain the system language in use when the AbilityStage instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } - onConfigurationUpdate(newConfig) { - console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); - if (systemLanguage !== newConfig.language) { - console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); - systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. - } + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } + } } ``` @@ -131,21 +131,21 @@ import UIAbility from '@ohos.app.ability.UIAbility'; let systemLanguage: string; // System language in use. export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. - console.info(`systemLanguage is ${systemLanguage} `); - } + onCreate(want, launchParam) { + systemLanguage = this.context.config.language; // Obtain the system language in use when the UIAbility instance is loaded for the first time. + console.info(`systemLanguage is ${systemLanguage} `); + } - onConfigurationUpdate(newConfig) { - console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); + onConfigurationUpdate(newConfig) { + console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`); - if (systemLanguage !== newConfig.language) { - console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); - systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. - } + if (systemLanguage !== newConfig.language) { + console.info(`systemLanguage from ${systemLanguage} changed to ${newConfig.language}`); + systemLanguage = newConfig.language; // Save the new system language as the system language in use, which will be used for comparison. } + } - // ... + ... } ``` @@ -163,10 +163,10 @@ The code snippet below uses FormExtensionAbility as an example to describe how t import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class EntryFormAbility extends FormExtensionAbility { - onConfigurationUpdate(newConfig) { - console.info(`newConfig is ${JSON.stringify(newConfig)}`); - } + onConfigurationUpdate(newConfig) { + console.info(`newConfig is ${JSON.stringify(newConfig)}`); + } - // ... + ... } ``` diff --git a/en/application-dev/application-models/thread-model-fa.md b/en/application-dev/application-models/thread-model-fa.md index 0f11cddb48792e887a14a2d5011dbdcd4736340d..f6b335f8932ee1ebd5bb9bdf11db99ff354a1470 100644 --- a/en/application-dev/application-models/thread-model-fa.md +++ b/en/application-dev/application-models/thread-model-fa.md @@ -1,13 +1,11 @@ # Thread Model Overview (FA Model) - There are three types of threads in the FA model: - - Main thread - + Manages other threads. - + - Ability thread - One ability thread for each ability. - Distributes input events. @@ -16,13 +14,11 @@ There are three types of threads in the FA model: - Receives messages sent by the worker thread. - Worker thread - + Performs time-consuming operations - Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. - > **NOTE** > > The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread. diff --git a/en/application-dev/application-models/thread-model-stage.md b/en/application-dev/application-models/thread-model-stage.md index 7343b9b619a5d68354e65e254a22a2b078ca44ee..2b1f855980a14eeba89a18184c69d46eebaea6ac 100644 --- a/en/application-dev/application-models/thread-model-stage.md +++ b/en/application-dev/application-models/thread-model-stage.md @@ -17,5 +17,6 @@ Based on the OpenHarmony thread model, different services run on different threa > **NOTE** > -> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the main thread or between the main thread and worker thread. -> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p ** -T command**, where ** indicates the ID of the application process. +> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the worker thread or between the main thread and worker thread. +> - The UIAbility and UI are in the main thread. For details about data synchronization between them, see [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md). +> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p ** -T command**, where ** indicates the [process ID](process-model-stage.md) of the application. diff --git a/en/application-dev/application-models/uiability-data-sync-with-ui.md b/en/application-dev/application-models/uiability-data-sync-with-ui.md index f53627e974a0f9b4b1323d7694f94e07ebf51753..6998001c763a464e51f8cef4a0c64aec6f1db5e8 100644 --- a/en/application-dev/application-models/uiability-data-sync-with-ui.md +++ b/en/application-dev/application-models/uiability-data-sync-with-ui.md @@ -3,17 +3,16 @@ Based on the OpenHarmony application model, you can use any of the following ways to implement data synchronization between the UIAbility component and UI: -- EventHub: The [base class Context](application-context-stage.md) provides the EventHub capability. It is implemented based on the publish/subscribe (pub/sub) pattern. Your application subscribes to an event and when the event occurs, receives a notification. - -- globalThis: It is a global object accessible in the ArkTS engine instance. -- LocalStorage/AppStorage: See [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md). +- [Using EventHub for Data Synchronization](#using-eventhub-for-data-synchronization): The **EventHub** object is provided by the base class **Context**. Events are transferred using the publish/subscribe (pub/sub) pattern. Specifically, after subscribing to an event, your application will receive the event and process it accordingly when the event is published. +- [Using globalThis for Data Synchronization](#using-globalthis-for-data-synchronization): **globalThis** is a global object inside the ArkTS engine instance and can be accessed by components such as UIAbility, ExtensionAbility, and Page. +- [Using AppStorage or LocalStorage for Data Synchronization](#using-appstorage-or-localstorage-for-data-synchronization): ArkUI provides two application-level state management solutions: AppStorage and LocalStorage, which implement application- and UIAbility-level data synchronization, respectively. ## Using EventHub for Data Synchronization -[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism at the UIAbility or ExtensionAbility component level. Centered on the UIAbility or ExtensionAbility component, EventHub provides data communication capabilities for subscribing to, unsubscribing from, and triggering events. +[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism for the UIAbility or ExtensionAbility component so that they can subscribe to, unsubscribe from, and trigger events. -Before using EventHub, you must obtain an EventHub object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. +Before using the APIs provided by **EventHub**, you must obtain an **EventHub** object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. 1. Call [eventHub.on()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**. @@ -23,21 +22,21 @@ Before using EventHub, you must obtain an EventHub object, which is provided by const TAG: string = '[Example].[Entry].[EntryAbility]'; export default class EntryAbility extends UIAbility { - func1(...data) { - // Trigger the event to complete the service operation. - console.info(TAG, '1. ' + JSON.stringify(data)); - } - - onCreate(want, launch) { - // Obtain an eventHub object. - let eventhub = this.context.eventHub; - // Subscribe to the event. - eventhub.on('event1', this.func1); - eventhub.on('event1', (...data) => { - // Trigger the event to complete the service operation. - console.info(TAG, '2. ' + JSON.stringify(data)); - }); - } + func1(...data) { + // Trigger the event to complete the service operation. + console.info(TAG, '1. ' + JSON.stringify(data)); + } + + onCreate(want, launch) { + // Obtain an eventHub object. + let eventhub = this.context.eventHub; + // Subscribe to the event. + eventhub.on('event1', this.func1); + eventhub.on('event1', (...data) => { + // Trigger the event to complete the service operation. + console.info(TAG, '2. ' + JSON.stringify(data)); + }); + } } ``` @@ -63,7 +62,7 @@ Before using EventHub, you must obtain an EventHub object, which is provided by // Page display. build() { - // ... + ... } } ``` @@ -81,44 +80,42 @@ Before using EventHub, you must obtain an EventHub object, which is provided by 4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event. ```ts - // context is the ability context of the UIAbility instance. + // context is the AbilityContext of the UIAbility instance. this.context.eventHub.off('event1'); ``` ## Using globalThis for Data Synchronization - **globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization. - **Figure 1** Using globalThis for data synchronization - - ![globalThis1](figures/globalThis1.png) +**Figure 1** Using globalThis for data synchronization +![globalThis1](figures/globalThis1.png) The following describes how to use **globalThis** in three scenarios. Precautions are provided as well. - [Using globalThis Between UIAbility and Page](#using-globalthis-between-uiability-and-page) -- [Using globalThis Between UIAbility and UIAbility](##using-globalthis-between-uiability-and-uiability) +- [Using globalThis Between UIAbility and UIAbility](#using-globalthis-between-uiability-and-uiability) - [Use globalThis Between UIAbility and ExtensionAbility](#using-globalthis-between-uiability-and-extensionability) - [Precautions for Using globalThis](#precautions-for-using-globalthis) ### Using globalThis Between UIAbility and Page -You can use **globalThis** to bind attributes or methods to implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. +By binding attributes or methods to **globalThis**, you can implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. -1. When **startAbility()** is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. +1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. ```ts - import UIAbility from '@ohos.app.ability.UIAbility' + import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launch) { - globalThis.entryAbilityWant = want; - // ... - } + onCreate(want, launch) { + globalThis.entryAbilityWant = want; + ... + } - // ... + ... } ``` @@ -136,7 +133,7 @@ You can use **globalThis** to bind attributes or methods to implement data synch // Page display. build() { - // ... + ... } } ``` @@ -144,51 +141,51 @@ You can use **globalThis** to bind attributes or methods to implement data synch ### Using globalThis Between UIAbility and UIAbility -To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from AbilityB. +To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from UIAbilityB. -1. AbilityA stores a string and binds it to globalThis. +1. UIAbilityA stores a string and binds it to globalThis. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { - globalThis.entryAbilityStr = 'AbilityA'; // AbilityA stores the string "AbilityA" to globalThis. - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { + globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA stores the string "UIAbilityA" to globalThis. + ... + } } ``` -2. Obtain the data from AbilityB. +2. Obtain the data from UIAbilityB. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityB extends UIAbility { - onCreate(want, launch) { - // AbilityB reads the name from globalThis and outputs it. - console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); - // ... - } + export default class UIAbilityB extends UIAbility { + onCreate(want, launch) { + // UIAbilityB reads name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + ... + } } ``` ### Using globalThis Between UIAbility and ExtensionAbility -To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from ServiceExtensionAbility. +To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from ServiceExtensionAbility. -1. AbilityA stores a string and binds it to globalThis. +1. UIAbilityA stores a string and binds it to globalThis. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { - // AbilityA stores the string "AbilityA" to globalThis. - globalThis.entryAbilityStr = 'AbilityA'; - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { + // UIAbilityA stores the string "UIAbilityA" to globalThis. + globalThis.entryAbilityStr = 'UIAbilityA'; + ... + } } ``` @@ -198,22 +195,21 @@ To implement data synchronization between the UIAbility and ExtensionAbility com import Extension from '@ohos.app.ability.ServiceExtensionAbility' export default class ServiceExtAbility extends Extension { - onCreate(want) { - / / ServiceExtAbility reads name from globalThis and outputs it. - console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); - // ... - } + onCreate(want) { + / / ServiceExtAbility reads name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + ... + } } ``` ### Precautions for Using globalThis - **Figure 2** Precautions for globalThis - +**Figure 2** Precautions for globalThis ![globalThis2](figures/globalThis2.png) -- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if AbilityA and AbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. +- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if UIAbilityA and UIAbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. - This problem does not occur in the FA model because each UIAbility component uses an independent engine. @@ -221,20 +217,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com The following provides an example to describe the object overwritten problem in the stage model. -1. In the AbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. +1. In the UIAbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { - globalThis.context = this.context; // AbilityA stores the context in globalThis. - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { + globalThis.context = this.context; // UIAbilityA stores the context in globalThis. + ... + } } ``` -2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability A. After the AbilityA instance is used, switch it to the background. +2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityA. After the UIAbilityA instance is used, switch it to the background. ```ts @Entry @@ -242,33 +238,29 @@ The following provides an example to describe the object overwritten problem in struct Index { onPageShow() { let ctx = globalThis.context; // Obtain the context from globalThis and use it. - let permissions = ['com.example.permission'] - ctx.requestPermissionsFromUser(permissions,(result) => { - // ... - }); } // Page display. build() { - // ... + ... } } ``` -3. In the AbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the AbilityA file. +3. In the UIAbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the UIAbilityA file. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityB extends UIAbility { - onCreate(want, launch) { - // AbilityB overwrites the context stored by AbilityA in globalThis. - globalThis.context = this.context; - // ... - } + export default class UIAbilityB extends UIAbility { + onCreate(want, launch) { + // UIAbilityB overwrites the context stored by UIAbilityA in globalThis. + globalThis.context = this.context; + ... + } } ``` -4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability B. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in AbilityB. +4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityB. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in UIAbilityB. ```ts @Entry @@ -276,47 +268,43 @@ The following provides an example to describe the object overwritten problem in struct Index { onPageShow() { let ctx = globalThis.context; // Obtain the context from globalThis and use it. - let permissions = ['com.example.permission'] - ctx.requestPermissionsFromUser(permissions,(result) => { - console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); - }); } // Page display. build() { - // ... + ... } } ``` -5. Switch the AbilityB instance to the background and switch the AbilityA instance to the foreground. In this case, AbilityA will not enter the **onCreate()** lifecycle again. +5. Switch the UIAbilityB instance to the background and switch the UIAbilityA instance to the foreground. In this case, UIAbilityA will not enter the **onCreate()** lifecycle again. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { // AbilityA will not enter this lifecycle. - globalThis.context = this.context; - // ... - } + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { // UIAbilityA will not enter this lifecycle. + globalThis.context = this.context; + ... + } } ``` -6. When the page of AbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of AbilityB instead of AbilityA. An error occurs. +6. When the page of UIAbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of UIAbilityB instead of UIAbilityA. An error occurs. ```ts @Entry @Component struct Index { onPageShow() { - let ctx = globalThis.context; // The context in globalThis is the context of AbilityB. - let permissions=['com.example.permission']; - ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown. - console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); - }); + let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB. } // Page display. build() { - // ... + ... } } ``` + +## Using AppStorage or LocalStorage for Data Synchronization + +ArkUI provides AppStorage and LocalStorage to implement application- and UIAbility-level data synchronization, respectively. Both solutions can be used to manage the application state, enhance application performance, and improve user experience. The AppStorage is a global state manager and is applicable when multiple UIAbilities share the same state data. The LocalStorage is a local state manager that manages state data used inside a single UIAbility. They help you control the application state more flexibly and improve the maintainability and scalability of applications. For details, see [State Management of Application-Level Variables](../quick-start/arkts-application-state-management-overview.md). diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md index 148e804f48531f286ecfe395d1ecd03464a5eb45..8e8bbb6535e1d2e0342c6e362b581ff556267ad5 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -15,6 +15,8 @@ This topic describes the UIAbility interaction modes in the following scenarios. - [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result) +- [Starting UIAbility with Window Mode Specified (for System Applications Only)](#starting-uiability-with-window-mode-specified-for-system-applications-only) + - [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) - [Using Call to Implement UIAbility Interaction (for System Applications Only)](#using-call-to-implement-uiability-interaction-for-system-applications-only) @@ -26,113 +28,134 @@ This scenario is possible when an application contains multiple UIAbility compon Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. You are required to start FuncAbility from EntryAbility. -1. In EntryAbility, call **startAbility()** to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). +1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts - let wantInfo = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. - parameters: {// Custom information. - info: 'From the Index page of EntryAbility', - }, + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbility(wantInfo).then(() => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` - -2. Use the FuncAbility lifecycle callback to receive the parameters passed from EntryAbility. + +2. In FuncAbility, use [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to receive the parameters passed in by EntryAbility. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - import Window from '@ohos.window'; export default class FuncAbility extends UIAbility { - onCreate(want, launchParam) { - // Receive the parameters passed by the initiator UIAbility. - let funcAbilityWant = want; - let info = funcAbilityWant?.parameters?.info; - // ... - } + onCreate(want, launchParam) { + // Receive the parameters passed by the initiator UIAbility. + let funcAbilityWant = want; + let info = funcAbilityWant?.parameters?.info; + ... + } } ``` - -3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility. + + > **NOTE** + > + > In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter. + +3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility. ```ts - // context is the AbilityContext of the UIAbility instance to stop. - this.context.terminateSelf((err) => { - // ... + let context = ...; // UIAbilityContext + + // context is the UIAbilityContext of the UIAbility instance to stop. + context.terminateSelf((err) => { + if (err.code) { + console.error(`Failed to terminate Self. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` + + > **NOTE** + > + > When [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called to stop the **UIAbility** instance, the snapshot of the instance is retained by default. That is, the mission corresponding to the instance is still displayed in Recents. If you do not want to retain the snapshot, set **removeMissionAfterTerminate** under the [abilities](../quick-start/module-configuration-file.md#abilities) tag to **true** in the [module.json5 file](../quick-start/module-configuration-file.md) of the corresponding UIAbility. + +4. To stop all UIAbility instances of the application, call **killProcessBySelf()** of [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) to stop all processes of the application. ## Starting UIAbility in the Same Application and Obtaining the Return Result When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility. -1. In EntryAbility, call **startAbilityForResult()** to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). +1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts - let wantInfo = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. - parameters: {// Custom information. - info: 'From the Index page of EntryAbility', - }, + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(wantInfo).then((data) => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + ... }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` - -2. Call **terminateSelfWithResult()** to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. + +2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; let abilityResult = { - resultCode: RESULT_CODE, - want: { - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - moduleName: 'module1', - parameters: { - info: 'From the Index page of FuncAbility', - }, + resultCode: RESULT_CODE, + want: { + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', + parameters: { + info: 'From the Index page of FuncAbility', }, + }, } // context is the AbilityContext of the target UIAbility. - this.context.terminateSelfWithResult(abilityResult, (err) => { - // ... + context.terminateSelfWithResult(abilityResult, (err) => { + if (err.code) { + console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` - -3. After FuncAbility stops itself, EntryAbility uses **startAbilityForResult()** to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. + +3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; - // ... + ... - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(want).then((data) => { - if (data?.resultCode === RESULT_CODE) { - // Parse the information returned by the target UIAbility. - let info = data.want?.parameters?.info; - // ... - } + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + if (data?.resultCode === RESULT_CODE) { + // Parse the information returned by the target UIAbility. + let info = data.want?.parameters?.info; + ... + } }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -145,26 +168,26 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview - Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter. -- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When **startAbility()** is called, the **want** parameter specifies a series of parameters such as [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction). **entities** provides category information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application. +- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the want parameter specifies a series of parameters such as **entities** and **actions**. **entities** provides category information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application. This section describes how to start the UIAbility of another application through implicit Want. -1. Install multiple document applications on your device. In the **module.json5** file of each UIAbility component, configure [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. +1. Install multiple document applications on your device. In the [module.json5 file](../quick-start/module-configuration-file.md) of each UIAbility component, configure **entities** and **actions** under **skills**. ```json { "module": { "abilities": [ { - // ... + ... "skills": [ { "entities": [ - // ... + ... "entity.system.default" ], "actions": [ - // ... + ... "ohos.want.action.viewData" ] } @@ -178,57 +201,62 @@ This section describes how to start the UIAbility of another application through 2. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts - let wantInfo = { - deviceId: '', // An empty deviceId indicates the local device. - // Uncomment the line below if you want to implicitly query data only in the specific bundle. - // bundleName: 'com.example.myapplication', - action: 'ohos.want.action.viewData', - // entities can be omitted. - entities: ['entity.system.default'], + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.viewData', + // entities can be omitted. + entities: ['entity.system.default'], } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbility(wantInfo).then(() => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` - - The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. - - ![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png) -3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. + The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. + ![](figures/uiability-intra-device-interaction.png) + +3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). ```ts - // context is the AbilityContext of the UIAbility instance to stop. - this.context.terminateSelf((err) => { - // ... + let context = ...; // UIAbilityContext + + // context is the UIAbilityContext of the UIAbility instance to stop. + context.terminateSelf((err) => { + if (err.code) { + console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` ## Starting UIAbility of Another Application and Obtaining the Return Result -If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use **startAbilityForResult()**. An example scenario is that the main application needs to start a third-party payment application and obtain the payment result. +If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). An example scenario is that the main application needs to start a third-party payment application and obtain the payment result. -1. In the **module.json5** file of the UIAbility corresponding to the payment application, set [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. +1. In the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility corresponding to the payment application, set **entities** and **actions** under **skills**. ```json { "module": { "abilities": [ { - // ... + ... "skills": [ { "entities": [ - // ... + ... "entity.system.default" ], "actions": [ - // ... + ... "ohos.want.action.editData" ] } @@ -239,68 +267,125 @@ If you want to obtain the return result when using implicit Want to start the UI } ``` -2. Call **startAbilityForResult()** to start the UIAbility of the payment application. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the initiator UIAbility after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. +2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start the UIAbility of the payment application. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the initiator UIAbility after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. ```ts - let wantInfo = { - deviceId: '', // An empty deviceId indicates the local device. - // Uncomment the line below if you want to implicitly query data only in the specific bundle. - // bundleName: 'com.example.myapplication', - action: 'ohos.want.action.editData', - // entities can be omitted. - entities: ['entity.system.default'], + let context = ...; // UIAbilityContext + let want = { + deviceId: '', // An empty deviceId indicates the local device. + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.editData', + // entities can be omitted. + entities: ['entity.system.default'] } - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(wantInfo).then((data) => { - // ... + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + ... }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` - -3. After the payment is finished, call **terminateSelfWithResult()** to stop the payment UIAbility and return the **abilityResult** parameter. + +3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter. ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; let abilityResult = { - resultCode: RESULT_CODE, - want: { - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', - moduleName: 'entry', - parameters: { - payResult: 'OKay', - }, + resultCode: RESULT_CODE, + want: { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + moduleName: 'entry', + parameters: { + payResult: 'OKay', }, + }, } // context is the AbilityContext of the target UIAbility. - this.context.terminateSelfWithResult(abilityResult, (err) => { - // ... + context.terminateSelfWithResult(abilityResult, (err) => { + if (err.code) { + console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); + return; + } }); ``` - -4. Receive the information returned by the payment application in the callback of **startAbilityForResult()**. The value of **RESULT_CODE** must be the same as that returned by **terminateSelfWithResult()**. + +4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). ```ts + let context = ...; // UIAbilityContext const RESULT_CODE: number = 1001; let want = { // Want parameter information. }; - // context is the AbilityContext of the initiator UIAbility. - this.context.startAbilityForResult(want).then((data) => { - if (data?.resultCode === RESULT_CODE) { - // Parse the information returned by the target UIAbility. - let payResult = data.want?.parameters?.payResult; - // ... - } + // context is the UIAbilityContext of the initiator UIAbility. + context.startAbilityForResult(want).then((data) => { + if (data?.resultCode === RESULT_CODE) { + // Parse the information returned by the target UIAbility. + let payResult = data.want?.parameters?.payResult; + ... + } }).catch((err) => { - // ... + console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); }) ``` +## Starting UIAbility with Window Mode Specified (for System Applications Only) + +By specifying the window mode when starting the UIAbility of an application, the application can be displayed in different window modes, which can be full-screen, floating window, or split-screen. + +In full-screen mode, an application occupies the entire screen after being started. Users cannot view other windows or applications. This mode is suitable for an application that requires users to focus on a specific task or UI. + +In floating window mode, an application is displayed on the screen as a floating window after being started. Users can easily switch to other windows or applications. The mode is suitable for an application that requires users to process multiple tasks at the same time. + +In split-screen mode, two applications occupy the entire screen, with one on the left or in the upper part of the screen and the other on the right or in the lower part. This mode helps users improve multi-task processing efficiency. + +The window mode is specified by the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). + +> **NOTE** +> +> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode. +> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities](../quick-start/module-configuration-file.md#abilities) tag in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. + +The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page. + +1. Add the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). +2. Set the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter to **WINDOW_MODE_FLOATING**, indicating that the UIAbility will be displayed in a floating window. + +For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). + +```ts +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + +let context = ...; // UIAbilityContext +let want = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'func', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, +} +let options = { + windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING +}; +// context is the UIAbilityContext of the initiator UIAbility. +context.startAbility(want, options).then(() => { + console.info('Succeeded in starting ability.'); +}).catch((err) => { + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); +}) +``` + +The display effect is shown below. + +![](figures/start-uiability-floating-window.png) ## Starting a Specified Page of UIAbility @@ -313,20 +398,21 @@ When the initiator UIAbility starts another UIAbility, it usually needs to redir ```ts -let wantInfo = { +let context = ...; // UIAbilityContext +let want = { deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'module1', // moduleName is optional. + moduleName: 'func', // moduleName is optional. parameters: {// Custom parameter used to pass the page information. router: 'funcA', }, } -// context is the AbilityContext of the initiator UIAbility. -this.context.startAbility(wantInfo).then(() => { - // ... +// context is the UIAbilityContext of the initiator UIAbility. +context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -341,25 +427,25 @@ import UIAbility from '@ohos.app.ability.UIAbility' import Window from '@ohos.window' export default class FuncAbility extends UIAbility { - funcAbilityWant; - - onCreate(want, launchParam) { - // Receive the parameters passed by the initiator UIAbility. - this.funcAbilityWant = want; - } - - onWindowStageCreate(windowStage: Window.WindowStage) { - // Main window is created. Set a main page for this UIAbility. - let url = 'pages/Index'; - if (this.funcAbilityWant?.parameters?.router) { - if (this.funcAbilityWant.parameters.router === 'funA') { - url = 'pages/Second'; - } - } - windowStage.loadContent(url, (err, data) => { - // ... - }); + funcAbilityWant; + + onCreate(want, launchParam) { + // Receive the parameters passed by the initiator UIAbility. + this.funcAbilityWant = want; + } + + onWindowStageCreate(windowStage: Window.WindowStage) { + // Main window is created. Set a main page for this UIAbility. + let url = 'pages/Index'; + if (this.funcAbilityWant?.parameters?.router) { + if (this.funcAbilityWant.parameters.router === 'funA') { + url = 'pages/Second'; + } } + windowStage.loadContent(url, (err, data) => { + ... + }); + } } ``` @@ -378,11 +464,11 @@ In summary, when a UIAbility instance of application A has been created and the import UIAbility from '@ohos.app.ability.UIAbility' export default class FuncAbility extends UIAbility { - onNewWant(want, launchParam) { - // Receive the parameters passed by the initiator UIAbility. - globalThis.funcAbilityWant = want; - // ... - } + onNewWant(want, launchParam) { + // Receive the parameters passed by the initiator UIAbility. + globalThis.funcAbilityWant = want; + ... + } } ``` @@ -406,25 +492,25 @@ In summary, when a UIAbility instance of application A has been created and the // Page display. build() { - // ... + ... } } ``` > **NOTE** > -> When the [launch type of the target UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the target UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. +> When the [launch type of the target UIAbility](uiability-launch-type.md) is set to **multiton**, a new instance is created each time the target UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. ## Using Call to Implement UIAbility Interaction (for System Applications Only) Call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the call to implement data sharing between two UIAbility instances (CallerAbility and CalleeAbility) through IPC. -The core API used for the call is **startAbilityByCall**, which differs from **startAbility** in the following ways: +The core API used for the call is **startAbilityByCall()**, which differs from **startAbility()** in the following ways: -- **startAbilityByCall** supports UIAbility launch in the foreground and background, whereas **startAbility** supports UIAbility launch in the foreground only. +- **startAbilityByCall()** supports UIAbility launch in the foreground and background, whereas **startAbility()** supports UIAbility launch in the foreground only. -- The CallerAbility can use the caller object returned by **startAbilityByCall** to communicate with the CalleeAbility, but **startAbility** does not provide the communication capability. +- The CallerAbility can use the caller object returned by **startAbilityByCall()** to communicate with the CalleeAbility, but **startAbility()** does not provide the communication capability. Call is usually used in the following scenarios: @@ -432,20 +518,21 @@ Call is usually used in the following scenarios: - Starting the CalleeAbility in the background + **Table 1** Terms used in the call | **Term**| Description| | -------- | -------- | -| CallerAbility | UIAbility that triggers the call.| +| CallerAbility| UIAbility that triggers the call.| | CalleeAbility | UIAbility invoked by the call.| | Caller | Object returned by **startAbilityByCall** and used by the CallerAbility to communicate with the CalleeAbility.| | Callee | Object held by the CalleeAbility to communicate with the CallerAbility.| The following figure shows the call process. - Figure 1 Call process +Figure 1 Call process - ![call](figures/call.png) +![call](figures/call.png) - The CallerAbility uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the CalleeAbility. @@ -463,7 +550,7 @@ The following figure shows the call process. The following table describes the main APIs used for the call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). - **Table 2** Call APIs +**Table 2** Call APIs | API| Description| | -------- | -------- | @@ -487,32 +574,13 @@ The implementation of using the call for UIAbility interaction involves two part For the CalleeAbility, 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 launch type of the UIAbility. - - Set **launchType** of the CalleeAbility 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", - "srcEnty": "./ets/CalleeAbility/CalleeAbility.ts", - "launchType": "singleton", - "description": "$string:CalleeAbility_desc", - "icon": "$media:icon", - "label": "$string:CalleeAbility_label", - "exported": true - }] - ``` - + For example, set the launch type of the CalleeAbility to **singleton**. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). + 2. Import the **UIAbility** module. ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; ``` 3. Define the agreed parcelable data. @@ -522,66 +590,66 @@ For the CalleeAbility, implement the callback to receive data and the methods to ```ts export default class MyParcelable { - num: number = 0 - str: string = "" + num: number = 0; + str: string = ''; - constructor(num, string) { - this.num = num - this.str = string - } + constructor(num, string) { + this.num = num; + this.str = string; + } - marshalling(messageSequence) { - messageSequence.writeInt(this.num) - messageSequence.writeString(this.str) - return true - } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } - unmarshalling(messageSequence) { - this.num = messageSequence.readInt() - this.str = messageSequence.readString() - return true - } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } } ``` 4. Implement **Callee.on** and **Callee.off**. - + The time to register a listener for the CalleeAbility 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 UIAbility and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: - + ```ts const TAG: string = '[CalleeAbility]'; const MSG_SEND_METHOD: string = 'CallSendMsg'; function sendMsgCallback(data) { - console.info('CalleeSortFunc called'); + console.info('CalleeSortFunc called'); - // Obtain the parcelable data sent by the CallerAbility. - let receivedData = new MyParcelable(0, ''); - data.readParcelable(receivedData); - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); + // Obtain the parcelable data sent by the CallerAbility. + let receivedData = new MyParcelable(0, ''); + data.readParcelable(receivedData); + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); - // Process the data. - // Return the parcelable data result to the CallerAbility. - return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); + // Process the data. + // Return the parcelable data result to the CallerAbility. + return new MyParcelable(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.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); - } + export default class CalleeAbility extends UIAbility { + onCreate(want, launchParam) { + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback); + } catch (err) { + console.error(`Failed to register. Code is ${err.code}, message is ${err.message}`); } + } - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD); - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); - } + onDestroy() { + try { + this.callee.off(MSG_SEND_METHOD); + } catch (err) { + console.error(`Failed to unregister. Code is ${err.code}, message is ${err.message}`); } + } } ``` @@ -591,41 +659,41 @@ For the CalleeAbility, implement the callback to receive data and the methods to 1. Import the **UIAbility** module. ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; ``` 2. Obtain the caller interface. - The **context** attribute of the UIAbility implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the UIAbility, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements. + The **UIAbilityContext** attribute implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **UIAbilityContext**, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements. ```ts // Register the onRelease() listener of the CallerAbility. private regOnRelease(caller) { - try { - caller.on("release", (msg) => { - console.info(`caller onRelease is called ${msg}`); - }) - console.info('caller register OnRelease succeed'); - } catch (error) { - console.info(`caller register OnRelease failed with ${error}`); - } + try { + caller.on('release', (msg) => { + console.info(`caller onRelease is called ${msg}`); + }) + console.info('Succeeded in registering on release.'); + } catch (err) { + console.err(`Failed to caller register on release. Code is ${err.code}, message is ${err.message}`); + } } async onButtonGetCaller() { - try { - this.caller = await context.startAbilityByCall({ - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' - }) - if (this.caller === undefined) { - console.info('get caller failed') - return - } - console.info('get caller success') - this.regOnRelease(this.caller) - } catch (error) { - console.info(`get caller failed with ${error}`) + try { + this.caller = await context.startAbilityByCall({ + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }); + if (this.caller === undefined) { + console.info('get caller failed') + return; } + console.info('get caller success') + this.regOnRelease(this.caller) + } (err) { + console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`); + } } ``` diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md index ff904d4f60918a5ceed622840d5a153e52f8d1a4..c7aac3d4bc3acdb2601580646024ec1f8117473f 100644 --- a/en/application-dev/application-models/uiability-launch-type.md +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -17,7 +17,8 @@ The launch type of the UIAbility component refers to the state of the UIAbility Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. -**Figure 1** Demonstration effect in singleton mode +**Figure 1** Demonstration effect in singleton mode + ![uiability-launch-type1](figures/uiability-launch-type1.gif) > **NOTE** @@ -30,11 +31,11 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration ```json { "module": { - // ... + ... "abilities": [ { "launchType": "singleton", - // ... + ... } ] } @@ -56,11 +57,11 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick ```json { "module": { - // ... + ... "abilities": [ { "launchType": "multiton", - // ... + ... } ] } @@ -73,6 +74,7 @@ To use the multiton mode, set **launchType** in the [module.json5 file](../quick The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. **Figure 3** Demonstration effect in specified mode + ![uiability-launch-type3](figures/uiability-launch-type3.gif) For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility. @@ -82,11 +84,11 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ```json { "module": { - // ... + ... "abilities": [ { "launchType": "specified", - // ... + ... } ] } @@ -99,23 +101,24 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili // Configure an independent key for each UIAbility instance. // For example, in the document usage scenario, use the document path as the key. function getInstance() { - // ... + ... } + let context =...; // context is the UIAbilityContext of the initiator UIAbility. let want = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'SpecifiedAbility', - moduleName: 'module1', // moduleName is optional. - parameters: {// Custom information. - instanceKey: getInstance(), - }, + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'SpecifiedAbility', + moduleName: 'specified', // moduleName is optional. + parameters: {// Custom information. + instanceKey: getInstance(), + }, } - // context is the UIAbilityContext of the initiator UIAbility. - this.context.startAbility(want).then(() => { - // ... + + context.startAbility(want).then(() => { + console.info('Succeeded in starting ability.'); }).catch((err) => { - // ... + console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); }) ``` @@ -127,16 +130,16 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili import AbilityStage from '@ohos.app.ability.AbilityStage'; export default class MyAbilityStage extends AbilityStage { - onAcceptWant(want): string { - // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. - // In this example, SpecifiedAbility of module1 is returned. - if (want.abilityName === 'SpecifiedAbility') { - // The returned key string is a custom string. - return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; - } - - return ''; + onAcceptWant(want): string { + // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. + // In this example, SpecifiedAbility of module1 is returned. + if (want.abilityName === 'SpecifiedAbility') { + // The returned key string is a custom string. + return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; } + + return ''; + } } ``` @@ -153,3 +156,4 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili 2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2. 3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3. 4. Return to the home screen and open file A again. UIAbility instance 2 is started. This is because the system automatically matches the key of the UIAbility instance and starts the UIAbility instance that has a matching key. In this example, UIAbility instance 2 has the same key as file A. Therefore, the system pulls back UIAbility instance 2 and focuses it without creating a new instance. + diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md index 57200abb8fbfb625e2e6c8999da5ad817e2e85b4..a61b9ae836904a420877d4d36ad011f82cf5202b 100644 --- a/en/application-dev/application-models/uiability-lifecycle.md +++ b/en/application-dev/application-models/uiability-lifecycle.md @@ -8,8 +8,7 @@ When a user opens, switches, and returns to an application, the UIAbility instan The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below. **Figure 1** UIAbility lifecycle states - -![Ability-Life-Cycle](figures/Ability-Life-Cycle.png) +![Ability-Life-Cycle](figures/Ability-Life-Cycle.png) ## Description of Lifecycle States @@ -22,24 +21,25 @@ The **Create** state is triggered when the UIAbility instance is created during ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Initialize the application. - } - // ... + onCreate(want, launchParam) { + // Initialize the application. + } + ... } ``` +> **NOTE** +> +> [Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. For details, see [Want](want-overview.md). ### WindowStageCreate and WindowStageDestory After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback. -**Figure 2** WindowStageCreate and WindowStageDestory - -![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) +**Figure 2** WindowStageCreate and WindowStageDestory +![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible. @@ -48,25 +48,40 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... - - onWindowStageCreate(windowStage: Window.WindowStage) { - // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible). - try { - windowStage.on('windowStageEvent', (data) => { - console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + - JSON.stringify(data)); - }); - } catch (exception) { - console.error('Failed to enable the listener for window stage event changes. Cause:' + - JSON.stringify(exception)); - }; - - // Set the UI loading. - windowStage.loadContent('pages/Index', (err, data) => { - // ... - }); + ... + + onWindowStageCreate(windowStage: window.WindowStage) { + // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible). + try { + windowStage.on('windowStageEvent', (data) => { + let stageEventType: window.WindowStageEventType = data; + switch (stageEventType) { + case window.WindowStageEventType.SHOWN: // Switch to the foreground. + console.info('windowStage foreground.'); + break; + case window.WindowStageEventType.ACTIVE: // Gain focus. + console.info('windowStage active.'); + break; + case window.WindowStageEventType.INACTIVE: // Lose focus. + console.info('windowStage inactive.'); + break; + case window.WindowStageEventType.HIDDEN: // Switch to the background. + console.info('windowStage background.'); + break; + default: + break; + } + }); + } catch (exception) { + console.error('Failed to enable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); } + + // Set UI loading. + windowStage.loadContent('pages/Index', (err, data) => { + ... + }); + } } ``` @@ -82,18 +97,23 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... - - onWindowStageDestroy() { - // Release UI resources. - // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback. - try { - windowStage.off('windowStageEvent'); - } catch (exception) { - console.error('Failed to disable the listener for window stage event changes. Cause:' + - JSON.stringify(exception)); - }; - } + windowStage: window.WindowStage; + ... + + onWindowStageCreate(windowStage: window.WindowStage) { + this.windowStage = windowStage; + ... + } + + onWindowStageDestroy() { + // Release UIresources. + // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback. + try { + this.windowStage.off('windowStageEvent'); + } catch (err) { + console.error(`Failed to disable the listener for window stage event changes. Code is ${err.code}, message is ${err.message}`); + }; + } } ``` @@ -115,16 +135,16 @@ When the application is switched to the background, you can disable positioning import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - // ... + ... - onForeground() { - // Apply for the resources required by the system or re-apply for the resources released in onBackground(). - } + onForeground() { + // Apply for the resources required by the system or re-apply for the resources released in onBackground(). + } - onBackground() { - // Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, - // for example, saving the status. - } + onBackground() { + // Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, + // for example, saving the status. + } } ``` @@ -137,13 +157,12 @@ The UIAbility instance is destroyed when **terminateSelf()** is called or the us ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - // ... + ... - onDestroy() { - // Release system resources and save data. - } + onDestroy() { + // Release system resources and save data. + } } ``` diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md index 7862f2038fc6c353629bcdc9b3e51cfb5bedb046..5aa0ca79c49bd9f7566e7e0cc1ea977cea8c83d5 100644 --- a/en/application-dev/application-models/uiability-overview.md +++ b/en/application-dev/application-models/uiability-overview.md @@ -11,7 +11,9 @@ The following design philosophy is behind UIAbility: 2. Support for multiple device types and window forms -For details, see [Interpretation of the Application Model](application-model-description.md). +> **NOTE** +> +> For details, see [Interpretation of the Application Model](application-model-description.md). The UIAbility division principles and suggestions are as follows: @@ -33,17 +35,17 @@ To enable an application to properly use a UIAbility component, declare the UIAb ```json { "module": { - // ... + ... "abilities": [ { "name": "EntryAbility", // Name of the UIAbility component. - "srcEnty": "./ets/entryability/EntryAbility.ts", // Code path of the UIAbility component. + "srcEntry": "./ets/entryability/EntryAbility.ts", // Code path of the UIAbility component. "description": "$string:EntryAbility_desc", // Description of the UIAbility component. "icon": "$media:icon", // Icon of the UIAbility component. "label": "$string:EntryAbility_label", // Label of the UIAbility component. "startWindowIcon": "$media:icon", // Index of the icon resource file. "startWindowBackground": "$color:start_window_background", // Index of the background color resource file. - // ... + ... } ] } diff --git a/en/application-dev/application-models/uiability-usage.md b/en/application-dev/application-models/uiability-usage.md index fa8badc6d48c7e550922cb60a15d02eab9cc80b6..46959284ef3bfe179d465f5dae92b6f8538f680a 100644 --- a/en/application-dev/application-models/uiability-usage.md +++ b/en/application-dev/application-models/uiability-usage.md @@ -14,14 +14,14 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - // Main window is created. Set a main page for this ability. - windowStage.loadContent('pages/Index', (err, data) => { - // ... - }); - } + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created. Set a main page for this ability. + windowStage.loadContent('pages/Index', (err, data) => { + ... + }); + } - // ... + ... } ``` @@ -40,15 +40,14 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Obtain the context of the UIAbility instance. - let context = this.context; - - // ... - } + onCreate(want, launchParam) { + // Obtain the context of the UIAbility instance. + let context = this.context; + ... + } } ``` - + - Import the context module and define the **context** variable in the component. ```ts @@ -68,7 +67,7 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC // Page display. build() { - // ... + ... } } ``` @@ -93,7 +92,7 @@ The UIAbility class has its own context, which is an instance of the [UIAbilityC // Page display. build() { - // ... + ... } } ``` diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md index 21c79d517fc237cae9b9bab7d5347ffc82766d5a..cf5cac43999a5efbe59659252b6b3db325cacd8a 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -3,47 +3,49 @@ ## Definition and Usage of Want -[Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. It is used as a parameter of **startAbility()** to specify the startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. For example, when UIAbilityA starts UIAbilityB and needs to transfer some data to UIAbilityB, it can use Want to transfer the data. +[Want](../reference/apis/js-apis-app-ability-want.md) is an object that transfers information between application components. It is often used as a parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). For example, when UIAbilityA needs to start UIAbilityB and transfer some data to UIAbilityB, it can use the **want** parameter in **startAbility()** to transfer the data. -**Figure 1** Want usage +**Figure 1** Want usage -![usage-of-want](figures/usage-of-want.png) +![usage-of-want](figures/usage-of-want.png) ## Types of Want -- **Explicit Want**: A type of Want with **abilityName** and **bundleName** specified when starting an ability. - When there is an explicit object to process the request, the target ability can be started by specifying the bundle name and ability name in Want. Explicit Want is usually used to start a known ability. - +- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an an application component, explicit Want is used. + + Explicit Want is usually used to start a known target application component in the same application. The target application component is started by specifying **bundleName** of the application where the target application component is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target application component. + ```ts let wantInfo = { - deviceId: '', // An empty deviceId indicates the local device. - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', } ``` - -- **Implicit Want**: A type of Want with **abilityName** unspecified when starting the ability. - Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request. - + +- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting the an application component, implicit Want is used. + + Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select. + ```ts let wantInfo = { - // Uncomment the line below if you want to implicitly query data only in the specific bundle. - // bundleName: 'com.example.myapplication', - action: 'ohos.want.action.search', - // entities can be omitted. - entities: [ 'entity.system.browsable' ], - uri: 'https://www.test.com:8080/query/student', - type: 'text/plain', + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.search', + // entities can be omitted. + entities: [ 'entity.system.browsable' ], + uri: 'https://www.test.com:8080/query/student', + type: 'text/plain', }; ``` - + > **NOTE** - > - Depending on the ability matching result, the following cases may be possible when you attempt to use implicit Want to start the ability. - > - No ability is matched. The startup fails. - > - An ability that meets the conditions is matched. That ability is started. - > - Multiple abilities that meet the conditions are matched. A dialog box is displayed for users to select one of them. + > - Depending on the application component matching result, the following cases may be possible when you attempt to use implicit Want to start the application component. + > - No application component is matched. The startup fails. + > - An application component that meets the conditions is matched. That application component is started. + > - Multiple application components that meet the conditions are matched. A dialog box is displayed for users to select one of them. > > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want. > diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md index 73cf20e0ce6ab82ae9e775dd8fb8f43922218b48..3aa1a9fd29495b36a02d155e5d2ad48e94bce5ad 100644 --- a/en/application-dev/application-models/widget-development-fa.md +++ b/en/application-dev/application-models/widget-development-fa.md @@ -20,7 +20,7 @@ Before you get started, it would be helpful if you have a basic understanding of Figure 1 shows the working principles of the widget framework. -**Figure 1** Widget framework working principles in the FA model +**Figure 1** Widget framework working principles in the FA model ![form-extension](figures/form-extension.png) The widget host consists of the following modules: @@ -122,48 +122,48 @@ To create a widget in the FA model, implement the widget lifecycle callbacks. Ge ```ts export default { - onCreate(want) { - console.info('FormAbility onCreate'); - // Called when the widget is created. The widget provider should return the widget data binding class. - 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.info('FormAbility onCastToNormal'); - }, - onUpdate(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.info('FormAbility onUpdate'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - formProvider.updateForm(formId, formData).catch((error) => { - console.info('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. This callback takes effect only for system applications. - console.info('FormAbility onVisibilityChange'); - }, - onEvent(formId, message) { - // If the widget supports event triggering, override this method and implement the trigger. - console.info('FormAbility onEvent'); - }, - onDestroy(formId) { - // Delete widget data. - console.info('FormAbility onDestroy'); - }, - onAcquireFormState(want) { - console.info('FormAbility onAcquireFormState'); - return formInfo.FormState.READY; - }, + onCreate(want) { + console.info('FormAbility onCreate'); + // Called when the widget is created. The widget provider should return the widget data binding class. + 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.info('FormAbility onCastToNormal'); + }, + onUpdate(formId) { + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + console.info('FormAbility onUpdate'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + formProvider.updateForm(formId, formData).catch((error) => { + console.info('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. This callback takes effect only for system applications. + console.info('FormAbility onVisibilityChange'); + }, + onEvent(formId, message) { + // If the widget supports event triggering, override this method and implement the trigger. + console.info('FormAbility onEvent'); + }, + onDestroy(formId) { + // Delete widget data. + console.info('FormAbility onDestroy'); + }, + onAcquireFormState(want) { + console.info('FormAbility onAcquireFormState'); + return formInfo.FormState.READY; + }, } ``` @@ -188,15 +188,15 @@ The widget configuration file is named **config.json**. Find the **config.json** ```json - "js": [{ - "name": "widget", - "pages": ["pages/index/index"], - "window": { - "designWidth": 720, - "autoDesignWidth": true - }, - "type": "form" - }] + "js": [{ + "name": "widget", + "pages": ["pages/index/index"], + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "type": "form" + }] ``` - The **abilities** module in the **config.json** file corresponds to **FormAbility** of the widget. The internal structure is described as follows: @@ -232,7 +232,7 @@ The widget configuration file is named **config.json**. Find the **config.json** "type": "service", "srcLanguage": "ets", "formsEnabled": true, - "formConfigAbility": "ability://com.example.entry.MainAbility", + "formConfigAbility": "ability://com.example.entry.EntryAbility", "forms": [{ "colorMode": "auto", "defaultDimension": "2*2", @@ -275,7 +275,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean } } -// ... +... onCreate(want) { console.info('FormAbility onCreate'); @@ -293,7 +293,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean let formData = formBindingData.createFormBindingData(obj); return formData; } -// ... +... ``` You should override **onDestroy** to implement widget data deletion. @@ -313,14 +313,14 @@ async function deleteFormInfo(formId: string) { } } -// ... +... onDestroy(formId) { console.info('FormAbility onDestroy'); // Delete the persistent widget instance data. // Implement this API based on project requirements. deleteFormInfo(formId); } -// ... +... ``` For details about how to implement persistent data storage, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md). @@ -434,7 +434,7 @@ You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. Thi "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } @@ -452,8 +452,8 @@ You can set router and message events for components on a widget. The router eve 2. Set the router event. - **action**: **"router"**, which indicates a router event. - - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.MainAbility. - - **params**: custom parameters passed to 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 MainAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. + - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.EntryAbility. + - **params**: custom parameters passed to 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. @@ -529,7 +529,7 @@ The following is an example: "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } diff --git a/en/application-dev/application-models/widget-development-stage.md b/en/application-dev/application-models/widget-development-stage.md deleted file mode 100644 index 3e542956072a31fbc8dbca097ae264dfe8ebfc5f..0000000000000000000000000000000000000000 --- a/en/application-dev/application-models/widget-development-stage.md +++ /dev/null @@ -1,599 +0,0 @@ -# FormExtensionAbility (Widget) - - -## Widget Overview - -FormExtensionAbility provides a service widget (also called widget), which 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 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. - -- 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. - - -## Working Principles - -Figure 1 shows the working principles of the widget framework. - -**Figure 1** Widget framework working principles in the stage model -![form-extension](figures/form-extension.png) - -The widget host consists of the following modules: - -- Widget usage: provides operations such as creating, deleting, or updating a widget. - -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. - -The Widget Manager consists of the following modules: - -- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. - -- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. - -- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. - -- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. - -- Communication adapter: communicates with the widget host and provider through RPCs. - -The widget provider consists of the following modules: - -- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. - -- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. - -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. - -> **NOTE** -> -> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. - - -## Available APIs - -The **FormExtensionAbility** class has the following APIs. For details, see [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). - -| API| Description| -| -------- | -------- | -| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| -| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| -| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget has been updated.| -| onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| -| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| -| onRemoveForm(formId: string): void| Called to notify the widget provider that a widget has been destroyed.| -| onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is updated.| -| onShareForm?(formId: string): { [key: string]: any }| Called by the widget provider to receive shared widget data.| - -The **FormExtensionAbility** class also has a member context, that is, the FormExtensionContext class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). - -| API| Description| -| -------- | -------- | -| startAbility(want: Want, callback: AsyncCallback<void>): void | Starts UIAbility of the application to which a widget belongs. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications. You must apply for the permission to use the API.)| -| startAbility(want: Want): Promise<void> | Starts UIAbility of the application to which a widget belongs. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications. You must apply for the permission to use the API.)| - -The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). - -| 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.| - -The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis/js-apis-app-form-formBindingData.md). - -| API| Description| -| -------- | -------- | -| createFormBindingData(obj?: Object \ string): FormBindingData| | Creates a **FormBindingData** object.| - - -## How to Develop - -The widget provider development based on the [stage model](stage-model-development-overview.md) involves the following key steps: - -- [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility. - -- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file. - -- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. - -- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. - -- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. - -- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget. - - -### Creating a FormExtensionAbility Instance - -To create a widget in the stage model, implement the lifecycle callbacks of **FormExtensionAbility**. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). - -1. Import related modules to **EntryFormAbility.ts**. - - ```ts - import FormExtension from '@ohos.app.form.FormExtensionAbility'; - import formBindingData from '@ohos.app.form.formBindingData'; - import formInfo from '@ohos.app.form.formInfo'; - import formProvider from '@ohos.app.form.formProvider'; - import dataStorage from '@ohos.data.storage'; - ``` - -2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. - - ```ts - export default class EntryFormAbility extends FormExtension { - onAddForm(want) { - console.info('[EntryFormAbility] onAddForm'); - // Called when the widget is created. The widget provider should return the widget data binding class. - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - } - onCastToNormalForm(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.info('[EntryFormAbility] onCastToNormalForm'); - } - onUpdateForm(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.info('[EntryFormAbility] onUpdateForm'); - let obj = { - "title": "titleOnUpdate", - "detail": "detailOnUpdate" - }; - let formData = formBindingData.createFormBindingData(obj); - formProvider.updateForm(formId, formData).catch((error) => { - console.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); - }); - } - onChangeFormVisibility(newStatus) { - // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. - console.info('[EntryFormAbility] onChangeFormVisibility'); - } - onFormEvent(formId, message) { - // If the widget supports event triggering, override this method and implement the trigger. - console.info('[EntryFormAbility] onFormEvent'); - } - onRemoveForm(formId) { - // Delete widget data. - console.info('[EntryFormAbility] onRemoveForm'); - } - onConfigurationUpdate(config) { - console.info('[EntryFormAbility] nConfigurationUpdate, config:' + JSON.stringify(config)); - } - onAcquireFormState(want) { - return formInfo.FormState.READY; - } - } - ``` - -> **NOTE** -> -> FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. - -### Configuring the Widget Configuration File - -1. Configure ExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For a FormExtensionAbility, 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 - { - "module": { - // ... - "extensionAbilities": [ - { - "name": "EntryFormAbility", - "srcEntrance": "./ets/entryformability/EntryFormAbility.ts", - "label": "$string:EntryFormAbility_label", - "description": "$string:EntryFormAbility_desc", - "type": "form", - "metadata": [ - { - "name": "ohos.extension.form", - "resource": "$profile:form_config" - } - ] - } - ] - } - } - ``` - -2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if resource is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal field structure. - **Table 1** Widget profile configuration file - - | Field| Description| Data Type| Initial Value Allowed| - | -------- | -------- | -------- | -------- | - | name | Class name of a widget. The value is a string with a maximum of 127 bytes.| String| No| - | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| - | src | Full path of the UI code corresponding to the widget.| String| No| - | window | Window-related configurations.| Object| Yes| - | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean| No| - | colorMode | Color mode of the widget.
**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": { - "designWidth": 720, - "autoDesignWidth": true - }, - "colorMode": "auto", - "isDefault": true, - "updateEnabled": true, - "scheduledUpdateTime": "10:30", - "updateDuration": 1, - "defaultDimension": "2*2", - "supportDimensions": [ - "2*2" - ] - } - ] - } - ``` - - -### 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. - - -```ts -const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; -async function storeFormInfo(formId: string, formName: string, tempFlag: boolean) { - // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored. - let formInfo = { - "formName": formName, - "tempFlag": tempFlag, - "updateCount": 0 - }; - try { - const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); - // Put the widget information. - await storage.put(formId, JSON.stringify(formInfo)); - console.info(`[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`); - await storage.flush(); - } catch (err) { - console.error(`[EntryFormAbility] failed to storeFormInfo, err: ${JSON.stringify(err)}`); - } -} - -export default class EntryFormAbility extends FormExtension { - // ... - onAddForm(want) { - console.info('[EntryFormAbility] onAddForm'); - - 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 instance acquisition and update. - // Implement this API based on project requirements. - storeFormInfo(formId, formName, tempFlag); - - let obj = { - "title": "titleOnCreate", - "detail": "detailOnCreate" - }; - let formData = formBindingData.createFormBindingData(obj); - return formData; - } -} -``` - -You should override **onRemoveForm** to implement widget data deletion. - - -```ts -const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; -async function deleteFormInfo(formId: string) { - try { - const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); - // Delete the widget information. - await storage.delete(formId); - console.info(`[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`); - await storage.flush(); - } catch (err) { - console.error(`[EntryFormAbility] failed to deleteFormInfo, err: ${JSON.stringify(err)}`); - } -} - -// ... - -export default class EntryFormAbility extends FormExtension { - // ... - onRemoveForm(formId) { - console.info('[EntryFormAbility] onRemoveForm'); - // Delete the persistent widget instance data. - // Implement this API based on project requirements. - deleteFormInfo(formId); - } -} -``` - -For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.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. - - -```ts -onUpdateForm(formId) { - // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. - console.info('[EntryFormAbility] onUpdateForm'); - 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.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); - }); -} -``` - - -### Developing the Widget UI Page - -You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below. - -![widget-development-stage](figures/widget-development-stage.png) - -> **NOTE** -> -> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. - -- HML: uses web-like paradigm components to describe the widget page information. - - ```html -
- -
- -
-
- {{title}} - {{detail}} -
-
-
- ``` - -- CSS: defines style information about the web-like paradigm components in HML. - - ```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: defines data and event interaction on the widget UI page. - - ```json - { - "data": { - "title": "TitleDefault", - "detail": "TextDefault" - }, - "actions": { - "routerEvent": { - "action": "router", - "abilityName": "EntryAbility", - "params": { - "message": "add detail" - } - } - } - } - ``` - - -### 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**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility. - - **params**: custom parameters passed to 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 main ability 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 **onFormEvent()**. - -The following is an example: - -- 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": { - "info": "router info", - "message": "router message" - } - }, - "messageEvent": { - "action": "message", - "params": { - "detail": "message detail" - } - } - } - } - ``` - -- Receive the router event and obtain parameters in UIAbility. - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility' - - export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - // Obtain the info parameter passed in the router event. - if (want.parameters.info === "router info") { - // Do something. - // console.log("router info:" + want.parameters.info) - } - // Obtain the message parameter passed in the router event. - if (want.parameters.message === "router message") { - // Do something. - // console.log("router message:" + want.parameters.message) - } - } - // ... - }; - ``` - -- Receive the message event in FormExtensionAbility and obtain parameters. - - ```ts - import FormExtension from '@ohos.app.form.FormExtensionAbility'; - - export default class FormAbility extends FormExtension { - // ... - onFormEvent(formId, message) { - // Obtain the detail parameter passed in the message event. - let msg = JSON.parse(message) - if (msg.params.detail === "message detail") { - // Do something. - // console.log("message info:" + msg.params.detail) - } - } - // ... - }; - ``` - diff --git a/en/application-dev/application-models/widget-switch.md b/en/application-dev/application-models/widget-switch.md index 0de83a6593f521e3b51b84dea5ff275e7ee5450f..2f8a0a41b2e1b20824a19d08c98f67e39cd05df6 100644 --- a/en/application-dev/application-models/widget-switch.md +++ b/en/application-dev/application-models/widget-switch.md @@ -11,7 +11,7 @@ Widget switching involves the following parts: | Configuration Item | FA Model | Stage Model | | ---------------- | ------------------------------------------- | ------------------------------------------------------------ | | Configuration item location | **formAbility** and **forms** are in the **config.json** file.| **extensionAbilities** (configuration for **formExtensionAbility**) is in the **module.json5** file in the level-1 directory, and **forms** (configuration for **forms** contained in **formExtensionAbility**) is in the **form_config.json** file in the level-2 directory.| -| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEnty**, with the file name. | +| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEntry**, with the file name. | | Programming language | **srcLanguage** can be set to **js** or **ets**. | This configuration item is unavailable. Only ets is supported. | | Whether to enable widgets | formsEnabled | This configuration item is unavailable. The setting of **type** set to **form** means that the widgets are enabled. | | Ability type | type: service | type: form | @@ -32,7 +32,7 @@ Figure 2 Widget configuration differences | Item| FA Model| Stage Model| | -------- | -------- | -------- | -| Entry file| **form.ts** in the directory pointed to by **srcPath**| File pointed to by **srcEnty**| +| Entry file| **form.ts** in the directory pointed to by **srcPath**| File pointed to by **srcEntry**| | Lifecycle| export default| import FormExtension from '\@ohos.app.form.FormExtensionAbility';
export default class FormAbility extends FormExtension| diff --git a/en/application-dev/application-models/windowextensionability.md b/en/application-dev/application-models/windowextensionability.md index a307a1da5e1c21e11b71d054b8300bb35ddf0522..975b350a47966341bd9c60046f9b69ee011f9ae3 100644 --- a/en/application-dev/application-models/windowextensionability.md +++ b/en/application-dev/application-models/windowextensionability.md @@ -43,7 +43,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i onWindowReady(window) { window.loadContent('WindowExtAbility/pages/index1').then(() => { window.getProperties().then((pro) => { - console.log("WindowExtension " + JSON.stringify(pro)); + console.info("WindowExtension " + JSON.stringify(pro)); }) window.show(); }) @@ -59,7 +59,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i } ``` -4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEnty** to the code path of the ExtensionAbility component. +4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntry** to the code path of the ExtensionAbility component. ```json { @@ -67,7 +67,7 @@ To implement an embedded application, manually create a WindowExtensionAbility i "extensionAbilities": [ { "name": "WindowExtAbility", - "srcEnty": "./ets/WindowExtAbility/WindowExtAbility.ts", + "srcEntry": "./ets/WindowExtAbility/WindowExtAbility.ts", "icon": "$media:icon", "description": "WindowExtension", "type": "window", diff --git a/en/application-dev/media/audio-playback-concurrency.md b/en/application-dev/media/audio-playback-concurrency.md index 0b36594f6bef62c7ba7588bc8977af67609a6c9d..fee7e776d68914ad376e01b8fe40ee84e3da4224 100644 --- a/en/application-dev/media/audio-playback-concurrency.md +++ b/en/application-dev/media/audio-playback-concurrency.md @@ -14,7 +14,7 @@ The audio interruption policy determines the operations (for example, pause, res Two audio interruption modes, specified by [InterruptMode](../reference/apis/js-apis-audio.md#interruptmode9), are preset in the audio interruption policy: -- **SHARED_MODE**: Multiple audio streams created by an application share one audio focus. The concurrency rules between these audio streams are determined by the application, without the use of the audio interruption policy. However, if another application needs to play audio while one of these audio streams is being played, the audio interruption policy is triggered. +- **SHARE_MODE**: Multiple audio streams created by an application share one audio focus. The concurrency rules between these audio streams are determined by the application, without the use of the audio interruption policy. However, if another application needs to play audio while one of these audio streams is being played, the audio interruption policy is triggered. - **INDEPENDENT_MODE**: Each audio stream created by an application has an independent audio focus. When multiple audio streams are played concurrently, the audio interruption policy is triggered. diff --git a/en/application-dev/media/audio-playback-overview.md b/en/application-dev/media/audio-playback-overview.md index d17970d6de9b8b238db74d971ad5f58c605462eb..5ef7a6f9c4d08719a71c9e07f34fa1104802fcc6 100644 --- a/en/application-dev/media/audio-playback-overview.md +++ b/en/application-dev/media/audio-playback-overview.md @@ -8,7 +8,7 @@ OpenHarmony provides multiple classes for you to develop audio playback applicat - [AudioRenderer](using-audiorenderer-for-playback.md): provides ArkTS and JS API to implement audio output. It supports only the PCM format and requires applications to continuously write audio data. The applications can perform data preprocessing, for example, setting the sampling rate and bit width of audio files, before audio input. This class can be used to develop more professional and diverse playback applications. To use this class, you must have basic audio processing knowledge. -- [OpenSLES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio output in PCM format and is applicable to playback applications that are ported from other embedded platforms or that implements audio output at the native layer. +- [OpenSL ES](using-opensl-es-for-playback.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio output in PCM format and is applicable to playback applications that are ported from other embedded platforms or that implements audio output at the native layer. - [TonePlayer](using-toneplayer-for-playback.md): provides ArkTS and JS API to implement the playback of dialing tones and ringback tones. It can be used to play the content selected from a fixed type range, without requiring the input of media assets or audio data. This class is application to specific scenarios where dialing tones and ringback tones are played. is available only to system applications. diff --git a/en/application-dev/media/audio-recording-overview.md b/en/application-dev/media/audio-recording-overview.md index 698255fddd78d98f9e635b16b3db94e6980bd4a0..2c6fb6fe5b8ffd0e82478d450e64bfc0e10257c6 100644 --- a/en/application-dev/media/audio-recording-overview.md +++ b/en/application-dev/media/audio-recording-overview.md @@ -8,7 +8,7 @@ OpenHarmony provides multiple classes for you to develop audio recording applica - [AudioCapturer](using-audiocapturer-for-recording.md): provides ArkTS and JS API to implement audio input. It supports only the PCM format and requires applications to continuously read audio data. The application can perform data processing after audio output. This class can be used to develop more professional and diverse recording applications. To use this class, you must have basic audio processing knowledge. -- [OpenSLES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio input in PCM format and is applicable to recording applications that are ported from other embedded platforms or that implements audio input at the native layer. +- [OpenSL ES](using-opensl-es-for-recording.md): provides a set of standard, cross-platform, yet unique native audio APIs. It supports audio input in PCM format and is applicable to recording applications that are ported from other embedded platforms or that implements audio input at the native layer. ## Precautions for Developing Audio Recording Applications diff --git a/en/application-dev/media/figures/audiocapturer-status-change.png b/en/application-dev/media/figures/audiocapturer-status-change.png index aadbc4fb6470b7cdc0f399ee5954a96c01a7f7c3..ff76a8414f7a254af7d2796e44f2c2555dc9185f 100644 Binary files a/en/application-dev/media/figures/audiocapturer-status-change.png and b/en/application-dev/media/figures/audiocapturer-status-change.png differ diff --git a/en/application-dev/media/media-application-overview.md b/en/application-dev/media/media-application-overview.md index d350482e61e7bc9659054b0426c10ce07da88045..6ca7bbd61bccab668076da76841e785d1918abe9 100644 --- a/en/application-dev/media/media-application-overview.md +++ b/en/application-dev/media/media-application-overview.md @@ -2,7 +2,7 @@ ## Multimedia Subsystem Architecture -The multimedia subsystem provides the capability of processing users' visual and auditory information. For example, it can be used to collect, compress, store, decompress, and play audio and video information. Based on the type of media information to process, the media system is usually divided into four modules: audio, media, camera, and image. +The multimedia subsystem provides the capability of processing users' visual and auditory information. For example, it can be used to collect, compress, store, decompress, and play audio and video information. Based on the type of media information to process, the multimedia subsystem subsystem is usually divided into four modules: audio, media, camera, and image. As shown in the figure below, the multimedia subsystem provides APIs for developing audio/video, camera, and gallery applications, and provides adaptation and acceleration for different hardware chips. In the middle part, it provides core media functionalities and management mechanisms in the form of services. diff --git a/en/application-dev/media/using-audiorenderer-for-playback.md b/en/application-dev/media/using-audiorenderer-for-playback.md index 11934e669813fa7a89ceef43bd2c3795db6bad75..d72637819259e3752a33b37d6f645786793cfc38 100644 --- a/en/application-dev/media/using-audiorenderer-for-playback.md +++ b/en/application-dev/media/using-audiorenderer-for-playback.md @@ -151,9 +151,6 @@ export default class AudioRendererDemo { console.info(`${TAG}: creating AudioRenderer success`); this.renderModel = renderer; this.renderModel.on('stateChange', (state) => { // Set the events to listen for. A callback is invoked when the AudioRenderer is switched to the specified state. - if (state == 1) { - console.info('audio renderer state is: STATE_PREPARED'); - } if (state == 2) { console.info('audio renderer state is: STATE_RUNNING'); } diff --git a/en/application-dev/media/using-avsession-developer.md b/en/application-dev/media/using-avsession-developer.md index 077f0b956a5fb6abaf26c647132bdbb81e78fc63..09951965228d31f615dbf0c51578455585b30382 100644 --- a/en/application-dev/media/using-avsession-developer.md +++ b/en/application-dev/media/using-avsession-developer.md @@ -1,6 +1,6 @@ # AVSession Provider -An audio and video application needs to access the AVSession service as a provider in order to display media information in the controller (for example, Media Controller) and respond to control commands delivered by the controller. +An audio and video application needs to access the AVSession service as a provider in order to display media information in the controller (for example, Media Controller) and respond to playback control commands delivered by the controller. ## Basic Concepts @@ -14,22 +14,22 @@ The table below lists the key APIs used by the provider. The APIs use either a c For details, see [AVSession Management](../reference/apis/js-apis-avsession.md). -| API| Description| +| API| Description| | -------- | -------- | -| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback<AVSession>): void | Creates an AVSession.
Only one AVSession can be created for a UIAbility.| -| setAVMetadata(data: AVMetadata, callback: AsyncCallback<void>): void | Sets AVSession metadata.| -| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback<void>): void | Sets the AVSession playback state.| -| setLaunchAbility(ability: WantAgent, callback: AsyncCallback<void>): void | Starts a UIAbility.| -| getController(callback: AsyncCallback<AVSessionController>): void | Obtains the controller of the AVSession.| -| activate(callback: AsyncCallback<void>): void | Activates the AVSession.| -| destroy(callback: AsyncCallback<void>): void | Destroys the AVSession.| +| createAVSession(context: Context, tag: string, type: AVSessionType, callback: AsyncCallback<AVSession>): void | Creates an AVSession.
Only one AVSession can be created for a UIAbility.| +| setAVMetadata(data: AVMetadata, callback: AsyncCallback<void>): void | Sets AVSession metadata.| +| setAVPlaybackState(state: AVPlaybackState, callback: AsyncCallback<void>): void | Sets the AVSession playback state.| +| setLaunchAbility(ability: WantAgent, callback: AsyncCallback<void>): void | Starts a UIAbility.| +| getController(callback: AsyncCallback<AVSessionController>): void | Obtains the controller of the AVSession.| +| activate(callback: AsyncCallback<void>): void | Activates the AVSession.| +| destroy(callback: AsyncCallback<void>): void | Destroys the AVSession.| ## How to Develop To enable an audio and video application to access the AVSession service as a provider, proceed as follows: 1. Call an API in the **AVSessionManager** class to create and activate an **AVSession** object. - + ```ts import AVSessionManager from '@ohos.multimedia.avsession'; // Import the AVSessionManager module. @@ -46,10 +46,10 @@ To enable an audio and video application to access the AVSession service as a pr - AVPlaybackState The controller will call an API in the **AVSessionController** class to obtain the information and display or process the information. - + ```ts async setSessionInfo() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; // The player logic that triggers changes in the session metadata and playback state is omitted here. // Set necessary session metadata. @@ -80,13 +80,13 @@ To enable an audio and video application to access the AVSession service as a pr 3. Set the UIAbility to be started by the controller. The UIAbility configured here is started when a user operates the UI of the controller, for example, clicking a widget in Media Controller. The UIAbility is set through the **WantAgent** API. For details, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). - + ```ts import WantAgent from "@ohos.app.ability.wantAgent"; ``` ```ts - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; let wantAgentInfo = { wants: [ @@ -104,14 +104,14 @@ To enable an audio and video application to access the AVSession service as a pr }) ``` -4. Listen for control commands delivered by the controller, for example, Media Controller. +4. Listen for playback control commands delivered by the controller, for example, Media Controller. > **NOTE** > - > After the provider registers a listener for the control command event, the event will be reflected in **getValidCommands()** of the controller. In other words, the controller determines that the command is valid and triggers the corresponding event as required. To ensure that the control commands delivered by the controller can be executed normally, the provider should not use a null implementation for listening. - + > After the provider registers a listener for playback control commands, the commands will be reflected in **getValidCommands()** of the controller. In other words, the controller determines that the command is valid and triggers the corresponding event as required. To ensure that the playback control commands delivered by the controller can be executed normally, the provider should not use a null implementation for listening. + ```ts async setListenerForMesFromController() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; // Generally, logic processing on the player is implemented in the listener. // After the processing is complete, use the setter to synchronize the playback information. For details, see the code snippet above. @@ -140,16 +140,16 @@ To enable an audio and video application to access the AVSession service as a pr ``` 5. Obtain an **AVSessionController** object for this **AVSession** object for interaction. - + ```ts async createControllerFromSession() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; // Obtain an AVSessionController object for this AVSession object. let controller: AVSessionManager.AVSessionController = await session.getController(); - // The AVSessionController object can interact with the AVSession object, for example, by delivering a control command. + // The AVSessionController object can interact with the AVSession object, for example, by delivering a playback control command. let avCommand: AVSessionManager.AVControlCommand = {command:'play'}; controller.sendControlCommand(avCommand); @@ -164,11 +164,12 @@ To enable an audio and video application to access the AVSession service as a pr ``` 6. When the audio and video application exits and does not need to continue playback, cancel the listener and destroy the **AVSession** object. - The code snippet below is used for canceling the listener for control commands: + + The code snippet below is used for canceling the listener for playback control commands: ```ts async unregisterSessionListener() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; // Cancel the listener of the AVSession object. @@ -180,11 +181,11 @@ To enable an audio and video application to access the AVSession service as a pr } ``` - The code snippet below is used for destroying the AVSession object: - + The code snippet below is used for destroying the AVSession object: + ```ts async destroySession() { - // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. + // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet in step 1. let session: AVSessionManager.AVSession = ALLREADY_CREATE_A_SESSION; // Destroy the AVSession object. session.destroy(function (err) { diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 8c9e825557ee1d899e7004fb9109ff7b7ea7a5da..db930ccbe8cc14f368b9e16d29b556074e981482 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -15,10 +15,11 @@ import bundle from '@ohos.bundle'; | Required Permissions | Permission Level | Description | |--------------------------------------------|--------------|---------------| +| ohos.permission.CHANGE_ABILITY_ENABLED_STATE | system_basic | Permission to enable or disable an application or ability.| | ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle.| | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles. | | ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall bundles. | -| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status. | +| ohos.permission.REMOVE_CACHE_FILES | system_basic | Permission to clear cache files of a bundle.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -186,6 +187,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleFlag = 0; let userId = 100; + bundle.getAllBundleInfo(bundleFlag, userId) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -310,7 +312,7 @@ SystemCapability.BundleManager.BundleFramework let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { - "userId" : 100 + "userId": 100 }; bundle.getBundleInfo(bundleName, bundleFlags, options) .then((data) => { @@ -360,7 +362,6 @@ bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { }) ``` - ## bundle.getBundleInfodeprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo) instead. @@ -394,7 +395,7 @@ SystemCapability.BundleManager.BundleFramework let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { - "userId" : 100 + "userId": 100 }; bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { if (err) { @@ -425,7 +426,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Return value** @@ -461,7 +462,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -498,7 +499,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -539,7 +540,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -583,7 +584,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -625,7 +626,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -670,7 +671,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -698,7 +699,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -720,7 +721,7 @@ let flag = bundle.BundleFlag.GET_ABILITY_INFO_WITH_PERMISSION; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.getAbilityInfo(want, flag, userId).then((abilityInfo) => { @@ -753,7 +754,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -793,7 +794,7 @@ SystemCapability.BundleManager.BundleFramework **System API** -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -903,7 +904,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo) instead. -getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; +getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback\\>): void; Obtains the information about all applications of the current user. This API uses an asynchronous callback to return the result. @@ -1006,7 +1007,6 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { }) ``` - ## bundle.getAbilityInfodeprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead. @@ -1042,7 +1042,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1081,7 +1081,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -1126,7 +1126,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityLabel(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1165,7 +1165,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -1203,7 +1203,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ bundle.isAbilityEnabled(abilityInfo).then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1236,7 +1236,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ bundle.isAbilityEnabled(abilityInfo, (err, data) => { if (err) { @@ -1355,7 +1355,7 @@ let bundleFlags = 0; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, userId) .then((data) => { @@ -1401,7 +1401,7 @@ let bundleFlags = 0; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { if (err) { @@ -1444,7 +1444,7 @@ SystemCapability.BundleManager.BundleFramework let bundleFlags = 0; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { if (err) { @@ -1635,7 +1635,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityIcon(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1675,7 +1675,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index d022dd0177356fbbcd1d81031f1b505d009136c6..18a163c13d7d6b249dd0a1a44dbe8978d94edc16 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -4,7 +4,7 @@ The **AbilityDelegatorRegistry** module provides APIs for storing the global reg > **NOTE** > -> The APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index 677884b754c5896b1a6af853d8a4df54355bbb85..6c54d957fae9711c9e48a1f0729e99cea5c532e8 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -4,7 +4,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying > **NOTE** > -> The APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-application-missionManager.md b/en/application-dev/reference/apis/js-apis-application-missionManager.md index 9ad6d14eec8aea3f597e1d7f2b425f29dc0ccc54..fcaa86e787e6ceb9756b58a84ea7c896b33a51e9 100644 --- a/en/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -4,7 +4,7 @@ The **missionManager** module provides APIs to lock, unlock, and clear missions, > **NOTE** > -> The APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index 5a014e7cfe5618c7e31741b43d32ce743d86a0b2..737c9f1dbf05e30e2f84e185b89e804642b0c39f 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -726,7 +726,7 @@ Checks whether this **Buffer** instance contains the specified value. | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| **Return value** @@ -758,7 +758,7 @@ Obtains the index of the first occurrence of the specified value in this **Buffe | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| **Return value** @@ -815,7 +815,7 @@ Obtains the index of the last occurrence of the specified value in this **Buffer | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| **Return value** @@ -838,7 +838,7 @@ console.log(buf.lastIndexOf('buffer').toString()); // Print: 17 readBigInt64BE(offset?: number): bigint -Reads a signed, big-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, big-endian, signed big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -872,14 +872,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigInt64BE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigInt64BE(0x0102030405060708n, 0); +let result = buf1.writeBigInt64BE(BigInt(0x0102030405060708), 0); ``` ### readBigInt64LE readBigInt64LE(offset?: number): bigint -Reads a signed, little-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, little-endian, signed big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -913,14 +913,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigInt64LE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigInt64BE(0x0102030405060708n, 0); +let result = buf1.writeBigInt64BE(BigInt(0x0102030405060708), 0); ``` ### readBigUInt64BE readBigUInt64BE(offset?: number): bigint -Reads an unsigned, big-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, big-endian, unsigned big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -954,14 +954,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigUInt64BE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); +let result = buf1.writeBigUInt64BE(BigInt(0xdecafafecacefade), 0); ``` ### readBigUInt64LE readBigUInt64LE(offset?: number): bigint -Reads an unsigned, little-endian 64-bit big integer from this **Buffer** instance at the specified offset. +Reads a 64-bit, little-endian, unsigned big integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -995,14 +995,14 @@ let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, console.log(buf.readBigUInt64LE(0).toString()); let buf1 = buffer.allocUninitializedFromPool(8); -let result = buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); +let result = buf1.writeBigUInt64BE(BigInt(0xdecafafecacefade), 0); ``` ### readDoubleBE readDoubleBE(offset?: number): number -Reads a 64-bit, big-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 64-bit, big-endian, double-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1042,7 +1042,7 @@ let result = buf1.writeDoubleBE(123.456, 0); readDoubleLE(offset?: number): number -Reads a 64-bit, little-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 64-bit, little-endian, double-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1082,7 +1082,7 @@ let result = buf1.writeDoubleLE(123.456, 0); readFloatBE(offset?: number): number -Reads a 32-bit, big-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 32-bit, big-endian, single-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1122,7 +1122,7 @@ let result = buf1.writeFloatBE(0xcabcbcbc, 0); readFloatLE(offset?: number): number -Reads a 32-bit, little-endian floating-point number from this **Buffer** instance at the specified offset. +Reads a 32-bit, little-endian, single-precision floating-point number from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1162,7 +1162,7 @@ let result = buf1.writeFloatLE(0xcabcbcbc, 0); readInt8(offset?: number): number -Reads a signed 8-bit integer from this **Buffer** instance at the specified offset. +Reads a 8-bit signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1203,7 +1203,7 @@ let result = buf1.writeInt8(0x12); readInt16BE(offset?: number): number -Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, big-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1243,7 +1243,7 @@ let result = buf1.writeInt16BE(0x1234, 0); readInt16LE(offset?: number): number -Reads a signed, little-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, little-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1283,7 +1283,7 @@ let result = buf1.writeInt16BE(0x1234, 0); readInt32BE(offset?: number): number -Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, big-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1323,7 +1323,7 @@ let result = buf1.writeInt32BE(0x12345678, 0); readInt32LE(offset?: number): number -Reads a signed, little-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, little-endian, signed integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1449,7 +1449,7 @@ let result = buf1.writeIntLE(0x123456789011, 0, 6); readUInt8(offset?: number): number -Reads an unsigned 8-bit integer from this **Buffer** instance at the specified offset. +Reads a 8-bit unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1491,7 +1491,7 @@ let result = buf1.writeUInt8(0x42); readUInt16BE(offset?: number): number -Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, big-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1533,7 +1533,7 @@ let result = buf1.writeUInt16BE(0x1234, 0); readUInt16LE(offset?: number): number -Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at the specified offset. +Reads a 16-bit, little-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1575,7 +1575,7 @@ let result = buf1.writeUInt16LE(0x1234, 0); readUInt32BE(offset?: number): number -Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, big-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -1616,7 +1616,7 @@ let result = buf1.writeUInt32BE(0x12345678, 0); readUInt32LE(offset?: number): number -Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at the specified offset. +Reads a 32-bit, little-endian, unsigned integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2013,7 +2013,7 @@ let length = buffer1.write('abcd', 8); writeBigInt64BE(value: bigint, offset?: number): number -Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, big-endian, signed big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2045,14 +2045,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigInt64BE(0x0102030405060708n, 0); +let result = buf.writeBigInt64BE(BigInt(0x0102030405060708), 0); ``` ### writeBigInt64LE writeBigInt64LE(value: bigint, offset?: number): number -Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, little-endian, signed big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2084,14 +2084,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigInt64LE(0x0102030405060708n, 0); +let result = buf.writeBigInt64LE(BigInt(0x0102030405060708), 0); ``` ### writeBigUInt64BE writeBigUInt64BE(value: bigint, offset?: number): number -Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, big-endian, unsigned big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2123,14 +2123,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigUInt64BE(0xdecafafecacefaden, 0); +let result = buf.writeBigUInt64BE(BigInt(0xdecafafecacefade), 0); ``` ### writeBigUInt64LE writeBigUInt64LE(value: bigint, offset?: number): number -Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset. +Writes a 64-bit, little-endian, unsigned big integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2162,14 +2162,14 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); -let result = buf.writeBigUInt64LE(0xdecafafecacefaden, 0); +let result = buf.writeBigUInt64LE(BigInt(0xdecafafecacefade), 0); ``` ### writeDoubleBE writeDoubleBE(value: number, offset?: number): number -Writes a big-endian double-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 64-bit, big-endian, double-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2208,7 +2208,7 @@ let result = buf.writeDoubleBE(123.456, 0); writeDoubleLE(value: number, offset?: number): number -Writes a little-endian double-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 64-bit, little-endian, double-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2247,7 +2247,7 @@ let result = buf.writeDoubleLE(123.456, 0); writeFloatBE(value: number, offset?: number): number -Writes a big-endian single-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 32-bit, big-endian, single-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2287,7 +2287,7 @@ let result = buf.writeFloatBE(0xcafebabe, 0); writeFloatLE(value: number, offset?: number): number -Writes a little-endian single-precision floating-point number to this **Buffer** instance at the specified offset. +Writes a 32-bit, little-endian, single-precision floating-point number to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2326,7 +2326,7 @@ let result = buf.writeFloatLE(0xcafebabe, 0); writeInt8(value: number, offset?: number): number -Writes a signed 8-bit integer to this **Buffer** instance at the specified offset. +Writes a 8-bit signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2367,7 +2367,7 @@ let result1 = buf.writeInt8(-2, 1); writeInt16BE(value: number, offset?: number): number -Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, big-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2407,7 +2407,7 @@ let result = buf.writeInt16BE(0x0102, 0); writeInt16LE(value: number, offset?: number): number -Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, little-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2446,7 +2446,7 @@ let result = buf.writeInt16LE(0x0304, 0); writeInt32BE(value: number, offset?: number): number -Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, big-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2486,7 +2486,7 @@ let result = buf.writeInt32BE(0x01020304, 0); writeInt32LE(value: number, offset?: number): number -Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, little-endian, signed integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2606,7 +2606,7 @@ let result = buf.writeIntLE(0x1234567890ab, 0, 6); writeUInt8(value: number, offset?: number): number -Writes an unsigned 8-bit integer to this **Buffer** instance at the specified offset. +Writes a 8-bit unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2648,7 +2648,7 @@ let result3 = buf.writeUInt8(0x42, 3); writeUInt16BE(value: number, offset?: number): number -Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, big-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2688,7 +2688,7 @@ let result1 = buf.writeUInt16BE(0xbeef, 2); writeUInt16LE(value: number, offset?: number): number -Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at the specified offset. +Writes a 16-bit, little-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2728,7 +2728,7 @@ let result1 = buf.writeUInt16LE(0xbeef, 2); writeUInt32BE(value: number, offset?: number): number -Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, big-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -2767,7 +2767,7 @@ let result = buf.writeUInt32BE(0xfeedface, 0); writeUInt32LE(value: number, offset?: number): number -Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at the specified offset. +Writes a 32-bit, little-endian, unsigned integer to this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index 4c66c928fb7ee6c5482d39db7b39acaa6793691e..8aad8fdf810b9f3246672b8c3d2e21df7733d94e 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -28,7 +28,7 @@ Converts an XML text into a JavaScript object. | Name | Type | Mandatory| Description | | ------- | --------------------------------- | ---- | --------------- | | xml | string | Yes | XML text to convert.| -| options | [ConvertOptions](#convertoptions) | No | Options for conversion. | +| options | [ConvertOptions](#convertoptions) | No | Options for conversion. The default value is a **ConvertOptions** object, which consists of the default values of the attributes in the object. | **Return value** @@ -89,7 +89,7 @@ Converts an XML text into a JavaScript object. | Name | Type | Mandatory| Description | | ------- | --------------------------------- | ---- | --------------- | | xml | string | Yes | XML text to convert.| -| options | [ConvertOptions](#convertoptions) | No | Options for conversion. | +| options | [ConvertOptions](#convertoptions) | No | Options for conversion. The default value is a **ConvertOptions** object, which consists of the default values of the attributes in the object. | **Return value** diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 6d381fe58429d72d81b6b1bcffec64b100d876a8..34337fa9198edeeeab9d437bc084538777834d31 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -879,6 +879,53 @@ async function Demo() { } ``` +### getColorSpace10+ + +getColorSpace(): colorSpaceManager.ColorSpaceManager + +Obtains the color space of this image + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------- | +| [colorSpaceManager.ColorSpaceManager](js-apis-colorSpaceManager.md#colorspacemanager) | Color space obtained.| + +**Example** + +```js +import colorSpaceManager from '@ohos.graphics.colorSpaceManager'; +async function Demo() { + let csm = pixelmap.getColorSpace(); +} +``` + +### setColorSpace10+ + +setColorSpace(colorSpace: colorSpaceManager.ColorSpaceManager): void + +Sets the color space for this image. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | --------------- | +| colorSpace | [colorSpaceManager.ColorSpaceManager](js-apis-colorSpaceManager.md#colorspacemanager) | Yes | Color space to set.| + +**Example** + +```js +import colorSpaceManager from '@ohos.graphics.colorSpaceManager'; +async function Demo() { + var csm = colorSpaceManager.create(colorSpaceName); + pixelmap.setColorSpace(csm); +} +``` + ### release7+ release():Promise\ @@ -937,7 +984,7 @@ Creates an **ImageSource** instance based on the URI. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------- | -| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.
Currently, the following formats are supported: JPG, PNG, GIF, BMP, Webp, and RAW.| +| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.
Currently, the following formats are supported: .jpg, .png, .gif, .bmp, .webp, and raw. For details, see [SVG Tags10+](#svg-tags). | **Return value** @@ -975,7 +1022,7 @@ Creates an **ImageSource** instance based on the URI. | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ----------------------------------- | -| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.
Currently, the following formats are supported: JPG, PNG, GIF, BMP, Webp, and RAW.| +| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.
Currently, the following formats are supported: .jpg, .png, .gif, .bmp, .webp, and raw. For details, see [SVG Tags10+](#svg-tags). | | options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.| **Return value** @@ -1489,8 +1536,8 @@ Creates a **PixelMap** object based on the default parameters. This API uses an ```js imageSourceApi.createPixelMap((err, pixelmap) => { - console.info('Succeeded in creating pixelmap object.'); - }) + console.info('Succeeded in creating pixelmap object.'); +}) ``` ### createPixelMap7+ @@ -1525,6 +1572,177 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => { }) ``` +### createPixelMapList10+ + +createPixelMapList(options?: DecodingOptions): Promise>; + +Creates an array of **PixelMap** objects based on image decoding parameters. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| options | [DecodingOptions](#decodingoptions7) | No | Image decoding parameters. | + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise> | Promise used to return an array of **PixeMap** objects.| + +**Example** + +```js +let decodeOpts = { + sampleSize: 1, + editable: true, + desiredSize: { width: 198, height: 202 }, + rotate: 0, + desiredPixelFormat: 3, + index: 0, +}; +let pixelmaplist = imageSourceApi.createPixelMapList(decodeOpts); +``` + +### createPixelMapList10+ + +createPixelMapList(callback: AsyncCallback>): void + +Creates an array of **PixelMap** objects based on the default parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback> | Yes | Callback used to return an array of **PixeMap** objects.| + +**Example** + +```js +imageSourceApi.createPixelMap( pixelmaplist => { + console.info('Succeeded in creating pixelmaplist object.'); +}) +``` + +### createPixelMapList10+ + +createPixelMapList(options: DecodingOptions, callback: AsyncCallback>): void; + +Creates an array of **PixelMap** objects based on image decoding parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| options | [DecodingOptions](#decodingoptions7) | Yes| Image decoding parameters.| +| callback | AsyncCallback> | Yes | Callback used to return an array of **PixeMap** objects.| + +**Example** + +```js +let decodeOpts = { + sampleSize: 1, + editable: true, + desiredSize: { width: 198, height: 202 }, + rotate: 0, + desiredPixelFormat: 3, + index: 0, +}; +imageSourceApi.createPixelMap(decodeOpts, pixelmaplist => { + console.log('Succeeded in creating pixelmaplist object.'); +}) +``` + +### getDelayTime10+ + +getDelayTime(callback: AsyncCallback>): void; + +Obtains an array of delay times. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback> | Yes | Callback used to return an array of delay times.| + +**Example** + +```js +imageSourceApi.getDelayTime( delayTimes => { + console.log('Succeeded in getting delay time.'); +}); +``` + +### getDelayTime10+ + +getDelayTime(): Promise>; + +Obtains an array of delay times. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise> | Promise used to return an array of delay times.| + +**Example** + +```js +let delayTimes = imageSourceApi.getDelayTime(); +``` + +### getFrameCount10+ + +getFrameCount(callback: AsyncCallback\): void; + +Obtains the number of frames. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the number of frames.| + +**Example** + +```js +imageSourceApi.getFrameCount( frameCount => { + console.log('Succeeded in getting frame count.'); +}); +``` + +### getFrameCount10+ + +getFrameCount(): Promise\; + +Obtains the number of frames. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageSource + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise\ | Promise used to return the number of frames.| + +**Example** + +```js +let frameCount = imageSourceApi.getFrameCount(); +``` + ### release release(callback: AsyncCallback\): void @@ -2616,7 +2834,50 @@ Describes the color components of an image. | pixelStride | number | Yes | No | Pixel stride. | | byteBuffer | ArrayBuffer | Yes | No | Component buffer.| -## ResponseCode +## Supplementary Information +### SVG Tags + +The SVG tags are supported since API verison 10. The used version is (SVG) 1.1. Currently, the following tags are supported: +- a +- circla +- clipPath +- defs +- ellipse +- feBlend +- feColorMatrix +- feComposite +- feDiffuseLighting +- feDisplacementMap +- feDistantLight +- feFlood +- feGaussianBlur +- feImage +- feMorphology +- feOffset +- fePointLight +- feSpecularLighting +- feSpotLight +- feTurbulence +- filter +- g +- image +- line +- linearGradient +- mask +- path +- pattern +- polygon +- polyline +- radialGradient +- rect +- stop +- svg +- text +- textPath +- tspan +- use + +### ResponseCode Enumerates the response codes returned upon build errors. diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md index 492ff93d33f7c4bf6f83776cf2d71be34e50f9c8..e6db9ed5b61837e587762b581a0b97d87c25b366 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -40,6 +40,8 @@ Creates the context based on the bundle name. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory | Description | @@ -102,6 +104,8 @@ Creates the context based on the bundle name and module name. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Type | Mandatory | Description | diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index 5d6b85f2bf376847699ff87684aebb5f55b461ed..7513ee297e542a79d33d2b01cd755889ca1c9209 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -60,7 +60,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | ------------------------------ | -| 12800006 | Input method controller error. | +| 12800006 | input method controller error. | **Example** @@ -88,7 +88,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800007 | Input method settings extension error. | +| 12800007 | input method settings extension error. | **Example** @@ -119,8 +119,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800005 | Configuration persisting error. | -| 12800008 | Input method manager service error. | +| 12800005 | configuration persisting error. | +| 12800008 | input method manager service error. | **Example** @@ -176,8 +176,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800005 | Configuration persisting error. | -| 12800008 | Input method manager service error. | +| 12800005 | configuration persisting error. | +| 12800008 | input method manager service error. | **Example** @@ -248,8 +248,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800005 | Configuration persisting error. | -| 12800008 | Input method manager service error. | +| 12800005 | configuration persisting error. | +| 12800008 | input method manager service error. | **Example** @@ -309,8 +309,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800005 | Configuration persisting error. | -| 12800008 | Input method manager service error. | +| 12800005 | configuration persisting error. | +| 12800008 | input method manager service error. | **Example** @@ -384,8 +384,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800005 | Configuration persisting error. | -| 12800008 | Input method manager service error. | +| 12800005 | configuration persisting error. | +| 12800008 | input method manager service error. | **Example** @@ -438,8 +438,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800005 | Configuration persisting error. | -| 12800008 | Input method manager service error. | +| 12800005 | configuration persisting error. | +| 12800008 | input method manager service error. | **Example** @@ -447,7 +447,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e let im = inputMethod.getCurrentInputMethod(); let imSubType = inputMethod.getCurrentInputMethodSubtype(); try { - inputMethod.switchCurrentInputMethodAndSubtype(inputMethodProperty, imSubType).then((result) => { + inputMethod.switchCurrentInputMethodAndSubtype(im, imSubType).then((result) => { if (result) { console.info('Succeeded in switching currentInputMethodAndSubtype.'); } else { @@ -533,8 +533,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800003 | Input method client error. | -| 12800008 | Input method manager service error. | +| 12800003 | input method client error. | +| 12800008 | input method manager service error. | **Example** @@ -576,8 +576,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800003 | Input method client error. | -| 12800008 | Input method manager service error. | +| 12800003 | input method client error. | +| 12800008 | input method manager service error. | **Example** @@ -619,8 +619,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800003 | Input method client error. | -| 12800008 | Input method manager service error. | +| 12800003 | input method client error. | +| 12800008 | input method manager service error. | **Example** @@ -656,8 +656,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800003 | Input method client error. | -| 12800008 | Input method manager service error. | +| 12800003 | input method client error. | +| 12800008 | input method manager service error. | **Example** @@ -691,8 +691,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800003 | Input method client error. | -| 12800008 | Input method manager service error. | +| 12800003 | input method client error. | +| 12800008 | input method manager service error. | **Example** @@ -728,8 +728,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800003 | Input method client error. | -| 12800008 | Input method manager service error. | +| 12800003 | input method client error. | +| 12800008 | input method manager service error. | **Example** @@ -876,8 +876,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800001 | Package manager error. | -| 12800008 | Input method manager service error. | +| 12800001 | package manager error. | +| 12800008 | input method manager service error. | **Example** @@ -928,8 +928,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800001 | Package manager error. | -| 12800008 | Input method manager service error. | +| 12800001 | package manager error. | +| 12800008 | input method manager service error. | **Example** @@ -972,8 +972,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800001 | Package manager error. | -| 12800008 | Input method manager service error. | +| 12800001 | package manager error. | +| 12800008 | input method manager service error. | **Example** @@ -1011,8 +1011,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800001 | Package manager error. | -| 12800008 | Input method manager service error. | +| 12800001 | package manager error. | +| 12800008 | input method manager service error. | **Example** @@ -1049,8 +1049,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800001 | Package manager error. | -| 12800008 | Input method manager service error. | +| 12800001 | package manager error. | +| 12800008 | input method manager service error. | **Example** @@ -1088,8 +1088,8 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800001 | Package manager error. | -| 12800008 | Input method manager service error. | +| 12800001 | package manager error. | +| 12800008 | input method manager service error. | **Return value** @@ -1131,7 +1131,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800008 | Input method manager service error. | +| 12800008 | input method manager service error. | **Example** @@ -1169,7 +1169,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------------------- | -| 12800008 | Input method manager service error. | +| 12800008 | input method manager service error. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index ecdfc7d180b05f69f9357ac1c8bf9470970961c7..72eac3df758994885afd2ffaa65422fe29434bb5 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -56,14 +56,16 @@ Provides the constant values of function keys, edit boxes, and the cursor. getInputMethodAbility(): InputMethodAbility -Obtains an [InputMethodAbility](#inputmethodability) instance for the input method. The input method can use the obtained instance to subscribe to a soft keyboard display/hide request event, create/destroy an input method panel, and the like. +Obtains an [InputMethodAbility](#inputmethodability) instance for the input method. + +The input method can use the obtained instance to subscribe to a soft keyboard display/hide request event. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| --------------------------------------- | ------------ | +| Type | Description | +| ----------------------------------------- | ------------------ | | [InputMethodAbility](#inputmethodability) | **InputMethodAbility** instance.| **Example** @@ -82,8 +84,8 @@ Obtains a [KeyboardDelegate](#keyboarddelegate) instance for the input method. T **Return value** -| Type | Description | -| ------------------------------------- | ---------------- | +| Type | Description | +| ------------------------------------- | ------------------------ | | [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance.| **Example** @@ -100,14 +102,14 @@ Obtains an [InputMethodEngine](#inputmethodengine) instance for the input method > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getInputMethodAbility()](#inputmethodenginegetinputmethodability9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getInputMethodAbility()](#inputmethodenginegetinputmethodability9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| --------------------------------------- | ------------ | +| Type | Description | +| ----------------------------------------- | ------------------ | | [InputMethodEngine](#inputmethodengine) | **InputMethodAbility** instance.| **Example** @@ -124,14 +126,14 @@ Obtains a [KeyboardDelegate](#keyboarddelegate) instance for the input method. T > **NOTE** > ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getKeyboardDelegate()](#inputmethodenginegetkeyboarddelegate9). +>This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getKeyboardDelegate()](#inputmethodenginegetkeyboarddelegate9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| ------------------------------------- | ---------------- | +| Type | Description | +| ------------------------------------- | ------------------------ | | [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance.| **Example** @@ -384,7 +386,7 @@ inputMethodEngine.getInputMethodAbility().off('setCallingWindow', () => { on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void -Enables listening for a keyboard event. This API uses an asynchronous callback to return the result. +Enables listening for a keyboard visibility event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -410,7 +412,7 @@ inputMethodEngine.getInputMethodAbility().on('keyboardHide', () => { off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void -Disables listening for a keyboard event. This API uses an asynchronous callback to return the result. +Disables listening for a keyboard visibility event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -442,9 +444,9 @@ Enables listening for the input method subtype setting event. This API uses an a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'setSubtype'** indicates the input method subtype setting event.| +| Name | Type| Mandatory | Description| +| -------- | --- | ---- | --- | +| type | string | Yes | Listening type.
The value **'setSubtype'** indicates the input method subtype setting event.| | callback | (inputMethodSubtype: [InputMethodSubtype](js-apis-inputmethod-subtype.md)) => void | Yes | Callback used to return the input method subtype. | **Example** @@ -465,9 +467,9 @@ Disables listening for the input method subtype setting event. This API uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'setSubtype'** indicates the input method subtype setting event.| +| Name | Type | Mandatory| Description | +| ------- | ----- | ---- | ---- | +| type | string | Yes | Listening type.
The value **'setSubtype'** indicates the input method subtype setting event.| | callback | (inputMethodSubtype: [InputMethodSubtype](js-apis-inputmethod-subtype.md)) => void | No | Callback used to return the input method subtype. | **Example** @@ -522,9 +524,9 @@ Disables listening for a keyboard event. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'keyDown'** indicates the keydown event.
The value **'keyUp'** indicates the keyup event.| +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ----- | +| type | string | Yes | Listening type.
The value **'keyDown'** indicates the keydown event.
The value **'keyUp'** indicates the keyup event.| | callback | (event: [KeyEvent](#keyevent)) => boolean | No | Callback used to return the key information. | **Example** @@ -550,9 +552,9 @@ Enables listening for the cursor change event. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'cursorContextChange'** indicates the cursor change event.| +| Name | Type | Mandatory | Description | +| -------- | ---- | ---- | ----- | +| type | string | Yes | Listening type.
The value **'cursorContextChange'** indicates the cursor change event.| | callback | (x: number, y: number, height: number) => void | Yes | Callback used to return the cursor information.
- **x**: x coordinate of the top of the cursor.
- **y**: x coordinate of the bottom of the cursor.
- **height**: height of the cursor.| **Example** @@ -575,9 +577,9 @@ Cancels listening for cursor context changes. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'cursorContextChange'** indicates the cursor change event.| +| Name | Type | Mandatory | Description | +| -------- | ---- | ---- | ------ | +| type | string | Yes | Listening type.
The value **'cursorContextChange'** indicates the cursor change event.| | callback | (x: number, y:number, height:number) => void | No | Callback used to return the cursor information.
- **x**: x coordinate of the top of the cursor.
- **y**: x coordinate of the bottom of the cursor.
- **height**: height of the cursor.
| @@ -598,9 +600,9 @@ Enables listening for the text selection change event. This API uses an asynchro **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'selectionChange'** indicates the text selection change event.| +| Name | Type | Mandatory| Description | +| -------- | ----- | ---- | ---- | +| type | string | Yes | Listening type.
The value **'selectionChange'** indicates the text selection change event.| | callback | (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void | Yes | Callback used to return the text selection information.
- **oldBegin**: start of the selected text before the change.
- **oldEnd**: end of the selected text before the change.
- **newBegin**: start of the selected text after the change.
- **newEnd**: end of the selected text after the change.| **Example** @@ -624,9 +626,9 @@ Cancels listening for text selection changes. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
The value **'selectionChange'** indicates the text selection change event.| +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ------- | +| type | string | Yes | Listening type.
The value **'selectionChange'** indicates the text selection change event.| | callback | (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void | No | Callback used to return the text selection information.
- **oldBegin**: start of the selected text before the change.
- **oldEnd**: end of the selected text before the change.
- **newBegin**: start of the selected text after the change.
- **newEnd**: end of the selected text after the change.
| **Example** @@ -651,7 +653,7 @@ Enables listening for the text change event. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Listening type.
The value **'textChange'** indicates the text change event.| -| callback | (text: string) => void | Yes | Callback used to return the text content. | +| callback | (text: string) => void | Yes | Callback used to return the text content.| **Example** @@ -762,7 +764,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [hide](#hide9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [hide](#hide9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -792,7 +794,7 @@ Hides the keyboard. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [hide](#hide9-1). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [hide](#hide9-1) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -828,7 +830,7 @@ Sends the function key. This API uses an asynchronous callback to return the res | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| +| action | number | Yes| Action of the function key.
- **0**: invalid key.
- **1**: confirm key (Enter key).| | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| **Error codes** @@ -872,7 +874,7 @@ Sends the function key. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| +| action | number | Yes| Action of the function key.
- **0**: invalid key.
- **1**: confirm key (Enter key).| **Return value** @@ -1073,7 +1075,7 @@ try { console.error('Failed to getForward: ' + JSON.stringify(err)); }); } catch (err) { - console.error('Failed to getForward: ' + JSON.stringify(err)); + console.error(`Failed to getBackward: ${JSON.stringify(err)}`); } ``` @@ -1098,7 +1100,7 @@ For details about the error codes, see [Input Method Framework Error Codes](../e | Error Code ID| Error Message | | -------- | -------------------------- | -| 12800002 | Input method engine error. | +| 12800002 | input method engine error. | | 12800003 | input method client error. | **Example** @@ -1166,7 +1168,7 @@ try { console.error('Failed to delete Forward: ' + JSON.stringify(err)); }); } catch (err) { - console.error('Failed to delete Forward: ' + JSON.stringify(err)); + console.error(`Failed to deleteForward: ${JSON.stringify(err)}`); } ``` @@ -1219,7 +1221,7 @@ try { deleteBackward(length:number): Promise<boolean> -Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text after the cursor. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1514,14 +1516,14 @@ Describes the attribute of a key. | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------ | -| keyCode | number | Yes | No | Key value.| -| keyAction | number | Yes | No | Key status.| +| keyCode | number | Yes | No | Key value. For detail, see [KeyCode](js-apis-keycode.md#keycode).| +| keyAction | number | Yes | No | Key event type.
- **2**: keydown event.
- **3**: keyup event.| ## TextInputClient(deprecated) > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [InputClient](#inputclient9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [InputClient](#inputclient9) instead. In the following API examples, you must first use **[on('inputStart')](#oninputstart)** to obtain a **TextInputClient** instance, and then call the APIs using the obtained instance. @@ -1533,7 +1535,7 @@ Obtains the specific-length text before the cursor. This API uses an asynchronou > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getForward](#getforward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getForward](#getforward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1565,7 +1567,7 @@ Obtains the specific-length text before the cursor. This API uses a promise to r > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getForward](#getforward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getForward](#getforward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1600,7 +1602,7 @@ Obtains the specific-length text after the cursor. This API uses an asynchronous > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getBackward](#getbackward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getBackward](#getbackward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1632,7 +1634,7 @@ Obtains the specific-length text after the cursor. This API uses a promise to re > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getBackward](#getbackward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getBackward](#getbackward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1667,7 +1669,7 @@ Deletes the fixed-length text before the cursor. This API uses an asynchronous c > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteForward](#deleteforward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteForward](#deleteforward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1703,7 +1705,7 @@ Deletes the fixed-length text before the cursor. This API uses a promise to retu > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteForward](#deleteforward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteForward](#deleteforward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1742,18 +1744,18 @@ Deletes the fixed-length text after the cursor. This API uses an asynchronous ca > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteBackward](#deletebackward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteBackward](#deletebackward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | -------------- | | length | number | Yes | Text length. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| - **Example** +**Example** ```js let length = 1; @@ -1774,11 +1776,11 @@ textInputClient.deleteBackward(length, (err, result) => { deleteBackward(length:number): Promise<boolean> -Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text after the cursor. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteBackward](#deletebackward9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteBackward](#deletebackward9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1816,18 +1818,18 @@ Sends the function key. This API uses an asynchronous callback to return the res > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [sendKeyFunction](#sendkeyfunction9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [sendKeyFunction](#sendkeyfunction9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| +| action | number | Yes| Action of the function key.
- **0**: invalid key.
- **1**: confirm key (Enter key).| | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| - **Example** +**Example** ```js let action = 1; @@ -1852,7 +1854,7 @@ Sends the function key. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [sendKeyFunction](#sendkeyfunction9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [sendKeyFunction](#sendkeyfunction9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1860,7 +1862,7 @@ Sends the function key. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| +| action | number | Yes| Action of the function key.
- **0**: invalid key.
- **1**: confirm key (Enter key).| **Return value** @@ -1891,7 +1893,7 @@ Inserts text. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [insertText](#inserttext9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [insertText](#inserttext9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1926,7 +1928,7 @@ Inserts text. This API uses a promise to return the result. > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [insertText](#inserttext9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [insertText](#inserttext9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1964,14 +1966,14 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getEditorAttribute](#geteditorattribute9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getEditorAttribute](#geteditorattribute9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** -| Name | Type | Mandatory | Description | -| ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| Name | Type | Mandatory | Description | +| -------- | ----- | ----- | ----- | | callback | AsyncCallback<[EditorAttribute](#editorattribute)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the attribute of the edit box. Otherwise, **err** is an error object.| **Example** @@ -1995,7 +1997,7 @@ Obtains the attribute of the edit box. This API uses a promise to return the res > **NOTE** > -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getEditorAttribute](#geteditorattribute9). +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getEditorAttribute](#geteditorattribute9) instead. **System capability**: SystemCapability.MiscServices.InputMethodFramework diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 240108ae1849dfb2fd04d927728c653cdb4627f7..4d8e85aa0ed8ff42dde6b92d6e6a3b9a62caf3fa 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -77,7 +77,6 @@ let media = mediaLibrary.getMediaLibrary(); ### getFileAssets7+ - getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void Obtains file assets (also called files). This API uses an asynchronous callback to return the result. @@ -105,7 +104,7 @@ async function example() { selectionArgs: [imageType.toString()], }; // Obtain the files in asynchronous callback mode. - media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { + media.getFileAssets(imagesFetchOp, async (error, fetchFileResult) => { // Check whether the result set of the obtained files is undefined. If yes, the API call fails. if (fetchFileResult == undefined) { console.error('get fetchFileResult failed with error: ' + error); @@ -124,8 +123,8 @@ async function example() { return; } console.info('Get fetchFileResult successfully, count: ' + count); - // Obtain the first file in the result set in asynchronous callback mode. - fetchFileResult.getFirstObject((error, fileAsset) => { + // Obtain the first file in the result set in asynchronous callback mode. If there are a large number of files, use getAllObject instead. + fetchFileResult.getFirstObject(async (error, fileAsset) => { // Check whether the first file is undefined. If yes, the API call fails. if (fileAsset == undefined) { console.error('get first object failed with error: ' + error); @@ -178,7 +177,7 @@ async function example() { selectionArgs: [imageType.toString()], }; // Obtain the files in promise mode. - media.getFileAssets(imagesFetchOp).then((fetchFileResult) => { + media.getFileAssets(imagesFetchOp).then(async (fetchFileResult) => { // Obtain the total number of files in the result set. const count = fetchFileResult.getCount(); // Check whether the number is less than 0. If yes, the API call fails. @@ -192,8 +191,8 @@ async function example() { return; } console.info('Get fetchFileResult successfully, count: ' + count); - // Obtain the first file in the result set in promise mode. - fetchFileResult.getFirstObject().then((fileAsset) => { + // Obtain the first file in the result set in promise mode. If there are a large number of files, use getAllObject instead. + fetchFileResult.getFirstObject().then(async (fileAsset) => { console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName); // Call getNextObject to obtain the next file until the last one. for (let i = 1; i < count; i++) { @@ -514,17 +513,18 @@ Obtains the albums. This API uses an asynchronous callback to return the result. ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { - if (albumList != undefined) { - console.info('getAlbums successfully: ' + JSON.stringify(albumList)); - } else { - console.error('getAlbums failed with error: ' + error); - } - }) + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => { + if (albumList != undefined) { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + } else { + console.error('getAlbums failed with error: ' + error); + } + }) } ``` @@ -554,15 +554,16 @@ Obtains the albums. This API uses a promise to return the result. ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { - console.info('getAlbums successfully: ' + JSON.stringify(albumList)); - }).catch((error) => { - console.error('getAlbums failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => { + console.info('getAlbums successfully: ' + JSON.stringify(albumList)); + }).catch((error) => { + console.error('getAlbums failed with error: ' + error); + }); } ``` @@ -2021,7 +2022,7 @@ async function example() { ### getNextObject7+ - getNextObject(callback: AsyncCallback<FileAsset>): void +getNextObject(callback: AsyncCallback<FileAsset>): void Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. > **NOTE** @@ -2049,7 +2050,8 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fileAsset.isAfterLast) { + console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName); + if (!fetchFileResult.isAfterLast()) { fetchFileResult.getNextObject((error, fileAsset) => { if (error) { console.error('fetchFileResult getNextObject failed with error: ' + error); @@ -2065,7 +2067,7 @@ async function example() { ### getNextObject7+ - getNextObject(): Promise<FileAsset> +getNextObject(): Promise<FileAsset> Obtains the next file asset in the result set. This API uses a promise to return the result. > **NOTE** @@ -2093,7 +2095,8 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); let fileAsset = await fetchFileResult.getFirstObject(); - if (!fileAsset.isAfterLast) { + console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName); + if (!fetchFileResult.isAfterLast()) { fetchFileResult.getNextObject().then((fileAsset) => { console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName); fetchFileResult.close(); @@ -2369,20 +2372,21 @@ Commits the modification in the album attributes to the database. This API uses ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - album.albumName = 'hello'; - album.commitModify((error) => { - if (error) { - console.error('commitModify failed with error: ' + error); - return; - } - console.info('commitModify successful.'); - }) + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + album.albumName = 'hello'; + album.commitModify((error) => { + if (error) { + console.error('commitModify failed with error: ' + error); + return; + } + console.info('commitModify successful.'); + }) } ``` @@ -2406,18 +2410,60 @@ Commits the modification in the album attributes to the database. This API uses ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - album.albumName = 'hello'; - album.commitModify().then(() => { - console.info('commitModify successfully'); - }).catch((error) => { - console.error('commitModify failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info('commitModify successfully'); + }).catch((error) => { + console.error('commitModify failed with error: ' + error); + }); +} +``` + +### getFileAssets7+ + +getFileAssets(callback: AsyncCallback<FetchFileResult>): void + +Obtains the file assets in this album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Callback used to return the file assets.| + +**Example** + +```js +async function example() { + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets((error, fetchFileResult) => { + if (error) { + console.error('album getFileAssets failed with error: ' + error); + return; + } + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }); } ``` @@ -2442,27 +2488,28 @@ Obtains the file assets in this album. This API uses an asynchronous callback to ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { + if (error) { + console.error('album getFileAssets failed with error: ' + error); + return; } - // Obtain the albums that meet the retrieval options and return the album list. - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. - album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => { - if (error) { - console.error('album getFileAssets failed with error: ' + error); - return; - } - let count = fetchFileResult.getCount(); - console.info('album getFileAssets successfully, count: ' + count); - fetchFileResult.close(); - }); + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }); } ``` @@ -2492,25 +2539,26 @@ Obtains the file assets in this album. This API uses a promise to return the res ```js async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - // Obtain the albums that meet the retrieval options and return the album list. - const albumList = await media.getAlbums(AlbumNoArgsfetchOp); - const album = albumList[0]; - // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. - album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { - let count = fetchFileResult.getCount(); - console.info('album getFileAssets successfully, count: ' + count); - fetchFileResult.close(); - }).catch((error) => { - console.error('album getFileAssets failed with error: ' + error); - }); + // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'. + let AlbumNoArgsfetchOp = { + selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + // Obtain the albums that meet the retrieval options and return the album list. + const albumList = await media.getAlbums(AlbumNoArgsfetchOp); + const album = albumList[0]; + // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album. + album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => { + let count = fetchFileResult.getCount(); + console.info('album getFileAssets successfully, count: ' + count); + fetchFileResult.close(); + }).catch((error) => { + console.error('album getFileAssets failed with error: ' + error); + }); } ``` diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 3f9387defec0e68dc6414fdb4b21c5bca9cb1490..2242fce6a608c15f13af12f895d5f82024559da2 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,4 +1,4 @@ -# @ohos.reminderAgent (Reminder Agent) +# @ohos.reminderAgent (reminderAgent) The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. @@ -13,19 +13,21 @@ You can use the APIs to create scheduled reminders for countdown timers, calenda ## Modules to Import -```ts +```js import reminderAgent from'@ohos.reminderAgent'; ``` -## reminderAgent.publishReminder +## reminderAgent.publishReminder(deprecated) -```ts -publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void -``` +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): 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). +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.publishReminder](js-apis-reminderAgentManager.md#reminderagentmanagerpublishreminder). + **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER **System capability**: SystemCapability.Notification.ReminderAgent @@ -35,29 +37,30 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| + | callback | AsyncCallback<number> | Yes| Callback used to return the published reminder's ID.| **Example** -```ts +```js let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } - reminderAgent.publishReminder(timer, (err, reminderId) => { console.log("callback, reminderId = " + reminderId); }); ``` -## reminderAgent.publishReminder +## reminderAgent.publishReminder(deprecated) -```ts -publishReminder(reminderReq: ReminderRequest): Promise -``` +publishReminder(reminderReq: ReminderRequest): Promise<number> 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). +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.publishReminder](js-apis-reminderAgentManager.md#reminderagentmanagerpublishreminder-1). + **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER **System capability**: SystemCapability.Notification.ReminderAgent @@ -70,29 +73,30 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise\ | Promise used to return the published reminder's ID.| + | Promise<number> | Promise used to return the published reminder's ID.| **Example** -```ts +```js let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } - reminderAgent.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); }); ``` -## reminderAgent.cancelReminder +## reminderAgent.cancelReminder(deprecated) -```ts -cancelReminder(reminderId: number, callback: AsyncCallback): void -``` +cancelReminder(reminderId: number, callback: AsyncCallback<void>): void Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.cancelReminder](js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** @@ -100,25 +104,27 @@ 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. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).| -| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** -```ts +```js reminderAgent.cancelReminder(1, (err, data) => { console.log("cancelReminder callback"); }); ``` -## reminderAgent.cancelReminder +## reminderAgent.cancelReminder(deprecated) -```ts -cancelReminder(reminderId: number): Promise -``` +cancelReminder(reminderId: number): Promise\ Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.cancelReminder](js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder-1). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** @@ -131,35 +137,37 @@ 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<void> | Promise used to return the result.| **Example** -```ts +```js reminderAgent.cancelReminder(1).then(() => { console.log("cancelReminder promise"); }); ``` -## reminderAgent.getValidReminders +## reminderAgent.getValidReminders(deprecated) -```ts -getValidReminders(callback: AsyncCallback>): void -``` +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. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.getValidReminders](js-apis-reminderAgentManager.md#reminderagentmanagergetvalidreminders). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** | 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<Array<[ReminderRequest](#reminderrequest)>> | Yes| Callback used to return an array of all valid reminders set by the current application.| **Example** -```ts +```js reminderAgent.getValidReminders((err, reminders) => { console.log("callback, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -187,25 +195,27 @@ reminderAgent.getValidReminders((err, reminders) => { ``` -## reminderAgent.getValidReminders +## reminderAgent.getValidReminders(deprecated) -```ts -getValidReminders(): Promise> -``` +getValidReminders(): Promise\> Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.getValidReminders](js-apis-reminderAgentManager.md#reminderagentmanagergetvalidreminders-1). + **System capability**: SystemCapability.Notification.ReminderAgent **Return value** | Type| Description| | -------- | -------- | -| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| +| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| **Example** -```ts +```js reminderAgent.getValidReminders().then((reminders) => { console.log("promise, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -233,63 +243,70 @@ reminderAgent.getValidReminders().then((reminders) => { ``` -## reminderAgent.cancelAllReminders +## reminderAgent.cancelAllReminders(deprecated) -```ts -cancelAllReminders(callback: AsyncCallback): void -``` +cancelAllReminders(callback: AsyncCallback<void>): void Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.cancelAllReminders](js-apis-reminderAgentManager.md#reminderagentmanagercancelallreminders). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** -```ts +```js reminderAgent.cancelAllReminders((err, data) =>{ console.log("cancelAllReminders callback") }) ``` -## reminderAgent.cancelAllReminders +## reminderAgent.cancelAllReminders(deprecated) -```ts -cancelAllReminders(): Promise -``` +cancelAllReminders(): Promise\ Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.cancelAllReminders](js-apis-reminderAgentManager.md#reminderagentmanagercancelallreminders-1). + **System capability**: SystemCapability.Notification.ReminderAgent **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** -```ts +```js reminderAgent.cancelAllReminders().then(() => { console.log("cancelAllReminders promise") }) ``` + ## reminderAgent.addNotificationSlot -```ts -addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void -``` +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void Adds a notification slot. 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 [reminderAgentManager.addNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanageraddnotificationslot). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** @@ -297,11 +314,11 @@ 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| Asynchronous callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** -```ts +```js import notification from '@ohos.notification' let mySlot = { @@ -313,14 +330,16 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ``` -## reminderAgent.addNotificationSlot +## reminderAgent.addNotificationSlot(deprecated) -```ts -addNotificationSlot(slot: NotificationSlot): Promise -``` +addNotificationSlot(slot: NotificationSlot): Promise\ Adds a notification slot. 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 [reminderAgentManager.addNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanageraddnotificationslot-1). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** @@ -333,11 +352,11 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** -```ts +```js import notification from '@ohos.notification' let mySlot = { @@ -349,26 +368,28 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ``` -## reminderAgent.removeNotificationSlot +## reminderAgent.removeNotificationSlot(deprecated) -```ts -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void -``` +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void Removes a notification slot of a specified type. 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 [reminderAgentManager.removeNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanagerremovenotificationslot). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| -| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** -```ts +```js import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { @@ -377,31 +398,33 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ``` -## reminderAgent.removeNotificationSlot +## reminderAgent.removeNotificationSlot(deprecated) -```ts -removeNotificationSlot(slotType: notification.SlotType): Promise -``` +removeNotificationSlot(slotType: notification.SlotType): Promise<void> Removes a notification slot of a specified type. 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 [reminderAgentManager.removeNotificationSlot](js-apis-reminderAgentManager.md#reminderagentmanagerremovenotificationslot-1). + **System capability**: SystemCapability.Notification.ReminderAgent **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** -```ts +```js import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { @@ -410,10 +433,14 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). ``` -## ActionButtonType +## ActionButtonType(deprecated) Enumerates button types. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.ActionButtonType](js-apis-reminderAgentManager.md#ActionButtonType). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Value| Description| @@ -422,10 +449,14 @@ Enumerates button types. | ACTION_BUTTON_TYPE_SNOOZE | 1 | Button for snoozing the reminder.| -## ReminderType +## ReminderType(deprecated) Enumerates reminder types. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.ReminderType](js-apis-reminderAgentManager.md#ReminderType). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Value| Description| @@ -435,10 +466,14 @@ Enumerates reminder types. | REMINDER_TYPE_ALARM | 2 | Alarm reminder.| -## ActionButton +## ActionButton(deprecated) Defines a button displayed in the reminder notification. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.ActionButton](js-apis-reminderAgentManager.md#ActionButton). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| @@ -447,34 +482,46 @@ Defines a button displayed in the reminder notification. | type | [ActionButtonType](#actionbuttontype) | Yes| Button type.| -## WantAgent +## WantAgent(deprecated) Sets the package and ability that are redirected to when the reminder notification is clicked. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.WantAgent](js-apis-reminderAgentManager.md#WantAgent). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the HAP that is redirected to when the reminder notification is clicked.| +| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| | abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.| -## MaxScreenWantAgent +## MaxScreenWantAgent(deprecated) 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. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.MaxScreenWantAgent](js-apis-reminderAgentManager.md#MaxScreenWantAgent). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the HAP that is automatically started when the reminder arrives and the device is not in use.| +| 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.| -## ReminderRequest +## ReminderRequest(deprecated) Defines the reminder to publish. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.ReminderRequest](js-apis-reminderAgentManager.md#ReminderRequest). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| @@ -494,42 +541,54 @@ Defines the reminder to publish. | slotType | [notification.SlotType](js-apis-notification.md#slottype) | No| Type of the slot used by the reminder.| -## ReminderRequestCalendar +## ReminderRequestCalendar(deprecated) ReminderRequestCalendar extends ReminderRequest Defines a reminder for a calendar event. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.ReminderRequestCalendar](js-apis-reminderAgentManager.md#ReminderRequestCalendar). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array\ | No| Month in which the reminder repeats.| -| repeatDays | Array\ | No| Date on which the reminder repeats.| +| repeatMonths | Array<number> | No| Month in which the reminder repeats.| +| repeatDays | Array<number> | No| Date on which the reminder repeats.| -## ReminderRequestAlarm +## ReminderRequestAlarm(deprecated) ReminderRequestAlarm extends ReminderRequest Defines a reminder for an alarm. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.ReminderRequestAlarm](js-apis-reminderAgentManager.md#ReminderRequestAlarm). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| +| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| -## ReminderRequestTimer +## ReminderRequestTimer(deprecated) ReminderRequestTimer extends ReminderRequest Defines a reminder for a scheduled timer. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.ReminderRequestTimer](js-apis-reminderAgentManager.md#ReminderRequestTimer). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| @@ -537,10 +596,14 @@ Defines a reminder for a scheduled timer. | triggerTimeInSeconds | number | Yes| Number of seconds in the countdown timer.| -## LocalDateTime +## LocalDateTime(deprecated) Sets the time information for a calendar reminder. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [reminderAgentManager.LocalDateTime](js-apis-reminderAgentManager.md#LocalDateTime). + **System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 36f2e4957980fd01e010d6dd5a0fb27813c6d046..9969a6eb9d827aa4121146a13ed2c869070b551a 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -122,7 +122,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<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -168,7 +168,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Error codes** @@ -324,7 +324,7 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** @@ -401,7 +401,7 @@ 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<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -478,7 +478,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<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -562,7 +562,7 @@ Enumerates reminder types. ## ActionButton -Defines a button displayed in the reminder notification. +Defines a button displayed for the reminder in the notification panel. **System capability**: SystemCapability.Notification.ReminderAgent @@ -580,8 +580,9 @@ Sets the package and ability that are redirected to when the reminder notificati | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the HAP that is redirected to when the reminder notification is clicked.| -| abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.| +| pkgName | string | Yes| Name of the target package.| +| abilityName | string | Yes| Name of the target ability.| +| uri | string | No| URI of the target ability. (This is a system API.)| ## MaxScreenWantAgent @@ -592,7 +593,7 @@ Provides the information about the target package and ability to start automatic | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the HAP that is automatically started when the reminder arrives and the device is not in use.| +| 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.| @@ -605,8 +606,8 @@ Defines the reminder to publish. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| -| actionButton | [ActionButton](#actionbutton) | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| -| wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the notification is clicked.| +| actionButton | [ActionButton](#actionbutton) | No| Button displayed for the reminder in the notification panel. (A maximum of two buttons are supported.)| +| wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| | ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| | snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index 302df8dcdfbb9dd31c64320f63c51e97ecf2d684..ae4decd405b23cfc87452846558533448a86563f 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -137,7 +137,7 @@ Queries the group of this application. This API uses a promise to return the res **Return value** -| Type | Description | +| Type | Description | | --------------- | --------------------------- | | Promise<number> | Promise used to return the group.| @@ -559,6 +559,7 @@ Queries events of this application based on the specified start time and end tim **System API**: This is a system API. **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | | begin | number | Yes | Start time, in milliseconds. | @@ -609,6 +610,7 @@ Queries events of this application based on the specified start time and end tim **System API**: This is a system API. **Parameters** + | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | | begin | number | Yes | Start time, in milliseconds.| @@ -1549,7 +1551,7 @@ Provides the usage duration information of an application. | ------------------------ | ------ | ---- | ---------------------------------------- | | bundleName | string | No | Bundle name of the application. | | abilityPrevAccessTime | number | No | Last time when the application was used. | -| abilityInFgTotalTime | number | No | Total time that the application runs in the foreground. | +| abilityInFgTotalTime | number | No | Total time that the application runs in the foreground. | | id | number | Yes | User ID.| | abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.| | abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.| @@ -1568,9 +1570,9 @@ Provides information about an application event. | Name | Type | Mandatory | Description | | --------------------- | ------ | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| eventId | number | Yes | Application event type. | -| eventOccurredTime | number | Yes | Timestamp when the application event occurs. | +| bundleName | string | No | Bundle name of the application. | +| eventId | number | No | Application event type. | +| eventOccurredTime | number | No | Timestamp when the application event occurs. | | appGroup | number | No | Usage priority group of the application.| | indexOfLink | string | No | Shortcut ID.| | nameOfClass | string | No | Class name.| @@ -1585,7 +1587,7 @@ Provides the usage duration information of an application. | Name | Type | Mandatory | Description | | ------------------------------ | ---------------------------------------- | ---- | -------------- | -| [key: string]: BundleStatsInfo | [key: string]: [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| +| [key: string] | [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| ## DeviceEventStats 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 967001b4652718a2ba0b2d368b2e366fa4d66daa..9118b8b56684cc021cbd83511a905e28d5ddaead 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -80,7 +80,7 @@ Instructs the **WorkSchedulerService** to stop the specified task. | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------- | | work | [WorkInfo](#workinfo) | Yes | Task to stop. | -| needCancel | boolean | No | Whether to cancel the task.| +| needCancel | boolean | No | Whether to cancel the task. The default value is **false**.| **Error codes** @@ -118,7 +118,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes } ``` -## workScheduler.getWorkStatus:callback +## workScheduler.getWorkStatus getWorkStatus(workId: number, callback : AsyncCallback\): void Obtains the latest task status. This API uses an asynchronous callback to return the result. @@ -130,7 +130,7 @@ 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. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise. | +| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise.| **Error codes** @@ -161,7 +161,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes } ``` -## workScheduler.getWorkStatus:promise +## workScheduler.getWorkStatus getWorkStatus(workId: number): Promise\ Obtains the latest task status. This API uses a promise to return the result. @@ -178,7 +178,7 @@ Obtains the latest task status. This API uses a promise to return the result. | Type | Description | | ------------------------------- | ---------------------------------------- | -| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise. | +| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise.| **Error codes** @@ -207,7 +207,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes } ``` -## workScheduler.obtainAllWorks:callback +## workScheduler.obtainAllWorks obtainAllWorks(callback : AsyncCallback\): Array\ Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result. @@ -252,8 +252,8 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes } ``` -## workScheduler.obtainAllWorks:promise -obtainAllWorks(): Promise> +## workScheduler.obtainAllWorks +obtainAllWorks(): Promise\> Obtains all tasks associated with this application. This API uses a promise to return the result. @@ -317,7 +317,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes } ``` -## workScheduler.isLastWorkTimeOut:callback +## workScheduler.isLastWorkTimeOut isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result. @@ -364,7 +364,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes } ``` -## workScheduler.isLastWorkTimeOut:promise +## workScheduler.isLastWorkTimeOut isLastWorkTimeOut(workId: number): Promise\ Checks whether the last execution of the specified task timed out. This API uses a promise to return the result. @@ -432,7 +432,7 @@ Provides detailed information about the task. For details about the constraints | 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. | +| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. | ## NetworkType Enumerates the network types that can trigger the task. diff --git a/en/application-dev/reference/apis/js-apis-stationary.md b/en/application-dev/reference/apis/js-apis-stationary.md index 6c2ec0a365b1224274e760a8bc5dcbea97aa176d..cb2f0f4432a5547960ef175e3ddd9a147515f0c9 100644 --- a/en/application-dev/reference/apis/js-apis-stationary.md +++ b/en/application-dev/reference/apis/js-apis-stationary.md @@ -123,7 +123,7 @@ Unsubscribes from the device status. | -------------------- | -------------------------------------------------- | ---- | ---------------------------- | | activity | [ActivityType](#activitytype) | Yes | Device status type. | | event | [ActivityEvent](#activityevent) | Yes | Event type. | -| callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data, if the callback parameter is not passed, all callbacks subscribed to this type under this process will be removed. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data. If this parameter is not passed, all callbacks associated with the specified event in the process will be unregistered. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md index c1741b242f4b98d76df8ad4868dfc75d8089b36a..f347d7e42f1f9901186938a9ae15005d2ed95e6e 100644 --- a/en/application-dev/reference/apis/js-apis-taskpool.md +++ b/en/application-dev/reference/apis/js-apis-taskpool.md @@ -1,4 +1,4 @@ -# @ohos.taskpool (Using the Task Pool) +# @ohos.taskpool (Starting the Task Pool) The task pool provides a multi-thread running environment for applications. It helps reduce resource consumption and improve system performance. It also frees you from caring about the lifecycle of thread instances. You can use the **TaskPool** APIs to create background tasks and perform operations on them, for example, executing or canceling a task. Theoretically, you can create an unlimited number of tasks, but this is not recommended for memory considerations. In addition, you are not advised performing blocking operations in a task, especially indefinite blocking. Long-time blocking operations occupy worker threads and may block other task scheduling, adversely affecting your application performance. @@ -46,7 +46,7 @@ A constructor used to create a **Task** instance. | Name| Type | Mandatory| Description | | ------ | --------- | ---- | -------------------------------------------------------------------- | | func | Function | Yes | Function to be passed in for task execution. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | -| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.| **Error codes** @@ -60,12 +60,12 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -let task = new taskpool.Task(func, "this is my first Task"); +let task = new taskpool.Task(printArgs, "this is my first Task"); ``` ### Attributes @@ -81,7 +81,7 @@ let task = new taskpool.Task(func, "this is my first Task"); execute(func: Function, ...args: unknown[]): Promise\ -Executes a task in the task pool. You must pass in a function and arguments to execute the task, and the task executed in this mode cannot be canceled. +Places the function to be executed in the internal task queue of the task pool. The function will be distributed to the worker thread for execution. The function to be executed in this mode cannot be canceled. **System capability**: SystemCapability.Utils.Lang @@ -89,8 +89,8 @@ Executes a task in the task pool. You must pass in a function and arguments to e | Name| Type | Mandatory| Description | | ------ | --------- | ---- | ---------------------------------------------------------------------- | -| func | Function | Yes | Function used to execute the task. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | -| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).| +| func | Function | Yes | Function to be executed. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types). | +| args | unknown[] | No | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types). The default value is **undefined**.| **Return value** @@ -112,24 +112,24 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let value = await taskpool.execute(func, 100); +async function taskpoolExecute() { + let value = await taskpool.execute(printArgs, 100); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.execute execute(task: Task, priority?: Priority): Promise\ -Executes a task in the task pool. You must pass in a created task, and the task executed in this mode can be canceled. +Places a task in the internal task queue of the task pool. The task will be distributed to the worker thread for execution. The task to be executed in this mode can be canceled. **System capability**: SystemCapability.Utils.Lang @@ -160,18 +160,18 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); +async function taskpoolExecute() { + let task = new taskpool.Task(printArgs, 100); let value = await taskpool.execute(task); console.log("taskpool result: " + value); } -taskpoolTest(); +taskpoolExecute(); ``` ## taskpool.cancel @@ -197,18 +197,18 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | 10200015 | If the task is not exist. | | 10200016 | If the task is running. | -**Example** +**Example of successful task cancellation** ```ts @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { - let task = new taskpool.Task(func, 100); - let value = await taskpool.execute(task); +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); + taskpool.execute(task); try { taskpool.cancel(task); } catch (e) { @@ -216,7 +216,67 @@ async function taskpoolTest() { } } -taskpoolTest(); +taskpoolCancel(); +``` + +**Example of a failure to cancel a task that has been executed** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; +} + +async function taskpoolCancel() { + let task = new taskpool.Task(printArgs, 100); + let value = taskpool.execute(task); + let start = new Date().getTime(); + while (new Date().getTime() - start < 1000) {// Wait for 1s to ensure that the task has been executed. + continue; + } + + try { + taskpool.cancel(task); // The task has been executed and fails to be canceled. + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } +} + +taskpoolCancel(); +``` + +**Example of a failure to cancel an ongoing task** + +```ts +@Concurrent +function printArgs(args) { + console.log("printArgs: " + args); + return args; +} + +async function taskpoolCancel() { + let task1 = new taskpool.Task(printArgs, 100); + let task2 = new taskpool.Task(printArgs, 200); + let task3 = new taskpool.Task(printArgs, 300); + let task4 = new taskpool.Task(printArgs, 400); + let task5 = new taskpool.Task(printArgs, 500); + let task6 = new taskpool.Task(printArgs, 600); + + let res1 = taskpool.execute(task1); + let res2 = taskpool.execute(task2); + let res3 = taskpool.execute(task3); + let res4 = taskpool.execute(task4); + let res5 = taskpool.execute(task5); + let res6 = taskpool.execute(task6); + try { + taskpool.cancel(task1); // task1 is being executed and fails to be canceled. + } catch (e) { + console.log("taskpool.cancel occur error:" + e); + } +} + +taskpoolCancel(); ``` ## Additional Information @@ -228,7 +288,7 @@ The following sequenceable data types are supported: All Primitive Type (excludi - The task pool APIs can be used only in the module with **compileMode** set to **esmodule** in the stage model. To check the **compileMode** setting of a module, open the **build-profile.json5** file of the module and check for **"compileMode": "esmodule"** under **buildOption**. - A task in the task pool can reference only variables passed in by input parameters or imported variables, rather than closure variables. The decorator **@Concurrent** is used to intercept unsupported variables. - A task in the task pool supports only common functions or async functions, rather than class member functions or anonymous functions. The decorator **@Concurrent** is used to intercept unsupported functions. -- The decorator **@Concurrent** can be used only in the .ets file. To create a task in the task pool in the .ts file, use the statement **use concurrent**. +- The decorator **@Concurrent** can be used only in .ets files. ### Using the Task Pool in Simple Mode @@ -237,14 +297,14 @@ The following sequenceable data types are supported: All Primitive Type (excludi ```ts // Common functions are supported, and variables passed in by input parameters are also supported. @Concurrent -function func(args) { - console.log("func: " + args); +function printArgs(args) { + console.log("printArgs: " + args); return args; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(func, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); @@ -253,7 +313,7 @@ async function taskpoolTest() { console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 2** @@ -268,24 +328,24 @@ export var c = 2000; import { c } from "./b"; @Concurrent -function test(a) { +function printArgs(a) { console.log(a); console.log(c); return a; } -async function taskpoolTest() { +async function taskpoolExecute() { // taskpool.execute(task) - let task = new taskpool.Task(test, "create task, then execute"); + let task = new taskpool.Task(printArgs, "create task, then execute"); let val1 = await taskpool.execute(task); console.log("taskpool.execute(task) result: " + val1); // taskpool.execute(function) - let val2 = await taskpool.execute(test, "execute task by func"); + let val2 = await taskpool.execute(printArgs, "execute task by func"); console.log("taskpool.execute(function) result: " + val2); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 3** @@ -293,57 +353,52 @@ taskpoolTest(); ```ts // The async functions are supported. @Concurrent -async function task() { +async function delayExcute() { let ret = await Promise.all([ new Promise(resolve => setTimeout(resolve, 1000, "resolved")) ]); return ret; } -async function taskpoolTest() { - taskpool.execute(task).then((result) => { +async function taskpoolExecute() { + taskpool.execute(delayExcute).then((result) => { console.log("TaskPoolTest task result: " + result); }); } -taskpoolTest(); +taskpoolExecute(); ``` **Example 4** ```ts -// Use use concurrent to create a task in the task pool in the .ts file. -// c.ts -function test1(n) { - "use concurrent" - return n; +// c.ets +@Concurrent +function strSort(inPutArr) { + let newArr = inPutArr.sort(); + return newArr; } -export async function taskpoolTest1() { - console.log("taskpoolTest1 start"); - var task = new taskpool.Task(test1, 100); +export async function func1() { + console.log("taskpoolTest start"); + let strArray = ['c test string', 'b test string', 'a test string']; + var task = new taskpool.Task(strSort, strArray); var result = await taskpool.execute(task); - console.log("taskpoolTest1 result:" + result); + console.log("func1 result:" + result); } -async function test2() { - "use concurrent" - var ret = await Promise.all([ - new Promise(resolve => setTimeout(resolve, 1000, "resolved")) - ]); - return ret; -} -export async function taskpoolTest2() { +export async function func2() { console.log("taskpoolTest2 start"); - taskpool.execute(test2).then((result) => { - console.log("TaskPoolTest2 result: " + result); + let strArray = ['c test string', 'b test string', 'a test string']; + taskpool.execute(strSort, strArray).then((result) => { + console.log("func2 result: " + result); }); } ``` ```ts -/ / a.ets (in the same directory as c.ts) +/ / a.ets (in the same directory as c.ets) import { taskpoolTest1, taskpoolTest2 } from "./c"; -taskpoolTest1(); -taskpoolTest2(); +func1(); +func2(); ``` diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index baeb122c19fccf1a1005b46e98604cb883976256..407929f734381a155dea2be72b2842a6730ecfc6 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -23,7 +23,7 @@ A constructor used to create a **URLParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object
The default value is **null**.| **Example** @@ -150,7 +150,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this object.| **Table 1** callbackFn parameter description @@ -404,7 +404,7 @@ Creates a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object
The default value is an empty string or an empty object.| **Example** @@ -444,7 +444,7 @@ Parses a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object
The default value is an empty string or an empty object.| **Error codes** @@ -522,7 +522,7 @@ A constructor used to create a **URLSearchParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object
The default value is **null**.| **Example** @@ -665,7 +665,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this object.| **Table 1** callbackFn parameter description diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 1a60dc51ae1404aee3947f799c166180ac13dde2..6600939a007d9ac3abd1ad964f3270445cec3a7e 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -547,7 +547,7 @@ A constructor used to create a **TextEncoder** object. | Name| Type| Mandatory| Description| | ----- | ---- | ---- | ---- | -| encoding | string | No| Encoding format.| +| encoding | string | No| Encoding format. The default format is **'utf-8'**.| **Example** @@ -567,7 +567,7 @@ Encodes the input content. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| input | string | No | String to encode.| +| input | string | No | String to encode. The default value is an empty string.| **Return value** @@ -665,7 +665,7 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| input | string | No| String to encode.| +| input | string | No| String to encode. The default value is an empty string.| **Return value** @@ -1646,18 +1646,18 @@ Create a class to implement the **compareTo** method. The **Temperature** class ```js class Temperature{ - constructor(value){ - // If TS is used for development, add the following code: - // private readonly _temp: Temperature; + // If ArkTS is used for development, add the following code: + // private readonly _temp: Temperature; + constructor(value) { this._temp = value; } - compareTo(value){ + compareTo(value) { return this._temp >= value.getTemp(); } - getTemp(){ + getTemp() { return this._temp; } - toString(){ + toString() { return this._temp.toString(); } } diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 3f30f8c0439ea53fb0574a9b062ba4c1cb4492fc..6b9b174376dec02011f7301671b448988eeaa23d 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -108,10 +108,10 @@ Describes the properties of the status bar and navigation bar. | Name | Type| Mandatory| Description | | -------------------------------------- | -------- | ---- | ------------------------------------------------------------ | -| statusBarColor | string | No | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.| +| statusBarColor | string | No | Background color of the status bar. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**. | | isStatusBarLightIcon7+ | boolean | No | Whether any icon on the status bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.| | statusBarContentColor8+ | string | No | Color of the text on the status bar. After this property is set, the setting of **isStatusBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.| -| navigationBarColor | string | No | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.| +| navigationBarColor | string | No | Background color of the navigation bar. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**. | | isNavigationBarLightIcon7+ | boolean | No | Whether any icon on the navigation bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.| | navigationBarContentColor8+ | string | No | Color of the text on the navigation bar. After this property is set, the setting of **isNavigationBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.| @@ -164,7 +164,7 @@ Describes the callback for a single system bar. | type | [WindowType](#windowtype7) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| | isEnable | boolean | Yes | No | Whether the system bar is displayed. The value **true** means that the system bar is displayed, and **false** means the opposite.| | region | [Rect](#rect7) | Yes | No | Current position and size of the system bar. | -| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| +| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | | contentColor | string | Yes | No | Color of the text on the system bar. | ## SystemBarTintState8+ @@ -232,7 +232,7 @@ Describes the window properties. | isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is **false**. The value **true** means that the window is immersive, and **false** means the opposite.| | focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is **true**. The value **true** means that the window can gain focus, and **false** means the opposite.| | touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is **true**. The value **true** means that the window is touchable, and **false** means the opposite.| -| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value **1** indicates the maximum brightness. | +| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value **1** indicates the maximum brightness. If no value is passed, the brightness follows the system. In this case, the obtained brightness value is –1.| | dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value **1** indicates the maximum dimness.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| | isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is **false**. The value **true** means that the screen is always on, and **false** means the opposite.| | isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is **false**. The value **true** means that the window is in privacy mode, and **false** means the opposite.| @@ -824,7 +824,7 @@ create(id: string, type: WindowType, callback: AsyncCallback<Window>): voi Creates a subwindow. 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 [createWindow()](#windowcreatewindow9) instead. **Model restriction**: This API can be used only in the FA model. @@ -860,7 +860,7 @@ create(id: string, type: WindowType): Promise<Window> Creates a subwindow. 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 [createWindow()](#windowcreatewindow9-1) instead. **Model restriction**: This API can be used only in the FA model. @@ -900,7 +900,7 @@ create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback&l Creates a system window. 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 [createWindow()](#windowcreatewindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -936,7 +936,7 @@ create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> Creates a system window. 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 [createWindow()](#windowcreatewindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -975,7 +975,7 @@ find(id: string, callback: AsyncCallback<Window>): void Finds a window based on the ID. 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 [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1008,7 +1008,7 @@ find(id: string): Promise<Window> Finds a window based on the ID. 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 [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1045,7 +1045,7 @@ getTopWindow(callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. > **NOTE** -> +> > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9) instead. **Model restriction**: This API can be used only in the FA model. @@ -1079,7 +1079,7 @@ getTopWindow(): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. > **NOTE** -> +> > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9-1) instead. **Model restriction**: This API can be used only in the FA model. @@ -1112,7 +1112,7 @@ getTopWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. > **NOTE** -> +> > This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1145,7 +1145,7 @@ getTopWindow(ctx: BaseContext): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. > **NOTE** -> +> > This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2542,7 +2542,7 @@ try { ### off('avoidAreaChange')9+ -off(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void +off(type: 'avoidAreaChange', callback?: Callback<{AvoidAreaType, AvoidArea}>): void Disables listening for changes to the area where the window cannot be displayed. @@ -3056,7 +3056,7 @@ let colorSpace = windowClass.getWindowColorSpace(); setWindowBackgroundColor(color: string): void -Sets the background color for this window. In the stage model, this API must be used after [loadContent](#loadcontent9). +Sets the background color for this window. In the stage model, this API must be used after the call of [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9) takes effect. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3091,6 +3091,8 @@ setWindowBrightness(brightness: number, callback: AsyncCallback<void>): vo Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -3132,6 +3134,8 @@ setWindowBrightness(brightness: number): Promise<void> Sets the screen brightness for this window. This API uses a promise to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -5266,7 +5270,7 @@ promise.then((data)=> { setBackgroundColor(color: string, callback: AsyncCallback<void>): void -Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). +Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after the call of [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9) takes effect. > **NOTE** > @@ -5298,7 +5302,7 @@ windowClass.setBackgroundColor(color, (err) => { setBackgroundColor(color: string): Promise<void> -Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). +Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after the call of [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9) takes effect. > **NOTE** > @@ -5336,6 +5340,8 @@ setBrightness(brightness: number, callback: AsyncCallback<void>): void Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + > **NOTE** > > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9) instead. @@ -5368,6 +5374,8 @@ setBrightness(brightness: number): Promise<void> Sets the screen brightness for this window. This API uses a promise to return the result. +When the screen brightness setting for the window takes effect, Control Panel cannot adjust the system screen brightness. It can do so only after the window screen brightness is restored to the default value. + > **NOTE** > > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9-1) instead. diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index edf8e405834d8db590a1f533ae5319b21048dc73..c8910b3df624c6c6ebfab3816a1a21eadaebcc96 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -33,11 +33,11 @@ Provides options that can be set for the **Worker** instance to create. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Readable| Writable| Description | +| Name| Type| Readable| Writable| Description| | ---- | -------- | ---- | ---- | -------------- | -| type | "classic" \| "module" | Yes | Yes | Mode in which the **Worker** instance executes the script. The default value is **classic**. The module **type** is not supported yet.| -| name | string | Yes | Yes | Name of the worker thread.| -| shared | boolean | Yes | Yes | Sharing of the **Worker** instance is not supported yet.| +| type | "classic" \| "module" | Yes | Yes| Mode in which the **Worker** instance executes the script. The **module** type is not supported yet. The default value is **classic**.| +| name | string | Yes | Yes| Name of the worker thread. The default value is **undefined**.| +| shared | boolean | Yes | Yes| Whether sharing of the **Worker** instance is enabled. Currently, sharing is not supported.| ## ThreadWorker9+ @@ -188,8 +188,6 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco ```js const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ts"); -workerInstance.postMessage("hello world"); - var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -207,7 +205,7 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Error codes** @@ -619,7 +617,7 @@ workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is n // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will not be proactively deleted. +// The event listener created by addEventListener will be always valid and will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -859,7 +857,7 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------- | -| message | Object | Yes | Message to be sent to the worker thread. | +| message | Object | Yes | Message to be sent to the host thread. | | transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| **Error codes** @@ -907,8 +905,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| message | Object | Yes | Message to be sent to the host thread. | +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Error codes** @@ -1279,8 +1277,6 @@ Sends a message to the worker thread. The data type of the message must be seque ```js const workerInstance = new worker.Worker("workers/worker.js"); -workerInstance.postMessage("hello world"); - var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -1301,7 +1297,7 @@ Sends a message to the worker thread. The data type of the message must be seque | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Example** @@ -1309,6 +1305,9 @@ Sends a message to the worker thread. The data type of the message must be seque const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); ``` @@ -1490,7 +1489,7 @@ Defines the event handler to be called when the host thread receives a message s | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------------------- | -| event | [MessageEvent](#messageevent)| Yes | Message received.| +| event | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** @@ -1519,7 +1518,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | -| event | [MessageEvent](#messageevent)| Yes | Error data.| +| event | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -1693,19 +1692,41 @@ Implements communication between the worker thread and the host thread. The **po > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. +### postMessage(deprecated) + +postMessage(messageObject: Object, transfer: Transferable[]): void; + +Sends a message to the host thread from the worker thread. + +> **NOTE**
+> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-2). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| messageObject | Object | Yes | Message to be sent to the host thread. | +| transfer| Transferable[] | Yes | Currently, this parameter is not supported. | + ### postMessage9+ postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; Sends a message to the host thread from the worker thread. +> **NOTE** +> +> The **DedicatedWorkerGlobalScope** class is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-2). + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ----------------------------------------------------- | -| message | Object | Yes | Message to be sent to the worker thread. | +| message | Object | Yes | Message to be sent to the host thread. | | transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| **Example** @@ -1738,7 +1759,7 @@ postMessage(messageObject: Object, options?: PostMessageOptions): void Sends a message to the host thread from the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.postMessage9+](#postmessage9-3). **System capability**: SystemCapability.Utils.Lang @@ -1746,8 +1767,8 @@ Sends a message to the host thread from the worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Message to be sent to the worker thread. | -| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +| message | Object | Yes | Message to be sent to the host thread. | +| options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The default value is **undefined**.| **Example** @@ -1778,7 +1799,7 @@ close(): void Terminates the worker thread to stop it from receiving messages. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.close9+](#close9). **System capability**: SystemCapability.Utils.Lang @@ -1806,7 +1827,7 @@ onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.onmessage9+](#onmessage9-1). **System capability**: SystemCapability.Utils.Lang @@ -1815,7 +1836,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | -| ev | [MessageEvent](#messageevent) | Yes | Message received.| +| ev | [MessageEvent](#messageeventt) | Yes | Message received.| **Example** @@ -1842,7 +1863,7 @@ onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+.onmessageerror9+](#onmessageerror9-1). **System capability**: SystemCapability.Utils.Lang @@ -1851,7 +1872,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| -| ev | [MessageEvent](#messageevent)| Yes | Error data.| +| ev | [MessageEvent](#messageeventt) | Yes | Error data.| **Example** @@ -1878,7 +1899,7 @@ Specifies the object whose ownership needs to be transferred during data transfe | Name | Type | Readable| Writable| Description | | -------- | -------- | ---- | ---- | --------------------------------- | -| transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership.| +| transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership. The array cannot contain **null**.| ## Event @@ -1976,7 +1997,7 @@ onerror?: (ev: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. > **NOTE**
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+.onerror9+](#onerror9-1). **System capability**: SystemCapability.Utils.Lang @@ -2212,4 +2233,4 @@ Configuration of the **build-profile.json5** file: } } ``` - + diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 5259aede120c7b89b0ade477f8fb1bb27490cc1a..f8e8f0fff5917b56be67e1f3ab0b21ac949e7ee3 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -27,13 +27,13 @@ A constructor used to create an **XmlSerializer** instance. | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------ | | buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** for storing the XML information to write.| -| encoding | string | No | Encoding format. | +| encoding | string | No | Encoding format. The default value is **'utf-8'** (the only format currently supported). | **Example** ```js let arrayBuffer = new ArrayBuffer(2048); -let thatSer = new xml.XmlSerializer(arrayBuffer,"utf-8"); +let thatSer = new xml.XmlSerializer(arrayBuffer, "utf-8"); thatSer.setDeclaration(); let result = ''; let view = new Uint8Array(arrayBuffer); @@ -363,11 +363,11 @@ console.log(view1) //'' ## XmlPullParser -### XmlPullParser +### constructor constructor(buffer: ArrayBuffer | DataView, encoding?: string) -Creates and returns an **XmlPullParser** object. The **XmlPullParser** object passes two parameters. The first parameter is the memory of the **ArrayBuffer** or **DataView** type, and the second parameter is the file format (UTF-8 by default). +Creates and returns an **XmlPullParser** object. **System capability**: SystemCapability.Utils.Lang @@ -375,8 +375,8 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------ | -| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** that contains XML text information.| -| encoding | string | No | Encoding format. Only UTF-8 is supported. | +| buffer | ArrayBuffer \| DataView | Yes | XML text information to be parsed.| +| encoding | string | No | Encoding format. The default value is **'utf-8'** (the only format currently supported). | **Example** @@ -401,13 +401,9 @@ let strXml = ' ' + ' ' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let i = 0; i < strLen; ++i) { - bufView[i] = strXml.charCodeAt(i); -} -let that = new xml.XmlPullParser(arrayBuffer, 'UTF-8'); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer, 'UTF-8'); let str1 = ''; function func1(name, value){ str1 += name+':'+value; @@ -443,13 +439,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -481,9 +473,9 @@ Defines the XML parsing options. | ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------------- | | supportDoctype | boolean | No | Whether to ignore **Doctype**. The default value is **false**.| | ignoreNameSpace | boolean | No | Whether to ignore **Namespace**. The default value is **false**. | -| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue**. | -| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. | -| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. | +| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue**. The default value is **null**. | +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. The default value is **null**. | +| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. The default value is **null**. | ## ParseInfo @@ -514,13 +506,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -561,13 +549,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -611,13 +595,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -658,13 +638,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -704,13 +680,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -750,13 +722,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -797,13 +765,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -843,13 +807,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -889,13 +849,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; @@ -934,13 +890,9 @@ let strXml = ' Work' + ' Play' + ''; -let arrayBuffer = new ArrayBuffer(strXml.length); -let bufView = new Uint8Array(arrayBuffer); -let strLen = strXml.length; -for (let tmp = 0; tmp < strLen; ++tmp) { - bufView[tmp] = strXml.charCodeAt(tmp); -} -let that = new xml.XmlPullParser(arrayBuffer); +let textEncoder = new util.TextEncoder(); +let arrbuffer = textEncoder.encodeInto(strXml); +let that = new xml.XmlPullParser(arrbuffer.buffer); let arrTag = {}; let str = ""; let i = 0; diff --git a/en/application-dev/reference/arkui-js/js-components-container-div.md b/en/application-dev/reference/arkui-js/js-components-container-div.md index e35eb42639301cfb6ce1a9a45880217ce1daf54b..1cbd9ac9be8e5f4f0dfd3a9db2f91c45d19b10f4 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-div.md +++ b/en/application-dev/reference/arkui-js/js-components-container-div.md @@ -275,7 +275,7 @@ In addition to the [universal methods](js-components-common-methods.md), the fol top:0, }, dragstart(e){ - prompt.showToast({ + promptAction.showToast({ message: 'Start to be dragged' }) }, @@ -385,25 +385,25 @@ In addition to the [universal methods](js-components-common-methods.md), the fol ```js // xxx.js - import prompt from '@system.prompt'; + import promptAction from '@ohos.promptAction'; export default { pinchstart(e){ - prompt.showToast({ + promptAction.showToast({ message: 'pinchstart!!!' }) }, pinchupdate(e){ - prompt.showToast({ + promptAction.showToast({ message: 'Two-finger pinch update' }) }, pinchend(e){ - prompt.showToast({ + promptAction.showToast({ message: 'Finished with two fingers pinching' }) }, pinchcancel(e){ - prompt.showToast({ + promptAction.showToast({ message: 'Finger pinching is interrupted' }) } diff --git a/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif b/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif index 90d9c7bba27ef616fb6bfdea407358df25ac6f91..60d551dd3f1de3a5443bc594c5080b5692704fd0 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif and b/en/application-dev/reference/arkui-ts/figures/LoadingProgress.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/colorFilter.gif b/en/application-dev/reference/arkui-ts/figures/colorFilter.gif new file mode 100644 index 0000000000000000000000000000000000000000..e326b328a292ca96b3c2b687128d51cce1106d27 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/colorFilter.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/list3.gif b/en/application-dev/reference/arkui-ts/figures/list3.gif new file mode 100644 index 0000000000000000000000000000000000000000..fee786913eb846e96189bf852e199d9185c7dafa Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/list3.gif differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md index 12e26b39a1c19111f5e6feaa868d16a18d7b11ac..7ddaa3e007c8403fbd7e3e8f0df85af0ed2bc8a2 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md @@ -1,6 +1,6 @@ # Blank -The **\** component is able to automatically fill the empty spaces in the container along the main axis. It is valid only when the parent container is **\** or **\**. +The **\** component is able to automatically fill the empty spaces in the container along the main axis. It works only when the parent component is **\**, **\**, or **\**. > **NOTE** > @@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.
Default value: **Color.Transparent**
Since API version 9, this API is supported in ArkTS widgets. | +| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.
Default value: **Color.Transparent**
Since API version 9, this API is supported in ArkTS widgets.| ## Events @@ -50,7 +50,7 @@ struct BlankExample { Row() { Text('Bluetooth').fontSize(18) Blank() - Toggle({ type: ToggleType.Switch }) + Toggle({ type: ToggleType.Switch }).margin({ top: 14, bottom: 14, left: 6, right: 6 }) }.width('100%').backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }) }.backgroundColor(0xEFEFEF).padding(20) } @@ -80,16 +80,16 @@ struct BlankExample { Row() { Text('Bluetooth').fontSize(18) Blank().color(Color.Yellow) - Toggle({ type: ToggleType.Switch }) + Toggle({ type: ToggleType.Switch }).margin({ top: 14, bottom: 14, left: 6, right: 6 }) }.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }) Row() { Text('Bluetooth').fontSize(18) // Set the minimum width to 160. Blank('160').color(Color.Yellow) - Toggle({ type: ToggleType.Switch }) + Toggle({ type: ToggleType.Switch }).margin({ top: 14, bottom: 14, left: 6, right: 6 }) }.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 }) - + }.backgroundColor(0xEFEFEF).padding(20).width('100%') } } 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 ef42e734ffcbfe7d5b6b961c3ac2df4278cc5a1e..3457191c2c305ccf440eefe7e50da64e8328f16f 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 @@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** path prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the application has the read permission to the files in the specified path.
**NOTE**
- ArkTS widgets support GIF images, but the images are played only once when they are displayed.
- ArkTS widgets do not support the **http://**, **datashare://**, or **file://data/storage** path prefixes.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type. | +| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the current application. Ensure that the application has the read permission to the files in the specified path.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://**, **datashare://**, or **file:///data/storage** prefix.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type. | ## Attributes @@ -55,7 +55,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the > > To use shortcut keys to copy the image, the image must be in focus. To enable the image to gain focus, set both the **focusable** and **focusOnTouch** attributes to **true**. > -> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, and **animate**. +> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, and **polygon**. ### ImageInterpolation @@ -224,7 +224,7 @@ struct Index { ``` > **NOTE** -> +> > For details about the request mode, timeout, and additional request parameters for loading online images, see [request()](../../reference/apis/js-apis-http.md) in the HTTP module. ### Setting Attributes @@ -415,4 +415,86 @@ struct LoadImageExample { } } ``` - \ No newline at end of file + +### Applying a Filter to an Image + +```ts +// xxx.ets +@Entry +@Component +struct colorFilterExample { + @State colorFilterR: number = 0 + @State colorFilterG: number = 0 + @State colorFilterB: number = 0 + @State colorFilterA: number = 0 + + build() { + Row() { + Column() { + Image($r('app.media.sky')) + .width(200) + .height(200) + Image($r('app.media.sky')) + .width(200) + .height(200) + .colorFilter([ + this.colorFilterR, 0, this.colorFilterR, 0, 0, + 0, this.colorFilterG, this.colorFilterG, 0, 0, + this.colorFilterB, 0, this.colorFilterB, 0, 0, + 0, 0, this.colorFilterA, 0, 0 + ]) + + Row() { + Text('R') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueR) => { + this.colorFilterR = valueR + }) + } + + Row() { + Text('G') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueG) => { + this.colorFilterG = valueG + }) + } + + Row() { + Text('B') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueB) => { + this.colorFilterB = valueB + }) + } + + Row() { + Text('A') + Slider({ + min: 0, + max: 1, + step: 0.01 + }) + .onChange((valueA) => { + this.colorFilterA = valueA + }) + } + }.width('90%').alignItems(HorizontalAlign.Center) + }.height('100%').width('100%').justifyContent(FlexAlign.Center) + } +} +``` + +![colorFilter](figures/colorFilter.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md index 65f7d17c6cc5f494896482669b720539aa07ad41..8917f7f58d697e4afd0097a2e63362fdf58f05b6 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-menu.md @@ -4,7 +4,9 @@ The **\** component is a vertical list of items presented to the user. > **NOTE** > -> This component is supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - This component is supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The **\** component must be used together with the [bindMenu](ts-universal-attributes-menu.md) or [bindContextMenu](ts-universal-attributes-menu.md) method. It does not work when used alone. ## Child Components @@ -22,7 +24,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | -------- | ------------------------- | ---------------------------------------------------------------- | -| fontSize | [Length](ts-types.md#length) | Font size that applies to all texts in the menu. When **Length** is of the number type, the unit is fp.| +| fontSize | [Length](ts-types.md#length) | Font size of the menu text. When **Length** is of the number type, the unit is fp.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md index 85745ba42d26583d369fe5f652c756ae318440f5..2a8ff6b2a1467813858d59cfd701f71ea3a6ce4a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-qrcode.md @@ -22,7 +22,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | string | Yes| Content of the QR code.| +| value | string | Yes| Content of the QR code. A maximum of 256 characters are supported. If the number of characters exceeds 256, the first 256 characters are used.
**NOTE**
The string cannot be **null**, **undefined**, or empty.| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md index d1912c38416cdd17be1e31eb3eaa81f4a97dbff7..e79244d086eba8de02a138bff039dd05245f19b3 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -18,8 +18,8 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll | Name | Type | Mandatory| Description | | ----------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| value | string | No | Text input in the search text box.
Since API version 10, this parameter supports two-way binding through [$$](../../quick-start/arkts-two-way-sync.md).| -| icon | string | No | Path to the search icon. By default, the system search icon is used.
For details about the supported image types, see [Image](ts-basic-components-image.md).| +| value | string | No | Text input in the search text box. | +| icon | string | No | Path to the search icon. By default, the system search icon is used.
**NOTE**
The icon data source can be a local or online image.
- The supported formats include PNG, JPG, BMP, SVG, GIF, and pixelmap.
- The Base64 string is supported in the following format: data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.| | controller | SearchController | No | Controller of the **\** component. | ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md index 6eb019577e5ff468e3b5b344ada6c7ef5b54ea33..fb708e133df835a75c5a52430b27ad57fd5dea77 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -22,7 +22,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | No| Current progress.
Default value: **0**| +| value | number | No| Current progress.
Default value: min| | min | number | No| Minimum value.
Default value: **0**| | max | number | No| Maximum value.
Default value: **100**
**NOTE**
If the value of **min** is greater than or equal to the value of **max**, the default value **0** is used for **min** and the default value **100** is used for **max**.
If the value is not within the [min, max] range, the value of **min** or **max**, whichever is closer.| | step | number | No| Step of the slider.
Default value: **1**
Value range: [0.01, max]
**NOTE**
If this parameter is set to a value less than 0 or a percentage, the default value is used.| @@ -48,7 +48,7 @@ Except touch target attributes, the universal attributes are supported. | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected part of the slider track.
Since API version 9, this API is supported in ArkTS widgets.| | showSteps | boolean | Whether to display the current step.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | showTips | boolean | Whether to display a bubble to indicate the percentage when the user drags the slider.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When **direction** is set to **Axis.Horizontal**, the bubble is displayed right above the slider. When **direction** is set to **Axis.Vertical**, the bubble is displayed on the left of the slider.
The drawing area of the bubble is the overlay of the slider.
If no margin is set for the slider or the margin is not large enough, the bubble will be clipped.| -| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.
Since API version 9, this API is supported in ArkTS widgets.| +| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.
Default value: **4.0vp** when **style** is set to **[SliderStyle](#sliderstyle).OutSet**; **20.0vp** when **style** is set to **[SliderStyle](#sliderstyle).InSet**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the default value.| ## Events 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 7427783669fc717e2b21857f16154c1fa4176817..07b043411ed7ce7658cb575490e559e0dbd3aab0 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 @@ -24,7 +24,7 @@ StepperItem() | -------- | -------- | -------- | | prevLabel | string | Text label of the button on the left, which is not displayed on the first page. When the **\** contains more than one page, the default value for all pages except the first page is **Back**.| | 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 | Display status of **nextLabel** in the stepper.
Default value: **ItemState.Normal**| +| status | [ItemState](#itemstate) | Display status of **nextLabel** in the stepper. Optional.
Default value: **ItemState.Normal**| ## ItemState 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 d2a96a86573880c5fc87ce29e69857a1bcd6b372..55fc4778a2aa43a7dc298093f9000ce3f62d822b 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 @@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | 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 the vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute.
Since API version 9, this API is supported in ArkTS widgets.| +| 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.
This attribute must be used with `maxLines` to take 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.| @@ -109,7 +109,7 @@ struct TextExample1 { Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC) // Clip the text when the value of maxLines is exceeded. Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.') - .textOverflow({ overflow: TextOverflow.None }) + .textOverflow({ overflow: TextOverflow.Clip }) .maxLines(1) .fontSize(12) .border({ width: 1 }) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md index 64a909c1eabdc6db90222c4de5100c6773e3ed42..533f2f6c84cb9429a7e60c8dd42b07c8c2d22f70 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textpicker.md @@ -22,7 +22,7 @@ Creates a text picker based on the selection range specified by **range**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | string[] \| [Resource](ts-types.md#resource) | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed. If it is dynamically changed to an empty array, the current value remains displayed.| +| range | string[] \| [Resource](ts-types.md#resource) | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If it is dynamically changed to an empty array, the current value remains displayed.| | selected | number | No| Index of the default item in the range.
Default value: **0**| | value | string | No| Value of the default item in the range. The priority of this parameter is lower than that of **selected**.
Default value: value of the first item| @@ -40,7 +40,9 @@ In addition to the [universal events](ts-universal-events-click.md), the followi | Name| Description| | -------- | -------- | -| onChange(callback: (value: string, index: number) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item.
- **index**: index of the selected item.| +| onAccept(callback: (value: string, index: number) => void) | Triggered when the OK button in the dialog box is clicked.

- **value**: value of the selected item.
- **index**: index of the selected item.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| +| onCancel(callback: () => void) | Triggered when the Cancel button in the dialog box is clicked.
**NOTE**
This event can be triggered only in the [text picker dialog box](ts-methods-textpicker-dialog.md).| +| onChange(callback: (value: string, index: number) => void) | Triggered when an item in the picker is selected.
- **value**: value of the selected item.
**NOTE**
For a text list or a list consisting of text and images, **value** indicates the text value of the selected item. For an image list, **value** is empty.
- **index**: index of the selected item.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index 191c4839533806a43c41e2c27f500dd10ca18e8d..92cf701ae4d215871c9dadd9edb6cab814ba8980 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -31,9 +31,9 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Description | | -------- | ---------------- | -| Checkbox | Check box type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: 12 vp,
right: 12 vp,
bottom: 12 vp,
left: 12 vp
} | +| Checkbox | Check box type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: 12 px,
right: 12 px,
bottom: 12 px,
left: 12 px
} | | Button | Button type. The set string, if any, will be displayed inside the button. | -| Switch | Switch type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: 14 vp,
right:6 vp,
bottom: 6 vp,
left: 14 vp
} | +| Switch | Switch type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: 14 vp,
right:6 vp,
bottom: 14 vp,
left: 6 vp
} | ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index 35211ab1665ca4dbee56199a3c449ae9ff2a8a0b..8801033ff3864cef03d0271db00a8d1dfb92d3da 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -22,7 +22,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ------ | ------ | ---- | --------- | ---------------------------- | | offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.| -| color | string | Yes | '#ffffff' | Gradient color to set. | +| color | string | Yes | '#ffffff' | Gradient color to set. For details about the color notation, see the description of the string type in [ResourceColor](ts-types.md#resourcecolor). | **Example** 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 25d75ce08f639ab0aeba31c2bf035f4e9a060f1e..f53f633da9cb814ffc843d3a9b9ac47319a35f8c 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -10,7 +10,7 @@ The **\** component provides a list container that presents a series of li ## Child Components -This component supports the **[\](ts-container-listitem.md)** and **[\](ts-container-listitemgroup.md)** child components. +This component supports the [\](ts-container-listitem.md) and [\](ts-container-listitemgroup.md) child components. > **NOTE** > @@ -52,14 +52,14 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | | listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider. This attribute cannot be set in percentage.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| -| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| +| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets. | | cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| -| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9.
Default value: **false**| +| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| | chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.| | multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the maximum width of list items in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets. | +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| | alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| | sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| @@ -71,7 +71,7 @@ This API is supported in ArkTS widgets. | ------ | -------------------------------------- | | Start | The list items are packed toward the start edge of the **\** component along the cross axis.| | Center | The list items are centered in the **\** component along the cross axis.| -| End | The list items are packed toward the end edge of the **\** component in the cross axis.| +| End | The list items are packed toward the end edge of the **\** component along the cross axis.| ## StickyStyle9+ @@ -79,7 +79,7 @@ This API is supported in ArkTS widgets. | Name | Description | | ------ | -------------------------------------- | -| None | In the **\** component, the header is not pinned to the top, and the footer is not pinned to the bottom.| +| None | In the **\** component, the header is not pinned to the top, and the footer is not pinned to the bottom.| | Header | In the **\** component, the header is pinned to the top, and the footer is not pinned to the bottom.| | Footer | In the **\** component, the footer is pinned to the bottom, and the header is not pinned to the top.| @@ -91,19 +91,19 @@ This API is supported in ArkTS widgets. | Name| Description| | -------- | -------- | -| onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| +| onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| | onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
This event is not triggered when **ScrollEdge** and **ScrollToIndex** are called by using the controller. In other cases, this event is triggered when scrolling occurs.
Since API version 9, this API is supported in ArkTS widgets.| -| onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or exits from the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or leaves the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| | onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| -| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| +| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| | onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current sliding status.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| | onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.
This API is supported in ArkTS widgets.| -| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| | onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.
- **from**: index of the item before moving.
- **to**: index of the item after moving.| | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the dragged list element.| | onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).| | onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: initial position of the dragged item.
- **insertIndex**: index of the position to which the dragged item will be dropped.| -| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the list item.| +| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item leaves the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the list item.| | onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: initial position of the dragged item.
- **insertIndex**: index of the position to which the dragged item will be dropped.
- **isSuccess**: whether the dragged item is successfully dropped.
**NOTE**
During dragging across lists, **true** is returned if the drop target is bound to **onItemDrop**. Otherwise, **false** is returned. During dragging within a list, **isSuccess** is the return value of the **onItemMove** event.| ## ScrollState @@ -113,7 +113,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Description | | ------ | ------------------------- | | Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged.| -| Scroll | Finger dragging. Triggered when the user drags the list to scroll.| +| Scroll | Finger dragging. Triggered when the user drags the list to scroll.| | Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.| > **NOTE** @@ -133,7 +133,7 @@ Since API version 9, this API is supported in ArkTS widgets. > - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback. -## Example +## Example 1 ```ts // xxx.ets @@ -172,6 +172,9 @@ struct ListExample { ![en-us_image_0000001174264378](figures/en-us_image_0000001174264378.gif) + +## Example 2 + ```ts // xxx.ets @Entry @@ -198,7 +201,6 @@ struct ListLanesExample { } .height(300) .width("90%") - .editMode(true) .border({ width: 3, color: Color.Red }) .lanes({ minLength: 40, maxLength: 40 }) .alignListItem(this.alignListItem) @@ -218,3 +220,57 @@ struct ListLanesExample { ``` ![list](figures/list1.gif) + + +## Example 3 + +```ts +// xxx.ets +@Entry +@Component +struct ListExample{ + @State arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + @State editFlag: boolean = false + + build(){ + Stack({alignContent: Alignment.TopStart}) { + Column(){ + List({space:20, initialIndex:0}) { + ForEach(this.arr, (item, index) => { + ListItem() { + Flex({direction: FlexDirection.Row, alignItems: ItemAlign.Center}) { + Text('' + item) + .width('100%') + .height(80) + .fontSize(20) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + .flexShrink(1) + if (this.editFlag) { + Button() { + Text("delete").fontSize(16) + }.width('30%').height(40) + .onClick(() => { + console.info(this.arr[index] + 'Delete') + this.arr.splice(index, 1) + console.info(JSON.stringify(this.arr)) + this.editFlag = false + }).stateEffect(true) + } + } + } + }, item => item) + }.width('90%') + }.width('100%') + + Button('edit list') + .onClick(() => { + this.editFlag = !this.editFlag + }).margin({ top: 5, left: 20 }) + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) + } +} +``` + +![list](figures/list3.gif) 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 7cd62c1323780d8ea22835b7ae8cdebac7952a5b..6819991d4c66ba1a96ca51dc4d56e7d900d24c0f 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -33,21 +33,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | --------------------------- | ---------------------------------------- | ---------------------------------------- | -| index | number | Index of the child component currently displayed in the container.
Default value: **0**
**NOTE**
If the value is less than 0 or greater than or equal to the number of child components, the default value **0** is used.
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| -| autoPlay | boolean | Whether to enable automatic playback for child component switching.
Default value: **false**
**NOTE**
If **loop** is set to **false**, the rotation stops when the last page is displayed. The playback continues when the page is not the last page after a swipe gesture. | +| index | number | Index of the child component currently displayed in the container.
Default value: **0**
**NOTE**
If the value is less than 0 or greater than or equal to the number of child components, the default value **0** is used.| +| autoPlay | boolean | Whether to enable automatic playback for child component switching.
Default value: **false**
**NOTE**
If **loop** is set to **false**, the playback stops when the last page is displayed. The playback continues when the page is not the last page after a swipe gesture.| | interval | number | Interval for automatic playback, in ms.
Default value: **3000** | | indicator | boolean | Whether to enable the navigation dots indicator.
Default value: **true** | | loop | boolean | Whether to enable loop playback.
The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.
Default value: **true**| | duration | number | Duration of the animation for switching child components, in ms.
Default value: **400** | | vertical | boolean | Whether vertical swiping is used.
Default value: **false** | -| itemSpace | number \| string | Space between child components.
Default value: **0**
**NOTE**
This parameter cannot be set in percentage.| +| itemSpace | number \| string | Space between child components.
Default value: **0**
**NOTE**
This parameter cannot be set in percentage.| | displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.
Default value: **SwiperDisplayMode.Stretch**| -| cachedCount8+ | number | Number of child components to be cached.
Default value: **1** | +| cachedCount8+ | number | Number of child components to be cached.
Default value: **1**
**NOTE**
**cachedCount** has caching optimized. You are advised not to use it together with [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md).| | disableSwipe8+ | boolean | Whether to disable the swipe feature.
Default value: **false** | -| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.
Default value: **Curve.Ease**| -| indicatorStyle8+ | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md),
selectedColor?: [ResourceColor](ts-types.md)
} | Style of the navigation dots indicator.
\- **left**: distance between the navigation dots indicator and the left edge of the **\** component.
\- **top**: distance between the navigation dots indicator and the top edge of the **\** component.
\- **right**: distance between the navigation dots indicator and the right edge of the **\** component.
\- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\** component.
\- **size**: diameter of the navigation dots indicator.
\- **mask**: whether to enable the mask for the navigation dots indicator.
\- **color**: color of the navigation dots indicator.
\- **selectedColor**: color of the selected navigation dot.| -| displayCount8+ | number\|string | Number of elements to display per page.
Default value: **1** | -| effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring** | +| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.
Default value: **Curve.Linear**| +| indicatorStyle8+ | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md),
selectedColor?: [ResourceColor](ts-types.md)
} | Style of the navigation point indicator.
\- **left**: distance between the navigation point indicator and the left edge of the **\** component.
\- **top**: distance between the navigation point indicator and the top edge of the **\** component.
\- **right**: distance between the navigation point indicator and the right edge of the **\** component.
\- **bottom**: distance between the navigation point indicator and the bottom edge of the **\** component.
\- **size**: diameter of the navigation point indicator.
\- **mask**: whether to enable the mask for the navigation point indicator.
\- **color**: color of the navigation point indicator.
\- **selectedColor**: color of the selected navigation dot.| +| displayCount8+ | number \| string | Number of elements to display per page.
Default value: **1**
**NOTE**
If the value is of the string type, it can only be **'auto'**, whose display effect is the same as that of **SwiperDisplayMode.AutoLinear**.
If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount - 1)] is evenly distributed among them on the main axis.| +| effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**
**NOTE**
The spring effect does not take effect when the controller API is called.| ## SwiperDisplayMode diff --git a/en/application-dev/reference/arkui-ts/ts-container-waterflow.md b/en/application-dev/reference/arkui-ts/ts-container-waterflow.md index 76507f08dfd3debfb83504d54ce4344e870e0524..44d2eeda5df735e9f81dbb9713b899cbd66037be 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-waterflow.md +++ b/en/application-dev/reference/arkui-ts/ts-container-waterflow.md @@ -14,6 +14,9 @@ The **\** component is a container that consists of cells formed by r The [\](ts-container-flowitem.md) child component is supported. +> **NOTE** +> +> When the **visibility** attribute of a child component in **\** is set to **None**, the child component is not displayed, but still takes up cells. ## APIs @@ -257,9 +260,11 @@ struct WaterflowDemo { Text("N" + item).fontSize(12).height('16') Image('res/waterFlowTest(' + item % 5 + ').jpg') .objectFit(ImageFit.Fill) + .width('100%') + .layoutWeight(1) } } - .width(this.itemWidthArray[item]) + .width('100%') .height(this.itemHeightArray[item]) .backgroundColor(this.colors[item % 5]) }, item => item) diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index e5cedbf9e226c3b37ce9c0a525c70376075f6187..b2903343a1acb957d5563cc100a0e150a463732f 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -24,9 +24,9 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P | Name | Type | Mandatory| Description | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string \| [Resource](ts-types.md) | No | Path of the video source, which can be a local path or a URL.
The video resources can be stored in the **video** or **rawfile** folder under **resources**.
The path can include a **dataability://** prefix, which indicates that the path is provided by a Data ability. For details about the path, see [Data Ability Development](../../application-models/dataability-overview.md).
**NOTE**
The supported video formats are MP4, MKV, WebM, and TS.| +| src | string \| [Resource](ts-types.md) | No | Path of the video source, which can be a local path or a URL.
The video resources can be stored in the **video** or **rawfile** folder under **resources**.
The path can include a **dataability://** prefix, which indicates that the path is provided by a Data ability. For details about the path, see [Data Ability Development](../../application-models/dataability-overview.md).
- Strings with the **file:///data/storage** prefix are supported, which are used to read resources in the application sandbox. Ensure that the application has the read permission to the files in the specified path.
**NOTE**
The supported video formats are MP4, MKV, WebM, and TS. | | currentProgressRate | number \| string \| PlaybackSpeed8+ | No | Video playback speed.
**NOTE**
The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**.
Default value: 1.0 \| PlaybackSpeed.Speed_Forward_1_00_X | -| previewUri | string \|PixelMap \| [Resource](ts-types.md) | No | Path of the preview image. (The PixelMap type is not supported currently.) | +| previewUri | string \|PixelMap \| [Resource](ts-types.md) | No | Path of the preview image. | | controller | [VideoController](#videocontroller) | No | Video controller. | ## PlaybackSpeed8+ diff --git a/en/application-dev/reference/arkui-ts/ts-pixel-units.md b/en/application-dev/reference/arkui-ts/ts-pixel-units.md index 4f7099cc28fffbe5b72c6fa3ddd5fe0cfa1b969f..8a820840da5c7a8d5ad232f16f548acd585ed262 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -3,12 +3,12 @@ The framework provides four pixel units, with vp as the reference data unit. -| Name | Description | -| ---- | ---------------------------------------- | -| px | Physical pixel unit of the screen. | -| vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified.| -| fp | Font pixel, which is similar to vp and varies according to the system font size. | -| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels.| +| Name| Description | +| ---- | ------------------------------------------------------------ | +| px | Physical pixel unit of the screen. | +| vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified. On a screen with an actual width of 1440 physical pixels, 1 vp is approximately equal to 3 px.| +| fp | Font pixel, which is similar to vp and varies according to the system font size.| +| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1 lpx is equal to 2 px for a screen with an actual width of 1440 physical pixels.| ## Pixel Unit Conversion @@ -37,33 +37,71 @@ struct Example { Flex({ wrap: FlexWrap.Wrap }) { Column() { Text("width(220)") - .width(220).height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width(220) + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("width('220px')") - .width('220px').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White) + .width('220px') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) }.margin(5) + Column() { Text("width('220vp')") - .width('220vp').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width('220vp') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("width('220lpx') designWidth:720") - .width('220lpx').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width('220lpx') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("width(vp2px(220) + 'px')") - .width(vp2px(220) + 'px').height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12vp') + .width(vp2px(220) + 'px') + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12vp') }.margin(5) + Column() { Text("fontSize('12fp')") - .width(220).height(40).backgroundColor(0xF9CF93) - .textAlign(TextAlign.Center).fontColor(Color.White).fontSize('12fp') + .width(220) + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12fp') + }.margin(5) + + Column() { + Text("width(px2vp(220))") + .width(px2vp(220)) + .height(40) + .backgroundColor(0xF9CF93) + .textAlign(TextAlign.Center) + .fontColor(Color.White) + .fontSize('12fp') }.margin(5) }.width('100%') } diff --git a/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md b/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md index cd072648a81f68b080ae88b9a90cf6a157376dc6..ff60c8526b70cd848293f696699a6bd5f4fe26c0 100644 --- a/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md +++ b/en/application-dev/reference/arkui-ts/ts-transition-animation-component.md @@ -19,10 +19,10 @@ Configure the component transition animations for when a component is inserted o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type, which includes component addition and deletion by default.
Default value: **TransitionType.All**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If **type** is not specified, insertion and deletion use the same transition type.| -| opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.
Default value: **1**
Value range: [0, 1]
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.| +| opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.
Default value: **1**
Value range: [0, 1]
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 or greater than 1 evaluates to the value **1**.| | translate | {
x? : number \| string,
y? : number \| string,
z? : number \| string
} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
-**x**: distance to translate along the x-axis.
-**y**: distance to translate along the y-axis.
-**z**: distance to translate along the z-axis.
Since API version 9, this API is supported in ArkTS widgets.| | scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: scale factor along the x-axis.
- **y**: scale factor along the y-axis.
- **z**: scale factor along the z-axis.
- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively. The default values are both **"50%"**.
- If the center point is 0, it indicates the upper left corner of the component.
Since API version 9, this API is supported in ArkTS widgets.| -| rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: rotation vector along the x-axis.
- **y**: rotation vector along the y-axis.
- **z**: rotation vector along the z-axis.
- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively. The default values are both **"50%"**.
- If the center point is (0, 0), it indicates the upper left corner of the component.
Since API version 9, this API is supported in ArkTS widgets.| +| rotate | {
x?: number,
y?: number,
z?: number,
angle: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.
- **x**: rotation vector along the x-axis.
- **y**: rotation vector along the y-axis.
- **z**: rotation vector along the z-axis.
- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively. The default values are both **"50%"**.
- If the center point is (0, 0), it indicates the upper left corner of the component.
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md index 001cc3473099f87b794b39aa398aeedcc4878bfe..8032455b78bf4a4e5654dfc939f23cfbdeafc2e3 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-gradient-color.md @@ -13,8 +13,8 @@ Create a more gorgeous look for a component by applying a gradient color effect | Name | Type | Description | | -------------- | -------------------------------------------- | ----------------------------------- | | linearGradient | {
angle?: number \| string,
direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Linear gradient.
- **angle**: start angle of the linear gradient. A positive value indicates a clockwise rotation from the origin, (0, 0).
Default value: **180**
- **direction**: direction of the linear gradient. It does not take effect when **angle** is set.
Default value: **GradientDirection.Bottom**
- **colors**: colors of the linear gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| -| sweepGradient | {
center: Point,
start?: number \| string,
end?: number \| string,
rotation?: number\|string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Sweep gradient, which can sweep around the specified center point in the 0–360 degree range. If the rotation angle exceeds the range, a monochrome color instead of a gradient will be drawn.
- **center**: center point of the sweep gradient, that is, the coordinates relative to the upper left corner of the current component.
- **start**: start point of the sweep gradient.
Default value: **0**
- **end**: end point of the sweep gradient.
Default value: **0**
- **rotation**: rotation angle of the sweep gradient.
Default value: **0**
- **colors**: colors of the sweep gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the value **0**. A value greater than 360 evaluates to the value **1**.
When the data type of **start**, **end**, and **rotation** is string, the value **"90"** or **"90%"** is equivalent to **90**.| -| radialGradient | {
center: Point,
radius: number \| string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Radial gradient.
- **center**: center point of the radial gradient, that is, the coordinates relative to the upper left corner of the current component.
- **radius**: radius of the radial gradient.
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the value **0**.
- **colors**: colors of the radial gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| +| sweepGradient | {
center: [Point](./ts-drawing-components-polygon.md#point),
start?: number \| string,
end?: number \| string,
rotation?: number\|string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Sweep gradient, which can sweep around the specified center point in the 0–360 degree range. If the rotation angle exceeds the range, a monochrome color instead of a gradient will be drawn.
- **center**: center point of the sweep gradient, that is, the coordinates relative to the upper left corner of the current component.
- **start**: start point of the sweep gradient.
Default value: **0**
- **end**: end point of the sweep gradient.
Default value: **0**
- **rotation**: rotation angle of the sweep gradient.
Default value: **0**
- **colors**: colors of the sweep gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
A value less than 0 evaluates to the value **0**. A value greater than 360 evaluates to the value **1**.
When the data type of **start**, **end**, and **rotation** is string, the value **"90"** or **"90%"** is equivalent to **90**.| +| radialGradient | {
center: [Point](./ts-drawing-components-polygon.md#point),
radius: number \| string,
colors: Array<[ColorStop](ts-basic-components-gauge.md#colorstop)>,
repeating?: boolean
} | Radial gradient.
- **center**: center point of the radial gradient, that is, the coordinates relative to the upper left corner of the current component.
- **radius**: radius of the radial gradient.
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the value **0**.
- **colors**: colors of the radial gradient.
- **repeating**: whether the colors are repeated.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md index cf02ba55e1483bf32b09caf519f603183ea6064e..583518b134041ca1ab7607ba0d34e7d46395fdb2 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-menu.md @@ -1,10 +1,12 @@ # Menu Control -A menu – a vertical list of items – can be bound to a component and displayed by long-pressing, clicking, or right-clicking the component. +A context menu – a vertical list of items – can be bound to a component and displayed by long-pressing, clicking, or right-clicking the component. > **NOTE** > -> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> +> - **CustomBuilder** does not support the use of **bindMenu** and **bindContextMenu** methods. To display a multi-level menu, use the [\](ts-basic-components-menu.md) component instead. ## Attributes diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-gradient.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-gradient.md index fbfe2c4db91511503d37bba3ad2100a912aee020..2c338d915e21c6a66ba684824739914c86966ff8 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-gradient.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-gradient.md @@ -33,54 +33,52 @@ background: repeating-linear-gradient(direction/angle, color, color, ...); The color can be specified in any of the following formats: \#ff0000, \#ffff0000, rgb(255, 0, 0), and rgba(255, 0, 0, 1). At least two colors must be specified. -- Parameters +**Parameters** - | Name | Type | Default Value | Mandatory | Description | - | --------- | ---------------------------------------- | ---------------------------- | ---- | ---------------------------------------- | - | direction | to <side-or-corner> <side-or-corner> = [left \| right] \|\| [top \| bottom] | to bottom (gradient from top to bottom)| No | Transition direction. For example, **to left** (gradient from right to left) or **to bottom right** (gradient from upper left corner to lower right corner).| - | angle | <deg> | 180deg | No | Transition direction, which is the angle between the gradient line and the y-axis (in the clockwise direction), with the geometric center of the element being the origin of coordinates and the horizontal axis being the x-axis.| - | color | <color> [<length>\|<percentage>] | - | Yes | Colors among which smooth transitions are rendered. | +| Name | Type | Default Value | Mandatory | Description | +| --------- | ---------------------------------------- | ---------------------------- | ---- | ---------------------------------------- | +| direction | to <side-or-corner> <side-or-corner> = [left \| right] \|\| [top \| bottom] | to bottom (gradient from top to bottom)| No | Transition direction. For example, **to left** (gradient from right to left) or **to bottom right** (gradient from upper left corner to lower right corner).| +| angle | <deg> | 180deg | No | Transition direction, which is the angle between the gradient line and the y-axis (in the clockwise direction), with the geometric center of the element being the origin of coordinates and the horizontal axis being the x-axis.| +| color | <color> [<length>\|<percentage>] | - | Yes | Colors among which smooth transitions are rendered. | -- Example +**Example** - 1. Gradient from top to bottom (default) +1. Gradient from top to bottom (default) - ```css - #gradient { - height: 300px; - width: 600px; - /* Gradient starts from red at the top to green at the bottom. */ - background: linear-gradient(red, #00ff00); - } - ``` + ```css + #gradient { + height: 300px; + width: 600px; + /* Gradient starts from red at the top to green at the bottom. */ + background: linear-gradient(red, #00ff00); + } + ``` - ![111](figures/111.PNG) + ![111](figures/111.PNG) - 2. Gradient at an angle of 45° +2. Gradient at an angle of 45° + ```css + /* Gradient at an angle of 45°, changing from red to green */ + background: linear-gradient(45deg, rgb(255, 0, 0),rgb(0, 255, 0)); + ``` - ```css - /* Gradient at an angle of 45°, changing from red to green */ - background: linear-gradient(45deg, rgb(255, 0, 0),rgb(0, 255, 0)); - ``` + ![222](figures/222.PNG) - ![222](figures/222.PNG) +3. Gradient from left to right - 3. Gradient from left to right + ```css + /* Gradient from left to right, which is available in the 270 px width between the left 90 px and the left 360 px (600*0.6) */ + background: linear-gradient(to right, rgb(255, 0, 0) 90px, rgb(0, 255, 0) 60%); + ``` - ```css - /* Gradient from left to right, which is available in the 270 px width between the left 90 px and the left 360 px (600*0.6) */ - background: linear-gradient(to right, rgb(255, 0, 0) 90px, rgb(0, 255, 0) 60%); - ``` + ![333](figures/333.PNG) +4. Repeating gradient - ![333](figures/333.PNG) + ```css + /* Repeating gradient from left to right, the area of which is 30 px (60 – 30) and the opacity is 0.5 */ + background: repeating-linear-gradient(to right, rgba(255, 255, 0, 1) 30vp,rgba(0, 0, 255, .5) 60vp); + ``` - 4. Repeating gradient - - ```css - /* Repeating gradient from left to right, the area of which is 30 px (60 – 30) and the opacity is 0.5 */ - background: repeating-linear-gradient(to right, rgba(255, 255, 0, 1) 30vp,rgba(0, 0, 255, .5) 60vp); - ``` - - ![444](figures/444.PNG) + ![444](figures/444.PNG) diff --git a/en/application-dev/reference/native-apis/_mind_spore.md b/en/application-dev/reference/native-apis/_mind_spore.md index 7e546e8f958341e55b9f59cd4123b274c78cc0f1..ded41297291a904a08793bd2cd94e2ab667a10a0 100644 --- a/en/application-dev/reference/native-apis/_mind_spore.md +++ b/en/application-dev/reference/native-apis/_mind_spore.md @@ -5,14 +5,6 @@ Provides APIs related to MindSpore Lite model inference. -Copyright 2021 Huawei Technologies Co., Ltd - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - -[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) - -Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - \@Syscap SystemCapability.Ai.MindSpore **Since:** diff --git a/en/application-dev/reference/native-apis/image.md b/en/application-dev/reference/native-apis/image.md index 218c78042c84bc5a43edf57b4849d08c0f6808a4..365d04c8dca0a1b718593337237a8e5fb4f0bcb9 100644 --- a/en/application-dev/reference/native-apis/image.md +++ b/en/application-dev/reference/native-apis/image.md @@ -1,13 +1,14 @@ # Image -## Overview - Provides APIs for obtaining pixel map data and information. -\@Syscap SystemCapability.Multimedia.Image +To use the APIs in this file, **libpixelmap_ndk.z.so** is required. + +@Syscap SystemCapability.Multimedia.Image + +**Since** -**Since:** 8 @@ -16,150 +17,180 @@ Provides APIs for obtaining pixel map data and information. ### Files -| Name | Description | +| Name| Description| | -------- | -------- | -| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | Declares the APIs that can lock, access, and unlock pixel map data.
File to Include: | +| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | Declares the APIs that can lock, access, and unlock a pixel map.
File to include:: | ### Structs -| Name | Description | +| Name| Description| | -------- | -------- | -| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | Defines the pixel map information. | -| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | Defines the options used for creating a pixel map. | +| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | Defines the pixel map information.| +| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | Defines the options used for creating a pixel map.| ### Types -| Name | Description | +| Name| Description| | -------- | -------- | -| [NativePixelMap](#nativepixelmap) | Defines the data type name of the native pixel map. | +| [NativePixelMap](#nativepixelmap) | Defines the data type name of the native pixel map.| ### Enums -| Name | Description | +| Name| Description| | -------- | -------- | -| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | Enumerates the error codes returned by a function. | -| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | Enumerates the pixel formats. | -| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | Enumerates the pixel map alpha types. | -| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | Enumerates the pixel map scale modes. | -| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | Enumerates the pixel map editing types. | +| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | Enumerates the error codes returned by the functions.| +| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | Enumerates the pixel formats.| +| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | Enumerates the pixel map alpha types.| +| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | Enumerates the pixel map scale modes.| +| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | Enumerates the pixel map editing types.| ### Functions -| Name | Description | -| -------- | -------- | -| [OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) structure. | -| [OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | Obtains the memory address of the **PixelMap** object data and locks the memory. | -| [OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | Unlocks the memory of the **PixelMap** object data. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs. | -| [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | Creates a **PixelMap** object. | -| [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | Creates a **PixelMap** object that contains only alpha channel information. | -| [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | Initializes a **PixelMap** object. | -| [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | Obtains the number of bytes per row of a **PixelMap** object. | -| [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*[editable](image__pixel__map__napi_8h.md#editable)) | Checks whether a **PixelMap** object is editable. | -| [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | Checks whether a **PixelMap** object supports alpha channels. | -| [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | Sets an alpha channel for a **PixelMap** object. | -| [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | Obtains the pixel density of a **PixelMap** object. | -| [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | Sets the pixel density for a **PixelMap** object. | -| [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | Sets the opacity for a **PixelMap** object. | -| [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Scales a **PixelMap** object. | -| [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Translates a **PixelMap** object. | -| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | Rotates a **PixelMap** object. | -| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | Flips a **PixelMap** object. | -| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](image__pixel__map__napi_8h.md#width), int32_t [height](image__pixel__map__napi_8h.md#height)) | Crops a **PixelMap** object. | +| Name| Description| +| -------- | -------- | +| [OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) struct.| +| [OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | Obtains the memory address of a **PixelMap** object and locks the memory.| +| [OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | Unlocks the memory of a **PixelMap** object. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs.| +| [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | Creates a **PixelMap** object.| +| [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | Creates a **PixelMap** object that contains only alpha channel information.| +| [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | Initializes a **PixelMap** object.| +| [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | Obtains the number of bytes per row of a **PixelMap** object.| +| [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*[editable](image__pixel__map__napi_8h.md#editable)) | Checks whether a **PixelMap** object is editable.| +| [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | Checks whether a **PixelMap** object supports alpha channels.| +| [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | Sets an alpha channel for a **PixelMap** object.| +| [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | Obtains the pixel density of a **PixelMap** object.| +| [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | Sets the pixel density for a **PixelMap** object.| +| [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | Sets the opacity for a **PixelMap** object.| +| [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Scales a **PixelMap** object.| +| [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | Translates a **PixelMap** object.| +| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | Rotates a **PixelMap** object.| +| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | Flips a **PixelMap** object.| +| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](image__pixel__map__napi_8h.md#width), int32_t [height](image__pixel__map__napi_8h.md#height)) | Crops a **PixelMap** object.| + ## Type Description ### NativePixelMap - + ``` -typedef struct NativePixelMapNativePixelMap +typedef struct NativePixelMap ``` -**Description:**
+**Description** + Defines the data type name of the native pixel map. +**Since** + +9 + + ## Enum Description ### anonymous enum - + ``` anonymous enum ``` -**Description**
-Enumerates the error codes returned by a function. +**Description** + +Enumerates the error codes returned by the functions. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_IMAGE_RESULT_SUCCESS | Operation success. | -| OHOS_IMAGE_RESULT_BAD_PARAMETER | Invalid value. | +| OHOS_IMAGE_RESULT_SUCCESS| Operation success.| +| OHOS_IMAGE_RESULT_BAD_PARAMETER| Invalid value.| +**Since** + +8 ### anonymous enum - + ``` anonymous enum ``` -**Description**
+**Description** + Enumerates the pixel formats. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_FORMAT_NONE | Unknown format. | -| OHOS_PIXEL_MAP_FORMAT_RGBA_8888 | 32-bit RGBA, with 8 bits each for R (red), G (green), B (blue), and A (alpha). The data is stored from the most significant bit to the least significant bit. | -| OHOS_PIXEL_MAP_FORMAT_RGB_565 | 16-bit RGB, with 5, 6, and 5 bits for R, G, and B, respectively. The storage sequence is from the most significant bit to the least significant bit. | +| OHOS_PIXEL_MAP_FORMAT_NONE| Unknown format.| +| OHOS_PIXEL_MAP_FORMAT_RGBA_8888| 32-bit RGBA, with 8 bits each for R (red), G (green), B (blue), and A (alpha). The data is stored from the most significant bit to the least significant bit.| +| OHOS_PIXEL_MAP_FORMAT_RGB_565| 16-bit RGB, with 5, 6, and 5 bits for R, G, and B, respectively. The storage sequence is from the most significant bit to the least significant bit.| + +**Since** + +8 ### anonymous enum - + ``` anonymous enum ``` -**Description:**
+**Description** + Enumerates the pixel map alpha types. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN | Unknown format. | -| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE | Opaque format. | -| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL | Premultiplied format. | -| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL | Unpremultiplied format. | +| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN| Unknown format.| +| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE| Opaque format.| +| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL| Premultiplied format.| +| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL| Unpremultiplied format.| + +**Since** +9 ### anonymous enum - + ``` anonymous enum ``` -**Description:**
+**Description** + Enumerates the pixel map scale modes. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE | Adaptation to the target image size. | -| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP | Cropping the center portion of an image to the target size. | +| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE| Adaptation to the target image size.| +| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP| Cropping the center portion of an image to the target size.| + +**Since** + +9 ### anonymous enum - + ``` anonymous enum ``` -**Description:**
+**Description** + Enumerates the pixel map editing types. -| Name | Description | +| Value| Description| | -------- | -------- | -| OHOS_PIXEL_MAP_READ_ONLY | Read-only. | -| OHOS_PIXEL_MAP_EDITABLE | Editable. | +| OHOS_PIXEL_MAP_READ_ONLY| Read-only.| +| OHOS_PIXEL_MAP_EDITABLE| Editable.| + +**Since** + +9 ## Function Description @@ -167,561 +198,552 @@ Enumerates the pixel map editing types. ### OH_AccessPixels() - + ``` int32_t OH_AccessPixels (napi_env env, napi_value value, void ** addrPtr ) ``` -**Description**
-Obtains the memory address of the **PixelMap** object data and locks the memory. +**Description** + +Obtains the memory address of a **PixelMap** object and locks the memory. -After the function is executed successfully, **\*addrPtr** is the address of the memory to be accessed. After the access operation is complete, you must use [OH_UnAccessPixels](#oh_unaccesspixels) to unlock the memory. Otherwise, the resources in the memory cannot be released. After being unlocked, the memory address cannot be accessed or operated. +After the function is executed successfully, **\*addrPtr** is the address of the memory to be accessed. After the access operation is complete, you must use [OH_UnAccessPixels](#oh_unaccesspixels) to unlock the memory. Otherwise, the resources in the memory cannot be released. After the memory is unlocked, its address cannot be accessed or operated. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | -| addrPtr | Indicates the double pointer to the memory address. | +| env | Indicates the NAPI environment pointer.| +| value | Indicates the **PixelMap** object at the application layer.| +| addrPtr | Indicates the double pointer to the memory address.| - **See** +**See** UnAccessPixels **Returns** -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. +Returns **OHOS_IMAGE_RESULT_SUCCESS** if the operation is successful; returns an error code otherwise. + +**Since** +8 ### OH_GetImageInfo() - + ``` -int32_t OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info ) +struct OhosPixelMapCreateOps OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info ) ``` -**Description**
-Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) structure. +**Description** + +Obtains the **PixelMap** information and stores the information to the [OhosPixelMapInfo](_ohos_pixel_map_info.md) struct. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | -| info | Indicates the pointer to the object that stores the information obtained. For details, see [OhosPixelMapInfo](_ohos_pixel_map_info.md). | +| env | Indicates the NAPI environment pointer.| +| value | Indicates the **PixelMap** object at the application layer.| +| info | Indicates the pointer to the object that stores the information obtained. For details, see [OhosPixelMapInfo](_ohos_pixel_map_info.md).| **Returns** Returns **0** if the information is obtained and stored successfully; returns an error code otherwise. - **See** +**See** [OhosPixelMapInfo](_ohos_pixel_map_info.md) +**Since** -### OH_UnAccessPixels() - - -``` -int32_t OH_UnAccessPixels (napi_env env, napi_value value ) -``` -**Description**
-Unlocks the memory of the **PixelMap** object data. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | - -**Returns** - -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. - - **See** +8 -AccessPixels ### OH_PixelMap_CreateAlphaPixelMap() - + ``` int32_t OH_PixelMap_CreateAlphaPixelMap (napi_env env, napi_value source, napi_value * alpha ) ``` -**Description:**
+**Description** + Creates a **PixelMap** object that contains only alpha channel information. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| source | Indicates the options for setting the **PixelMap** object. | -| alpha | Indicates the pointer to the alpha channel. | +| env | Indicates the NAPI environment pointer.| +| source | Indicates the options for setting the **PixelMap** object.| +| alpha | Indicates the pointer to the alpha channel.| **Returns** Returns a **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** CreateAlphaPixelMap +**Since** + +9 + ### OH_PixelMap_CreatePixelMap() - + ``` int32_t OH_PixelMap_CreatePixelMap (napi_env env, OhosPixelMapCreateOps info, void * buf, size_t len, napi_value * res ) ``` -**Description:**
+**Description** + Creates a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| info | Indicates the options for setting the **PixelMap** object. | -| buf | Indicates the pointer to the buffer of the image. | -| len | Indicates the image size. | -| res | Indicates the pointer to the **PixelMap** object at the application layer. | +| env | Indicates the NAPI environment pointer.| +| info | Indicates the options for setting the **PixelMap** object.| +| buf | Indicates the pointer to the buffer of the image.| +| len | Indicates the image size.| +| res | Indicates the pointer to the **PixelMap** object at the application layer.| **Returns** Returns a **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** CreatePixelMap +**Since** + +9 + ### OH_PixelMap_Crop() - + ``` int32_t OH_PixelMap_Crop (const NativePixelMap * native, int32_t x, int32_t y, int32_t width, int32_t height ) ``` -**Description:**
+**Description** + Crops a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Indicates the x-coordinate of the upper left corner of the target image. | -| y | Indicates the y-coordinate of the upper left corner of the target image. | -| width | Indicates the width of the cropped region. | -| height | Indicates the height of the cropped region. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Indicates the x-coordinate of the upper left corner of the target image.| +| y | Indicates the y-coordinate of the upper left corner of the target image.| +| width | Indicates the width of the cropped region.| +| height | Indicates the height of the cropped region.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Crop +**Since** + +9 + ### OH_PixelMap_Flip() - + ``` int32_t OH_PixelMap_Flip (const NativePixelMap * native, int32_t x, int32_t y ) ``` -**Description:**
+**Description** + Flips a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Specifies whether to flip around the x axis. | -| y | Specifies whether to flip around the y axis. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Specifies whether to flip around the x axis.| +| y | Specifies whether to flip around the y axis.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Flip +**Since** + +9 + ### OH_PixelMap_GetBytesNumberPerRow() - + ``` int32_t OH_PixelMap_GetBytesNumberPerRow (const NativePixelMap * native, int32_t * num ) ``` -**Description:**
+**Description** + Obtains the number of bytes per row of a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| num | Indicates the pointer to the number of bytes per row of the **PixelMap** object. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| num | Indicates the pointer to the number of bytes per row of the **PixelMap** object.| **Returns** Returns the number of bytes per row of the **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** GetBytesNumberPerRow +**Since** + +9 ### OH_PixelMap_GetDensity() - + ``` int32_t OH_PixelMap_GetDensity (const NativePixelMap * native, int32_t * density ) ``` -**Description:**
+**Description** + Obtains the pixel density of a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| density | Indicates the pointer to the pixel density. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| density | Indicates the pointer to the pixel density.| **Returns** Returns the pixel density if the operation is successful; returns an error code otherwise. - **See** +**See** GetDensity +**Since** -### OH_PixelMap_GetImageInfo() - - -``` -int32_t OH_PixelMap_GetImageInfo (const NativePixelMap * native, OhosPixelMapInfo * info ) -``` -**Description:**
-Obtains the image information of a **PixelMap** object. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| info | Indicates the pointer to the image information. | - -**Returns** - -Returns **0** if the operation is successful; returns an error code otherwise. - - **See** - -[OhosPixelMapInfo](_ohos_pixel_map_info.md) +9 ### OH_PixelMap_GetIsEditable() - + ``` int32_t OH_PixelMap_GetIsEditable (const NativePixelMap * native, int32_t * editable ) ``` -**Description:**
+**Description** + Checks whether a **PixelMap** object is editable. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| editable | Indicates the pointer to the editing type of the **PixelMap** object. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| editable | Indicates the pointer to the editing type of the **PixelMap** object.| **Returns** Returns an enumerated value that indicates the editing type of the **PixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** GetIsEditable +**Since** + +9 + ### OH_PixelMap_InitNativePixelMap() - + ``` NativePixelMap* OH_PixelMap_InitNativePixelMap (napi_env env, napi_value source ) ``` -**Description:**
+**Description** + Initializes a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| source | Indicates the options for setting the **PixelMap** object. | +| env | Indicates the NAPI environment pointer.| +| source | Indicates the options for setting the **PixelMap** object.| **Returns** Returns a pointer to the **NativePixelMap** object if the operation is successful; returns an error code otherwise. - **See** +**See** InitNativePixelMap +**Since** + +9 + ### OH_PixelMap_IsSupportAlpha() - + ``` int32_t OH_PixelMap_IsSupportAlpha (const NativePixelMap * native, int32_t * alpha ) ``` -**Description:**
+**Description** + Checks whether a **PixelMap** object supports alpha channels. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| alpha | Indicates the pointer to the support for alpha channels. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| alpha | Indicates the pointer to the support for alpha channels.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** IsSupportAlpha +**Since** + +9 + + ### OH_PixelMap_Rotate() - + ``` int32_t OH_PixelMap_Rotate (const NativePixelMap * native, float angle ) ``` -**Description:**
+**Description** + Rotates a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| angle | Indicates the angle to rotate. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| angle | Indicates the angle to rotate.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Rotate +**Since** + +9 + ### OH_PixelMap_Scale() - + ``` int32_t OH_PixelMap_Scale (const NativePixelMap * native, float x, float y ) ``` -**Description:**
+**Description** + Scales a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Indicates the scaling ratio of the width. | -| y | Indicates the scaling ratio of the height. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Indicates the scaling ratio of the width.| +| y | Indicates the scaling ratio of the height.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Scale +**Since** + +9 + ### OH_PixelMap_SetAlphaAble() - + ``` int32_t OH_PixelMap_SetAlphaAble (const NativePixelMap * native, int32_t alpha ) ``` -**Description:**
+**Description** + Sets an alpha channel for a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| alpha | Indicates the alpha channel to set. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| alpha | Indicates the alpha channel to set.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** SetAlphaAble +**Since** + +9 + ### OH_PixelMap_SetDensity() - + ``` int32_t OH_PixelMap_SetDensity (const NativePixelMap * native, int32_t density ) ``` -**Description:**
+**Description** + Sets the pixel density for a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| density | Indicates the pixel density to set. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| density | Indicates the pixel density to set.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** GetDensity +**Since** + +9 + ### OH_PixelMap_SetOpacity() - + ``` int32_t OH_PixelMap_SetOpacity (const NativePixelMap * native, float opacity ) ``` -**Description:**
+**Description** + Sets the opacity for a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| opacity | Indicates the opacity to set. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| opacity | Indicates the opacity to set.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** SetOpacity +**Since** + +9 + ### OH_PixelMap_Translate() - + ``` int32_t OH_PixelMap_Translate (const NativePixelMap * native, float x, float y ) ``` -**Description:**
+**Description** + Translates a **PixelMap** object. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| x | Indicates the horizontal distance to translate. | -| y | Indicates the vertical distance to translate. | +| native | Indicates the pointer to a **NativePixelMap** object.| +| x | Indicates the horizontal distance to translate.| +| y | Indicates the vertical distance to translate.| **Returns** Returns **0** if the operation is successful; returns an error code otherwise. - **See** +**See** Translate +**Since** -### OH_PixelMap_UnAccessPixels() - - -``` -int32_t OH_PixelMap_UnAccessPixels (const NativePixelMap * native) -``` -**Description:**
-Unlocks the memory of the **NativePixelMap** object data. This function is used with [OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels) in pairs. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | - -**Returns** - -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. - - **See** - -AccessPixels - - -### OH_PixelMap_AccessPixels() - - -``` -int32_t OH_PixelMap_AccessPixels(const NativePixelMap* native, void** addr) -``` -**Description:**
-Obtains the memory address of a **NativePixelMap** object and locks the memory. - - **Parameters** - -| Name | Description | -| -------- | -------- | -| native | Indicates the pointer to a **NativePixelMap** object. | -| addr | Indicates the double pointer to the memory address. | - -**Returns** - -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. - - **See** - -UnAccessPixels +9 ### OH_UnAccessPixels() - + ``` int32_t OH_UnAccessPixels (napi_env env, napi_value value ) ``` -**Description:**
+**Description** + Unlocks the memory of a **PixelMap** object. This function is used with [OH_AccessPixels](#oh_accesspixels) in pairs. - **Parameters** +**Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | -| env | Indicates the NAPI environment pointer. | -| value | Indicates the **PixelMap** object at the application layer. | +| env | Indicates the NAPI environment pointer.| +| value | Indicates the **PixelMap** object at the application layer.| **Returns** -Returns OHOS_IMAGE_RESULT_SUCCESS if the operation is successful; returns an error code otherwise. +Returns **OHOS_IMAGE_RESULT_SUCCESS** if the operation is successful; returns an error code otherwise. - **See** +**See** AccessPixels + +**Since** + +8 \ No newline at end of file diff --git a/en/application-dev/ui/arkts-animation-overview.md b/en/application-dev/ui/arkts-animation-overview.md index 420a573762be5303597b80341e7a17e16ffbb31c..d75619d1c1acb3bb0d0273d7f44738101b43e59e 100644 --- a/en/application-dev/ui/arkts-animation-overview.md +++ b/en/application-dev/ui/arkts-animation-overview.md @@ -1,27 +1,27 @@ # Animation Overview -The principle of animation is that the UI appearance is changed for multiple times within a period of time. Because human eyes generate visual persistence, what you finally see is a continuous animation. A change of the UI is called an animation frame, which corresponds to a screen refresh. An important indicator that determines the animation smoothness is the frame rate (FPS), that is, the number of animation frames per second. The higher the frame rate, the smoother the animation. +The principle of animation is that the UI appearance is changed for multiple times within a period of time. Because human eyes retain persistence of vision, what you finally see is a continuous animation. A change of the UI is called an animation frame, which corresponds to a screen refresh. An important indicator that determines the animation smoothness is the frame rate (FPS), that is, the number of animation frames per second. The higher the frame rate, the smoother the animation. -In ArkUI, an animation is generated by changing the attribute value and specifying the animation parameters. Animation parameters include parameters such as animation duration and change rule (that is, curve). After the attribute value changes, the original state is transited to the new state according to the animation parameter, that is, an animation is formed. +In ArkUI, an animation is generated by changing the attribute value and specifying the animation parameters. Animation parameters include animation duration, change rule (that is, curve), and more. After the attribute value changes, the original state is transited to the new state according to the animation parameters. In this way, an animation is formed. -The animation capability provided by the ArkUI can be classified into intra-page animation and inter-page animation based on the page classification mode. As shown in the following figure, an animation on a page refers to an animation that can occur on a page, and an animation between pages refers to an animation that occurs only when two pages jump. +The animation capability provided by ArkUI can be classified into intra-page animation and inter-page animation based on the page classification mode. As shown in the following figure, an animation on a page refers to an animation that can occur on a page, and an animation between pages refers to an animation that occurs only with redirection between pages. - Figure 1 Animation by page + **Figure 1** Animation by page ![en-us_image_0000001562700385](figures/en-us_image_0000001562700385.png) -Based on the basic capability, the animation can be divided into three parts: attribute animation, explicit animation, and transition animation. as shown in the following figure. +By capability, the animation can be divided into three parts: attribute animation, explicit animation, and transition animation, as shown in the following figure. - Figure 2 Animation classified by basic capability + **Figure 2** Animation classified by basic capability ![en-us_image_0000001562820753](figures/en-us_image_0000001562820753.png) -Based on the page classification mode and application scenarios, this document provides the usage methods and precautions of various animations for developers to quickly learn animations. +This topic will introduce you to the usage and precautions of animations by the preceding classification and use cases. diff --git a/en/application-dev/ui/arkts-common-components-video-player.md b/en/application-dev/ui/arkts-common-components-video-player.md index 39cab59adf7576d52bfafc8c9bc9631bd85e06e8..27d68175306f3fa7095417f953c5e1a75f760b52 100644 --- a/en/application-dev/ui/arkts-common-components-video-player.md +++ b/en/application-dev/ui/arkts-common-components-video-player.md @@ -13,7 +13,7 @@ You can create a **\