diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index dba77cf37aab62a7bb4d33b367839a0c0c88bc4e..8484845fb47d82c6de79664c00d0d1c234b0e167 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -2,52 +2,87 @@ - [Application Development Overview](application-dev-guide.md) - About OpenHarmony - - [OpenHarmony Project](../OpenHarmony-Overview.md) - - [Glossary](../glossary.md) - - [OpenHarmony Release Notes](../release-notes/Readme.md) + - [OpenHarmony Project](../OpenHarmony-Overview.md) + - [Glossary](../glossary.md) + - [OpenHarmony Release Notes](../release-notes/Readme.md) - Quick Start - - Getting Started - - [Preparations](quick-start/start-overview.md) - - [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md) - - [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md) - - [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md) - - Development Fundamentals - - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - - [SysCap](quick-start/syscap.md) - + - Getting Started + - [Before You Start](quick-start/start-overview.md) + - [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md) + - [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md) + - [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md) + - Development Fundamentals + - Application Package Fundamentals + - [Application Package Overview](quick-start/application-package-overview.md) + - Application Package Structure + - [Application Package Structure in Stage Model)](quick-start/application-package-structure-stage.md) + - [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md) + - [HAR File Structure](quick-start/har-structure.md) + - Multi-HAP Mechanism + - [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md) + - [Multi-HAP Build View](quick-start/multi-hap-build-view.md) + - [Multi-HAP Development, Debugging, Release, and Deployment Process](quick-start/multi-hap-release-deployment.md) + - [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md) + - [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md) + - [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md) + - Application Configuration Files in Stage Model + - [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md) + - [app.json5 Configuration File](quick-start/app-configuration-file.md) + - [module.json5 Configuration File](quick-start/module-configuration-file.md) + - Application Configuration Files in FA Model + - [Application Configuration File Overview (FA Model)](quick-start/application-configuration-file-overview-fa.md) + - [Internal Structure of the app Tag](quick-start/app-structure.md) + - [Internal structure of deviceConfig Tag](quick-start/deviceconfig-structure.md) + - [Internal Structure of the module Tag](quick-start/module-structure.md) + - [Resource Categories and Access](quick-start/resource-categories-and-access.md) + - Learning ArkTS + - [Getting Started with ArkTS](quick-start/arkts-get-started.md) + - ArkTS Syntax (Declarative UI) + - [Basic UI Description](quick-start/arkts-basic-ui-description.md) + - State Management + - [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md) + - [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md) + - [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md) + - [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md) + - [Rendering Control](quick-start/arkts-rendering-control.md) + - [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md) - Development - - [Ability Development](ability/Readme-EN.md) - - [UI Development](ui/Readme-EN.md) - - [Common Event and Notification](notification/Readme-EN.md) - - [Window Manager](windowmanager/Readme-EN.md) - - [WebGL](webgl/Readme-EN.md) - - [Media](media/Readme-EN.md) - - [Security](security/Readme-EN.md) - - [Connectivity](connectivity/Readme-EN.md) - - [Data Management](database/Readme-EN.md) - - [File Management](file-management/Readme-EN.md) - - [Telephony](telephony/Readme-EN.md) - - [Task Management](task-management/Readme-EN.md) - - [Device Management](device/Readme-EN.md) - - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - - [DFX](dfx/Readme-EN.md) - - [Internationalization](internationalization/Readme-EN.md) - - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - - [Using Native APIs in Application Projects](napi/Readme-EN.md) + - [Application Models](application-models/Readme-EN.md) + - [UI Development](ui/Readme-EN.md) + - [Common Event and Notification](notification/Readme-EN.md) + - [Window Manager](windowmanager/Readme-EN.md) + - [WebGL](webgl/Readme-EN.md) + - [Media](media/Readme-EN.md) + - [Security](security/Readme-EN.md) + - [Connectivity](connectivity/Readme-EN.md) + - [Data Management](database/Readme-EN.md) + - [File Management](file-management/Readme-EN.md) + - [Telephony](telephony/Readme-EN.md) + - [Task Management](task-management/Readme-EN.md) + - [Device Management](device/Readme-EN.md) + - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) + - [DFX](dfx/Readme-EN.md) + - [Internationalization](internationalization/Readme-EN.md) + - [Application Test](application-test/Readme-EN.md) + - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) + - [Using Native APIs in Application Projects](napi/Readme-EN.md) - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs) - API References - - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - - APIs - - [JS and TS APIs](reference/apis/Readme-EN.md) - - Native APIs - - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - - [Node_API](reference/native-lib/third_party_napi/napi.md) + - [SystemCapability](reference/syscap.md) + - [SystemCapability List](reference/syscap-list.md) + - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) + - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) + - [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) + - APIs + - [ArkTS and JS APIs](reference/apis/Readme-EN.md) + - [Error Codes](reference/errorcodes/Readme-EN.md) + - Native APIs + - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) + - [Node_API](reference/native-lib/third_party_napi/napi.md) - [FAQs](faqs/Readme-EN.md) - Contribution - - [How to Contribute](../contribute/documentation-contribution.md) + - [How to Contribute](../contribute/documentation-contribution.md) diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index f074e1906535d708b193adea3b1ee3308fb0de4e..96e956f86e1528c5946c094b204c83e6e7d96222 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -18,7 +18,7 @@ To facilitate your application development, we provide development guidelines fo First thing first, familiarize yourself with the two cornerstone frameworks in OpenHarmony applications: -- Application framework: [Ability Development](ability/Readme-EN.md) +- Application framework: [Application Models](application-models/Readme-EN.md) - UI framework: [UI Development](ui/Readme-EN.md) All applications should be developed on top of these frameworks. @@ -37,6 +37,7 @@ Then, equip yourself for developing the key features, with the following guideli - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - [DFX](dfx/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md) +- [Application Test](application-test/Readme-EN.md) - [IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/Readme-EN.md) @@ -56,11 +57,11 @@ API references encompass all components and APIs available in OpenHarmony, helpi They are organized as follows: - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - -- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) -- APIs - - [JS and TS APIs](reference/apis/Readme-EN.md) - - Native APIs +- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) +- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) +- APIs + - [JS and TS APIs](reference/apis/Readme-EN.md) + - Native APIs - [Standard Library](reference/native-lib/third_party_libc/musl.md) - [Node_API](reference/native-lib/third_party_napi/napi.md) diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 2b22839820539e2919f1a705595a47cc491df8d0..b9bc5bb92ed39b292ca4eede0023989364eb473c 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -18,7 +18,7 @@ To facilitate your application development, we provide development guidelines fo First thing first, familiarize yourself with the two cornerstone frameworks in OpenHarmony applications: -- Application framework: [Ability Development](ability/fa-brief.md) +- Application framework: [Application Models](application-models/application-model-composition.md) - UI framework: [UI Development](ui/arkui-overview.md) All applications should be developed on top of these frameworks. @@ -35,8 +35,9 @@ Then, equip yourself for developing the key features, with the following guideli - [Task Management](task-management/background-task-overview.md) - [Device](device/usb-overview.md) - [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md) -- [DFX](dfx/hiappevent-overview.md) +- [DFX](dfx/hiappevent-guidelines.md) - [Internationalization](internationalization/international-overview.md) +- [Application Test](application-test/arkxtest-guidelines.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md) @@ -59,7 +60,9 @@ They are organized as follows: - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) -- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md) +- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) + +- [JS and TS APIs](reference/apis/js-apis-ability-dataUriUtils.md) - Native APIs - [Standard Library](reference/native-lib/third_party_libc/musl.md) 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 0a5ba865f4b8c9894523666de1582b012f8f2237..ab116c430cb7b248b947ccbee46cf5ac932f9fc9 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 @@ -78,6 +78,5 @@ The **module.json5** of a browser application is as follows: 4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful. -2. When there are multiple matching applications, a dialog box is displayed for you to select one of them. - -stage-want1 \ No newline at end of file +2. When there are multiple matching applications, a dialog box is displayed for you to select one of them. +stage-want1 diff --git a/en/application-dev/application-models/abilitystage.md b/en/application-dev/application-models/abilitystage.md index fa3aa07c60287688749c13035451d0b470e621ea..4e0a273f850b4919d0964580ebed89c053c273f7 100644 --- a/en/application-dev/application-models/abilitystage.md +++ b/en/application-dev/application-models/abilitystage.md @@ -55,4 +55,3 @@ When an application is switched to the background, it is cached in the backgroun } ``` - \ No newline at end of file diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md index 2479ab317cfdff8bc642f3f307fb4d8423efe112..85dfb9523ca117e691480bcbd2321b5fb3b22304 100644 --- a/en/application-dev/application-models/actions-entities.md +++ b/en/application-dev/application-models/actions-entities.md @@ -2,6 +2,7 @@ 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. + **Common action Values** @@ -15,6 +16,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio 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. + **Common entities Values** diff --git a/en/application-dev/application-models/api-switch-overview.md b/en/application-dev/application-models/api-switch-overview.md index 461e321d410a7f0036f5b4a1700c6176d7d451da..bf8223b5a6c047af46e960dad6713f20e251d02f 100644 --- a/en/application-dev/application-models/api-switch-overview.md +++ b/en/application-dev/application-models/api-switch-overview.md @@ -13,8 +13,8 @@ Due to the differences in the thread model and process model, certain APIs (mark import fa from '@ohos.ability.featureAbility'; let parameter = { "want": { - bundleName: "ohos.samples.demo", - abilityName: "ohos.samples.demo.MainAbility" + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.EntryAbility" } } fa.startAbility(parameter).then((data) => { @@ -30,8 +30,8 @@ Due to the differences in the thread model and process model, certain APIs (mark // context is a member of the ability object and is required for invoking inside a non-ability object. // Pass in the Context object. let wantInfo = { - bundleName: "ohos.samples.demo", - abilityName: "ohos.samples.demo.MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; this.context.startAbility(wantInfo).then((data) => { console.info('startAbility success.'); diff --git a/en/application-dev/application-models/app-deviceconfig-switch.md b/en/application-dev/application-models/app-deviceconfig-switch.md index 8630746cb46979d1a7e37c2c6e30787ad5fe91ec..1092c21081cd9a8d62c92a1a68ba434efee7c8c9 100644 --- a/en/application-dev/application-models/app-deviceconfig-switch.md +++ b/en/application-dev/application-models/app-deviceconfig-switch.md @@ -28,4 +28,3 @@ OpenHarmony has reconstructed the [deviceConfig](../quick-start/deviceconfig-str | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.| / | This configuration is not supported in the stage model.| | network | Network security configuration.| / | This configuration is not supported in the stage model.| - \ No newline at end of file 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 d460966545bc6e4901169779f0450308b44c8866..4cc1c9ad6831f0e54ae4c70f4f7229a7abc7c62f 100644 --- a/en/application-dev/application-models/application-component-configuration-fa.md +++ b/en/application-dev/application-models/application-component-configuration-fa.md @@ -38,4 +38,3 @@ When developing an application, you may need to configure certain tags to identi To request component permissions, set the **reqPermission** field under **module** in the **config.json** file. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. For details about the configuration, see [reqPermission](../quick-start/module-structure.md). - \ No newline at end of file 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 56a5ddac56d43e09609fa8e6e9669fab39681988..de9e29941b5ddcc9e29f62ddc039fb38b6bc54b6 100644 --- a/en/application-dev/application-models/application-component-configuration-stage.md +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -3,8 +3,7 @@ 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. - - **Figure 1** Icons and labels +**Figure 1** Icons and labels ![application-component-configuration-stage](figures/application-component-configuration-stage.png) @@ -71,4 +70,3 @@ When developing an application, you may need to configure certain tags to identi The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. - \ No newline at end of file diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index af8f5d82a3f162381f4b970c82e0def06b91070b..8d49b7369bb93e26f4407313f2d9352acd7380e1 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -12,7 +12,7 @@ context-holding - 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 the ability, obtain the ability configuration, request permissions from users, and more. + - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, and more. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -65,15 +65,10 @@ This topic describes how to use the context in the following scenarios: - [Obtaining the Application Development Path](#obtaining-the-application-development-path) - - [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas) - - [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) - - [Subscribing to Ability Lifecycle Changes in a Process](#subscribing-to-ability-lifecycle-changes-in-a-process) -- [Requesting Permissions from Users Through AbilityContext](#requesting-permissions-from-users-through-uiabilitycontext) - ### Obtaining the Application Development Path @@ -180,9 +175,9 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../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'; @@ -194,8 +189,8 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] // ... } } - ``` - +``` + - Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module. > **NOTE** > @@ -204,7 +199,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > > - This is a system API and cannot be called by third-party applications. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -217,7 +212,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] } } ``` - + - Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module. ```ts @@ -242,7 +237,7 @@ When the ability lifecycle changes in a process, for example, being created or d ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; const TAG: string = "[Example].[Entry].[EntryAbility]"; @@ -298,14 +293,3 @@ export default class EntryAbility extends UIAbility { } } ``` - - -### Requesting Permissions from Users Through UIAbilityContext - -Each ability has the **Context** attribute. The ability is used to process the lifecycle. Methods use to operate the ability (such as **startAbility()**, **connectServiceExtensionAbility()**, and **terminateSelf()**) are implemented in the corresponding context. The context also provides methods for obtaining the ability configuration and requesting permissions from users. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). - - -When an application needs to obtain users' privacy information or use system capabilities, for example, to obtain location information, to access the calendar, or to use the camera to take photos or record videos, the application must request permissions from users, as shown below. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md). - -**Figure 2** Requesting the permission to access the calendar from users -application-context-stage \ No newline at end of file diff --git a/en/application-dev/application-models/application-model-description.md b/en/application-dev/application-models/application-model-description.md index 2c15a15ee2aa30c9e56a04fb21497af01969cd07..de7e3045d79eff2c681291f8d4de55129d361245 100644 --- a/en/application-dev/application-models/application-model-description.md +++ b/en/application-dev/application-models/application-model-description.md @@ -58,4 +58,3 @@ The table below describes their differences in detail. | **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).| - \ No newline at end of file diff --git a/en/application-dev/application-models/bind-serviceability-from-stage.md b/en/application-dev/application-models/bind-serviceability-from-stage.md index 0ee35195b8810efea9af4382c80d0c8e37e0fd70..2d99fddfe503db082cf7613f3875dcf490331dd9 100644 --- a/en/application-dev/application-models/bind-serviceability-from-stage.md +++ b/en/application-dev/application-models/bind-serviceability-from-stage.md @@ -12,15 +12,15 @@ A UIAbility accesses a ServiceAbility in the same way as it accesses a ServiceEx ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.info("MainAbility onCreate"); + console.info("EntryAbility onCreate"); } onDestroy() { - console.info("MainAbility onDestroy") + console.info("EntryAbility onDestroy") } onWindowStageCreate(windowStage) { - console.info("MainAbility onWindowStageCreate") + console.info("EntryAbility onWindowStageCreate") let want = { bundleName: "com.ohos.fa", abilityName: "ServiceAbility", @@ -40,13 +40,13 @@ export default class MainAbility extends UIAbility { let connectionId = this.context.connectServiceExtensionAbility(want, options); } onWindowStageDestroy() { - console.info("MainAbility onWindowStageDestroy") + console.info("EntryAbility onWindowStageDestroy") } onForeground() { - console.info("MainAbility onForeground") + console.info("EntryAbility onForeground") } onBackground() { - console.info("MainAbility onBackground") + console.info("EntryAbility onBackground") } } ``` diff --git a/en/application-dev/application-models/component-startup-rules-fa.md b/en/application-dev/application-models/component-startup-rules-fa.md index 15788e109c4406d740f403d3e21a27d7d0a451c6..db64e8c093df679a9e52d6bc753e4935a21c25be 100644 --- a/en/application-dev/application-models/component-startup-rules-fa.md +++ b/en/application-dev/application-models/component-startup-rules-fa.md @@ -25,7 +25,7 @@ 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.** - This rule applies only to cross-application scenarios. - 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-tag) + - For details, see [Component Visible 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. @@ -67,4 +67,3 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ![component-startup-rules](figures/component-startup-inter-fa.png) - \ No newline at end of file diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index a00d01780d9bf67b6b64ec90b4c3bd0635865c74..0e6c2ce33c68913221c7b09f02e96327b0ea1c30 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -24,7 +24,7 @@ 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-tag) + - For details, see [Component Visible 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. @@ -62,4 +62,3 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ![component-startup-rules](figures/component-startup-inter-stage.png) - \ No newline at end of file diff --git a/en/application-dev/application-models/config-file-fa.md b/en/application-dev/application-models/config-file-fa.md index f19104d0db5b36346ff3f868d0fb9e5773460ac1..3f550aa6192faeab625b9f65884fb0bbc7e79e15 100644 --- a/en/application-dev/application-models/config-file-fa.md +++ b/en/application-dev/application-models/config-file-fa.md @@ -4,4 +4,3 @@ The application configuration file contains information about the application co The application project code developed based on the FA model contains a **config.json** file. For details about common configuration items, see [Application- or Component-Level Configuration](application-component-configuration-fa.md). For details about the file, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md). - \ No newline at end of file diff --git a/en/application-dev/application-models/config-file-stage.md b/en/application-dev/application-models/config-file-stage.md index bf667dcb0d33228581cfbec3a7ab4750a3cb4b94..66cabf4a99fd4a3f5138c0a8ef1bbf2cefbe15c0 100644 --- a/en/application-dev/application-models/config-file-stage.md +++ b/en/application-dev/application-models/config-file-stage.md @@ -4,4 +4,3 @@ The application configuration file contains information about the application co The application project code developed based on the stage model contains one **app.json5** file and one or more **module.json5** files. For details about common configuration items, see [Application- or Component-Level Configuration (Stage Model)](application-component-configuration-stage.md). For details about the two files, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md). - \ No newline at end of file diff --git a/en/application-dev/application-models/configuration-file-diff.md b/en/application-dev/application-models/configuration-file-diff.md index 141eeab16f692b144c57488918e978217e61d08f..745f2702cab12b8ef99e174c924d49cf2217bf2b 100644 --- a/en/application-dev/application-models/configuration-file-diff.md +++ b/en/application-dev/application-models/configuration-file-diff.md @@ -9,4 +9,3 @@ The stage model uses the [app.json5](../quick-start/app-configuration-file.md) a **Figure 1** Configuration file differences ![comparison-of-configuration-file](figures/comparison-of-configuration-file.png) - \ No newline at end of file diff --git a/en/application-dev/application-models/create-pageability.md b/en/application-dev/application-models/create-pageability.md index 7a79770c309a165b8421974b28263bb20fa587ee..783646ff4cfd5fa2ab193005bfa9d182dc75b70c 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" } @@ -65,6 +65,7 @@ After the PageAbility is created, its abilities-related configuration items are In the FA model, you can call **getContext** of **featureAbility** to obtain the application context and then use the capabilities provided by the context. + **Table 1** featureAbility APIs | API| Description| diff --git a/en/application-dev/application-models/dataability-configuration.md b/en/application-dev/application-models/dataability-configuration.md index d3618ea7a026311004524a9eb79ff3d1951d6a93..c8c69c8626cf9872e40931b2f97c431e105cb38f 100644 --- a/en/application-dev/application-models/dataability-configuration.md +++ b/en/application-dev/application-models/dataability-configuration.md @@ -59,4 +59,3 @@ The following is an example **config.json** file: For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md). - \ No newline at end of file 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 99aa45c9f8f387e5717a90478a0a24d2be60f463..ccf33e07d1b389eb1246a89a377febb1e7d24a78 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -1,48 +1,48 @@ # 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. +## Matching Rules of Explicit Want + + +The table below describes the matching rules of explicit Want. -- **Matching rules of explicit Want** - - | Name| Type| Matching Item| Mandatory| Rule Description| - | -------- | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| No| If this field is unspecified, only abilities 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.| - | 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.| - | 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.| +| Name| Type| Matching Item| Mandatory| Rule Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceId | string | Yes| No| If this field is unspecified, only abilities 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.| +| 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.| +| 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.| - -- **Matching rules for implicit Want** - | Name| Type| Matching Item| Mandatory| Rule Description| - | -------- | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| No| Implicit invoking is not supported across devices.| - | abilityName | string | No| No| To use implicit Want, this field must be left unspecified.| - | bundleName | string | Yes| No| - When only **bundleName** is specified, matching is limited to that application.
- When both **bundleName** and **moduleName** are specified, matching is limited to that module in that application.
- When only **moduleName** is specified, the setting is invalid.
For details, see [Interpretation of Implicit Want Matching Rules](#interpretation-of-implicit-want-matching-rules). | - | moduleName | string | Yes| No|| - | uri | string | Yes| No|| - | type | string | Yes| No|| - | 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.| +## Matching Rules for Implicit Want -## Interpretation of Implicit Want Matching Rules +The table below describes the matching rules of implicit Want. +| Name | Type | Matching Item| Mandatory| Rule Description | +| ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | No | Implicit invoking is not supported across devices. | +| abilityName | string | No | No | To use implicit Want, this field must be left unspecified. | +| bundleName | string | Yes | No | - When only **bundleName** is specified, matching is limited to that application.
- When both **bundleName** and **moduleName** are specified, matching is limited to that module in that application.
- When only **moduleName** is specified, the setting is invalid.

These fields will be used for implicit matching.| +| moduleName | string | Yes | No | | +| uri | string | Yes | No | | +| type | string | Yes | No | | +| 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. | 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-tag) in the [module.json5 file](../quick-start/module-configuration-file.md). +- 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 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. @@ -60,8 +60,7 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m - 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. - Figure 1 Matching rules of action in the want parameter - + **Figure 1** Matching rules of action in the want parameter want-action @@ -112,6 +111,7 @@ There are four combinations of **uri** and **type** settings. The matching rules 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. + Figure 4 Matching rules of uri and type in the want parameter want-uri-type2 @@ -158,5 +158,3 @@ To simplify the description, **uri** in the passed **want** parameter is called - If the last character of **s_type** is the wildcard `*`, for example, `prefixType/*`, the matching is successful only when **w_type** contains `prefixType/`. - If the last character of **w_type** is the wildcard `*`, for example, `prefixType/*`, the matching is successful only when **s_type** contains `prefixType/`. - - \ No newline at end of file diff --git a/en/application-dev/application-models/figures/application-component-configuration-stage.png b/en/application-dev/application-models/figures/application-component-configuration-stage.png index 8957b1b4a85a7bdc8d0d9ab422d7cf379ae6cf75..9ddf0c3892998aa5391de99775db5965f66bd4b1 100644 Binary files a/en/application-dev/application-models/figures/application-component-configuration-stage.png and b/en/application-dev/application-models/figures/application-component-configuration-stage.png differ diff --git a/en/application-dev/application-models/figures/application-context-stage.png b/en/application-dev/application-models/figures/application-context-stage.png index 9423fd5f99deb310315c13173422cb050d93fbb7..0d4c6cdfd040b4df9930d8bc639deff32f033824 100644 Binary files a/en/application-dev/application-models/figures/application-context-stage.png and b/en/application-dev/application-models/figures/application-context-stage.png differ diff --git a/en/application-dev/application-models/figures/stage-want1.png b/en/application-dev/application-models/figures/stage-want1.png index 09ebc69170dca547c7b965dbf62c1a4df978815f..558f0a8588d7785eaad1402e68d6ba60c3118f27 100644 Binary files a/en/application-dev/application-models/figures/stage-want1.png and b/en/application-dev/application-models/figures/stage-want1.png differ diff --git a/en/application-dev/application-models/figures/stage-want2.png b/en/application-dev/application-models/figures/stage-want2.png index 3c5358cb3d98f8b519369f8ecce1964fd02c3d58..72829adade52ee11419d726f19e218ec4de15220 100644 Binary files a/en/application-dev/application-models/figures/stage-want2.png and b/en/application-dev/application-models/figures/stage-want2.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 59a0110cfc0b36780adb0a936af34588fcfdeb1a..92292f2c6ef4c9cbd06da2a523f27b571a957e2b 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/hop-multi-device-collaboration.md b/en/application-dev/application-models/hop-multi-device-collaboration.md index 85d6403187331a40bb9ea6280a3129dfb0e84883..3a6fa2646a37785d41793407d4803d60743342dd 100644 --- a/en/application-dev/application-models/hop-multi-device-collaboration.md +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -345,21 +345,19 @@ The following describes how to implement multi-device collaboration through cros 3. Create the callee ability. - -For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. + For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. 1. Configure the launch type of the UIAbility. - Set **launchType** of the callee ability to **singleton** in the **module.json5** file. - - | JSON Field| Description| - | -------- | -------- | - | "launchType"| Ability launch type. Set this parameter to **singleton**.| - - An example of the UIAbility configuration is as follows: + Set **launchType** of the callee ability to **singleton** in the **module.json5** file. + | JSON Field| Description| + | -------- | -------- | + | "launchType"| Ability launch type. Set this parameter to **singleton**.| -​ + An example of the UIAbility configuration is as follows: + + ```json "abilities":[{ "name": ".CalleeAbility", @@ -377,77 +375,75 @@ For the callee ability, implement the callback to receive data and the methods t ```ts import Ability from '@ohos.app.ability.UIAbility'; ``` - + 3. Define the agreed sequenceable data. - - The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. - - + The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. + ```ts export default class MySequenceable { - num: number = 0; - str: string = ""; + num: number = 0 + str: string = "" constructor(num, string) { - this.num = num; - this.str = string; + this.num = num + this.str = string } marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - return true; + messageParcel.writeInt(this.num) + messageParcel.writeString(this.str) + return true } unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - return true; + this.num = messageParcel.readInt() + this.str = messageParcel.readString() + return true } } ``` 4. Implement **Callee.on** and **Callee.off**. - In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. - - ```ts - const TAG: string = '[CalleeAbility]'; - const MSG_SEND_METHOD: string = 'CallSendMsg'; - - function sendMsgCallback(data) { - console.info('CalleeSortFunc called'); - - // Obtain the sequenceable data sent by the caller ability. - let receivedData = new MySequenceable(0, ''); - data.readSequenceable(receivedData); - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); - - // Process the data. - // Return the sequenceable data result to the caller ability. - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); - } - - export default class CalleeAbility extends Ability { - onCreate(want, launchParam) { - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback); - } catch (error) { - console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); - } - } - - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD); - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); - } - } - } - ``` - + In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. + + ```ts + const TAG: string = '[CalleeAbility]' + const MSG_SEND_METHOD: string = 'CallSendMsg' + + function sendMsgCallback(data) { + console.info('CalleeSortFunc called') + + // Obtain the sequenceable data sent by the caller ability. + let receivedData = new MySequenceable(0, '') + data.readSequenceable(receivedData) + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) + + // Process the data. + // Return the sequenceable data result to the caller ability. + return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) + } + + export default class CalleeAbility extends Ability { + onCreate(want, launchParam) { + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + } + + onDestroy() { + try { + this.callee.off(MSG_SEND_METHOD) + } catch (error) { + console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) + } + } + } + ``` + 4. Obtain the caller object and access the callee ability. 1. Import the **UIAbility** module. @@ -457,14 +453,13 @@ For the callee ability, implement the callback to receive data and the methods t 2. Obtain the caller object. - - The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. + The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. ```ts async onButtonGetRemoteCaller() { - var caller = undefined; - var context = this.context; + var caller = undefined + var context = this.context context.startAbilityByCall({ deviceId: getRemoteDeviceId(), @@ -472,23 +467,22 @@ For the callee ability, implement the callback to receive data and the methods t abilityName: 'CalleeAbility' }).then((data) => { if (data != null) { - caller = data; - console.info('get remote caller success'); + caller = data + console.info('get remote caller success') // Register the onRelease() listener of the caller ability. caller.onRelease((msg) => { - console.info(`remote caller onRelease is called ${msg}`); + console.info(`remote caller onRelease is called ${msg}`) }) - console.info('remote caller register OnRelease succeed'); + console.info('remote caller register OnRelease succeed') } }).catch((error) => { - console.error(`get remote caller failed with ${error}`); + console.error(`get remote caller failed with ${error}`) }) } - ``` - - For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). - ``` - + ``` + + For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). + 5. Sends agreed sequenceable data to the callee ability. 1. The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. diff --git a/en/application-dev/application-models/mission-management-launch-type.md b/en/application-dev/application-models/mission-management-launch-type.md index 7dbb3b5c8fa5a8dfab3f03ab0eb3b02ba4cb98d2..72b6dbf80df2628119ebcc29339ed7e4b70e9a50 100644 --- a/en/application-dev/application-models/mission-management-launch-type.md +++ b/en/application-dev/application-models/mission-management-launch-type.md @@ -31,4 +31,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility > > The **specified** mode is supported in the stage model only. - \ No newline at end of file diff --git a/en/application-dev/application-models/serviceability-configuration.md b/en/application-dev/application-models/serviceability-configuration.md index a0bf139c2ec08382b73e1bce7bb87882a2306def..2c8e009a10937140e013d030cf21a1167b1fd3e8 100644 --- a/en/application-dev/application-models/serviceability-configuration.md +++ b/en/application-dev/application-models/serviceability-configuration.md @@ -14,4 +14,3 @@ Similar to a PageAbility, a ServiceAbility is configured in **abilities** under For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md). - \ No newline at end of file diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index 6626bf66592f4fabb9abf890b163b9b392f04955..c4ffdbd980fff4ce568115f92af884da06739ad2 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -293,4 +293,3 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec }) ``` - \ No newline at end of file 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 139a27e2151cd3141bd7a0dd3a93c3c90929bf2a..6fbf06baa44d4c0f2196fa3c1b00a0761a71a161 100644 --- a/en/application-dev/application-models/stage-model-development-overview.md +++ b/en/application-dev/application-models/stage-model-development-overview.md @@ -17,7 +17,7 @@ The following figure shows the basic concepts used in the stage model. - 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) - Each UIAbility class instance is bound to a WindowStage class instance, which functions as the window manager in the application process. The WindowStage class instance contains a main window. That is, UIAbility holds a window through WindowStage, and this window provides an area for ArkUI to render. + Each UIAbility class instance is bound to a WindowStage class instance, which functions as the window manager in the application process. The WindowStage class instance contains a main window. That is, UIAbility holds a main window through WindowStage, and this window provides an area for ArkUI to render. - [Context](application-context-stage.md) @@ -32,12 +32,12 @@ The following figure shows the basic concepts used in the stage model. During application development based on the stage model, the following tasks are involved in the application model. - **Table 1** Stage model development process +**Table 1** Stage model development process | 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) | +| 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)| -| 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 MissionList](page-mission-stack.md) | -| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](config-file-stage.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](config-file-stage.md)| diff --git a/en/application-dev/application-models/start-local-pageability.md b/en/application-dev/application-models/start-local-pageability.md index d8344820078bcdd52c2d92b1b406dfabf9253a35..425566ab88d66aecd4690c569dd84d94c46cd568 100644 --- a/en/application-dev/application-models/start-local-pageability.md +++ b/en/application-dev/application-models/start-local-pageability.md @@ -22,7 +22,7 @@ import featureAbility from '@ohos.ability.featureAbility' want: { bundleName: "com.example.myapplication", moduleName: "entry", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.EntryAbility" } } await featureAbility.startAbility(param) diff --git a/en/application-dev/application-models/start-page.md b/en/application-dev/application-models/start-page.md index adf814355974157f579b809be6583d9b7a713d70..58966d93cba037eaad141caaed0feaaaa672cde1 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" } @@ -89,7 +89,7 @@ struct Index { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page1" } } }).then((data) => { @@ -104,7 +104,7 @@ struct Index { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page2" } } }).then((data) => { 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 f3a09f4af4613e2ad963b8e0aba1596ba6903c67..9d1b7ed27f6780ce56d1e90b3be5d196cf3b1187 100644 --- a/en/application-dev/application-models/start-pageability-from-stage.md +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -9,23 +9,23 @@ This topic describes how the two application components of the stage model start A UIAbility starts a PageAbility in the same way as it starts another UIAbility. ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.info("MainAbility onCreate") + console.info("EntryAbility onCreate") } onDestroy() { - console.info("MainAbility onDestroy") + console.info("EntryAbility onDestroy") } onWindowStageCreate(windowStage) { - console.info("MainAbility onWindowStageCreate") + console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { // ... }); let want = { bundleName: "com.ohos.fa", - abilityName: "MainAbility", + abilityName: "EntryAbility", }; this.context.startAbility(want).then(() => { console.info('Start Ability successfully.'); @@ -34,13 +34,13 @@ export default class MainAbility extends UIAbility { }); } onWindowStageDestroy() { - console.info("MainAbility onWindowStageDestroy") + console.info("EntryAbility onWindowStageDestroy") } onForeground() { - console.info("MainAbility onForeground") + console.info("EntryAbility onForeground") } onBackground() { - console.info("MainAbility onBackground") + console.info("EntryAbility onBackground") } } ``` @@ -54,23 +54,23 @@ A UIAbility starts a PageAbility through **startAbilityForResult()** in the same ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.info("MainAbility onCreate") + console.info("EntryAbility onCreate") } onDestroy() { - console.info("MainAbility onDestroy") + console.info("EntryAbility onDestroy") } onWindowStageCreate(windowStage) { - console.info("MainAbility onWindowStageCreate") + console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { // ... }); let want = { bundleName: "com.ohos.fa", - abilityName: "MainAbility", + abilityName: "EntryAbility", }; this.context.startAbilityForResult(want).then((result) => { console.info('Ability verify result: ' + JSON.stringify(result)); @@ -79,13 +79,13 @@ export default class MainAbility extends UIAbility { }); } onWindowStageDestroy() { - console.info("MainAbility onWindowStageDestroy") + console.info("EntryAbility onWindowStageDestroy") } onForeground() { - console.info("MainAbility onForeground") + console.info("EntryAbility onForeground") } onBackground() { - console.info("MainAbility onBackground") + console.info("EntryAbility onBackground") } } ``` @@ -110,7 +110,7 @@ export default class ServiceExtension extends Extension { console.info("ServiceExtension onRequest") let wantFA = { bundleName: "com.ohos.fa", - abilityName: "MainAbility", + abilityName: "EntryAbility", }; this.context.startAbility(wantFA).then(() => { console.info('Start Ability successfully.'); diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md index 54f370aa454019d3568c6048649d5fca4003d777..4e998a15d23d298bfdb402bd18ea0db2a9f819eb 100644 --- a/en/application-dev/application-models/start-remote-pageability.md +++ b/en/application-dev/application-models/start-remote-pageability.md @@ -97,13 +97,13 @@ function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { let list = dmClass.getTrustedDeviceListSync(); if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.info("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); return; } - console.info("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); return list[0].deviceId; } else { - console.info("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); } } ``` diff --git a/en/application-dev/application-models/start-uiability-from-fa.md b/en/application-dev/application-models/start-uiability-from-fa.md index fd2328f6471e045171312ea3909e652f68831c24..42d8e034cd6519643423bb289217d1aa140a18d4 100644 --- a/en/application-dev/application-models/start-uiability-from-fa.md +++ b/en/application-dev/application-models/start-uiability-from-fa.md @@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.MainAbility" + abilityName: "com.ohos.stage.EntryAbility" } }; featureAbility.startAbility(parameter).then((code) => { @@ -38,7 +38,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.MainAbility" + abilityName: "com.ohos.stage.EntryAbility" } }; featureAbility.startAbilityForResult(parameter).then((result) => { @@ -60,7 +60,7 @@ import particleAbility from '@ohos.ability.particleAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.MainAbility" + abilityName: "com.ohos.stage.EntryAbility" } }; particleAbility.startAbility(parameter).then(() => { 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 db85dfdffb0a7d9e60e78151d6654fcdd4a973aa..ea6b8bbecfa4a9a4f5434fb0aa5aad6184f38c9f 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -1,4 +1,4 @@ -# Interaction Intra-Device Between UIAbility Components +# Intra-Device Interaction Between UIAbility Components UIAbility is the minimum unit that can be scheduled by the system. Jumping between functional modules in a device involves starting of specific UIAbility components, which belong to the same or a different application (for example, starting UIAbility of a third-party payment application). @@ -50,7 +50,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - import Window from '@ohos.window'; + import window from '@ohos.window'; export default class FuncAbility extends UIAbility { onCreate(want, launchParam) { @@ -196,6 +196,7 @@ This section describes how to start the UIAbility of another application through ``` The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. + uiability-intra-device-interaction 3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. @@ -442,7 +443,8 @@ Ability call is usually used in the following scenarios: The following figure shows the ability call process. -Figure 1 Ability call process +**Figure 1** Ability call process + call - The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability. @@ -461,7 +463,7 @@ Figure 1 Ability call process The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). - **Table 2** Ability call APIs +**Table 2** Ability call APIs | API| Description| | -------- | -------- | @@ -486,8 +488,7 @@ For the callee ability, implement the callback to receive data and the methods t 1. Configure the ability launch type. - -Set **launchType** of the callee ability to **singleton** in the **module.json5** file. + Set **launchType** of the callee ability to **singleton** in the **module.json5** file. | JSON Field| Description| | -------- | -------- | @@ -595,9 +596,9 @@ An example of the ability configuration is as follows: 2. Obtain the caller interface. - The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. + ```ts // Register the onRelease() listener of the caller ability. private regOnRelease(caller) { diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md index c64d7fb3ffc0e3fa31741924439998118449068a..cda8307ddd3dae6f7cceac3fad134ef510d7383c 100644 --- a/en/application-dev/application-models/uiability-launch-type.md +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -18,6 +18,7 @@ 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 + uiability-launch-type1 > **NOTE** @@ -47,6 +48,7 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**. **Figure 2** Demonstration effect in standard mode + standard-mode To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**. @@ -72,6 +74,7 @@ To use the standard mode, set **launchType** in the [module.json5 configuration 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-type2 For example, there are EntryAbility and SpecifiedAbility, and the launch type of SpecifiedAbility is set to **specified**. You are required to start SpecifiedAbility from EntryAbility. @@ -93,7 +96,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ``` 2. Before a UIAbility instance is created, you can create a unique string key for the instance. The key is bound to the UIAbility instance when it is created. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application is asked which UIAbility instance is used to respond to the [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) request. - In EntryAbility, add a custom parameter, for example, **instanceKey**, to the **want** parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances. + In EntryAbility, add a custom parameter, for example, **instanceKey**, to the [want](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances. ```ts // Configure an independent key for each UIAbility instance. @@ -146,7 +149,8 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of For example, in the document application, different key values are bound to different document instances. Each time a document is created, a new key value (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage. - The following steps are used as an example. + +The following steps are used as an example. 1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started. 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. diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md index b530a7bda5c4f3c4fe0dd2eb96d53991083a5ff4..9ec701cbffd4da51098d5dc448addd88f26ee47e 100644 --- a/en/application-dev/application-models/uiability-lifecycle.md +++ b/en/application-dev/application-models/uiability-lifecycle.md @@ -7,7 +7,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 +**Figure 1** UIAbility lifecycle states Ability-Life-Cycle @@ -21,7 +21,7 @@ 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'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { @@ -36,14 +36,14 @@ export default class EntryAbility extends UIAbility { 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 +**Figure 2** WindowStageCreate and WindowStageDestory Ability-Life-Cycle-WindowStage 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. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { // ... @@ -77,7 +77,7 @@ Before the UIAbility instance is destroyed, the **onWindowStageDestroy()** callb ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { // ... @@ -135,7 +135,7 @@ 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'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { // ... diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md index ec26d2ca9b360259d7f7c00c37cba53bd5db8756..14cb5c4652749c97dd6e50c4232b6f65fb6feaab 100644 --- a/en/application-dev/application-models/uiability-overview.md +++ b/en/application-dev/application-models/uiability-overview.md @@ -37,4 +37,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb > > For the ability composition, see [Adding an Ability to a Module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-ability-0000001218280664-V3). - \ No newline at end of file diff --git a/en/application-dev/application-models/uiability-usage.md b/en/application-dev/application-models/uiability-usage.md index ccd80625f460ea704f689f9b7dfa83f6b42fa47f..fa8badc6d48c7e550922cb60a15d02eab9cc80b6 100644 --- a/en/application-dev/application-models/uiability-usage.md +++ b/en/application-dev/application-models/uiability-usage.md @@ -11,10 +11,10 @@ If no startup page is specified, a white screen occurs after the application is ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: Window.WindowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created. Set a main page for this ability. windowStage.loadContent('pages/Index', (err, data) => { // ... diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md index 784f190ad6b23a85c60995c44babdc8dd34d576d..f8239c64cf43a0df0acca0bc1ec0e3be914eecfe 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -23,7 +23,7 @@ ``` - **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-tag)) 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 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. ```ts @@ -47,5 +47,3 @@ > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want. > > - If the **want** parameter passed contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start ServiceExtensionAbility. By default, ServiceExtensionAbility with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility is returned. - - \ No newline at end of file diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md index c170f134932af44c4e8b55888e216926ef51186e..df162455f63272a817d0a7773d150419011a7467 100644 --- a/en/application-dev/application-models/widget-development-fa.md +++ b/en/application-dev/application-models/widget-development-fa.md @@ -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", @@ -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 MainAbility name of the FA model created by DevEco Studio 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 main ability 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 index 38f4e89d108d9d012c968b3d05de5b4e841ff482..32aa03e7aaea833a41b948764ca225c605adf24b 100644 --- a/en/application-dev/application-models/widget-development-stage.md +++ b/en/application-dev/application-models/widget-development-stage.md @@ -597,4 +597,3 @@ The following is an example: }; ``` - \ No newline at end of file diff --git a/en/application-dev/application-test/Readme.md b/en/application-dev/application-test/Readme-EN.md similarity index 100% rename from en/application-dev/application-test/Readme.md rename to en/application-dev/application-test/Readme-EN.md diff --git a/en/application-dev/connectivity/figures/IPC_RPC_communication.PNG b/en/application-dev/connectivity/figures/IPC_RPC_communication.PNG new file mode 100644 index 0000000000000000000000000000000000000000..63f193ade7b3932279295641a5612bc5720befef Binary files /dev/null and b/en/application-dev/connectivity/figures/IPC_RPC_communication.PNG differ diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index 0eeef8040da8abd9710f3996f0b5f2c65ecf71e2..5512d7a016754c94174fe269d5ed58424a218fb6 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -1,135 +1,316 @@ -# IPC & RPC Development +# IPC & RPC Development Guidelines -## When to Use +## When to Use IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices. -## Available APIs -**Table 1** Native IPC APIs +## Available APIs -| Class/Interface | Function | Description | -| --------------- | -------- | ----------- | -| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | -| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. | -| IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. | +Table 1 Native IPC APIs -## How to Develop +| Class| API| Description| +| -------- | -------- | -------- | +| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr<IRemoteObject> AsObject() | Holder of a remote proxy object. If you call this API on the stub, the **RemoteObject** is returned; if you call this API on the proxy, the proxy object is returned.| +| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Callback used to process a request from the proxy and return the result. Derived classes need to override this API.| +| IRemoteProxy | | Service proxy class, which is derived from the **IRemoteProxy** class.| -**Using Native APIs** -1. Define the IPC interface **ITestAbility**. +## How to Develop - **ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub. +### **Using Native APIs** - ``` - class ITestAbility : public IRemoteBroker { - public: +1. Add dependencies. + + SDK dependency: + + ``` + #IPC scenario + external_deps = [ + "ipc:ipc_single", + ] + + #RPC scenario + external_deps = [ + "ipc:ipc_core", + ] + ``` + + In addition, the refbase implementation on which IPC/RPC depends is stored in **//utils**. Add the dependency on the Utils source code. + + ``` + external_deps = [ + "c_utils:utils", + ] + ``` + +2. Define the IPC interface **ITestAbility**. + + **ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub. + + ```c++ + #include "iremote_broker.h" + + // Define message codes. + const int TRANS_ID_PING_ABILITY = 5 + + const std::string DESCRIPTOR = "test.ITestAbility"; + + class ITestAbility : public IRemoteBroker { + public: // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. - DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); - int TRANS_ID_PING_ABILITY = 1; // Define the message code. + DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR)); virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. - }; - ``` + }; + ``` -2. Define and implement service provider **TestAbilityStub**. +3. Define and implement service provider **TestAbilityStub**. - This class is related to the IPC framework and needs to inherit **IRemoteStub**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy. + This class is related to the IPC framework and needs to inherit **IRemoteStub<ITestAbility>**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy. - ``` - class TestAbilityStub : public IRemoteStub { - public: - virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - int TestPingAbility(const std::u16string &dummy) override; + ```c++ + #include "iability_test.h" + #include "iremote_stub.h" + + class TestAbilityStub : public IRemoteStub { + public: + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int TestPingAbility(const std::u16string &dummy) override; }; - - int TestServiceStub::OnRemoteRequest(uint32_t code, - MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - switch (code) { - case TRANS_ID_PING_ABILITY: { - std::u16string dummy = data.ReadString16(); - int result = TestPingAbility(dummy); - reply.WriteInt32(result); - return 0; - } - default: - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - } - ``` - -3. Define the **TestAbility** class that implements functions for the stub. - - ``` - class TestAbility : public TestAbilityStub { - public: - int TestPingAbility(const std::u16string &dummy); - } - - int TestAbility::TestPingAbility(const std::u16string &dummy) { - return 0; - } - ``` - -4. Define and implement **TestAbilityProxy**. - - This class is implemented on the proxy and inherits **IRemoteProxy**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub. - - ``` - class TestAbilityProxy : public IRemoteProxy { - public: - explicit TestAbilityProxy(const sptr &impl); - int TestPingService(const std::u16string &dummy) override; - private: - static inline BrokerDelegator delegator_; // Use the iface_cast macro. - } - - TestAbilityProxy::TestAbilityProxy(const sptr &impl) - : IRemoteProxy(impl) - { - } - - int TestAbilityProxy::TestPingService(const std::u16string &dummy) { - MessageOption option; - MessageParcel dataParcel, replyParcel; - dataParcel.WriteString16(dummy); - int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); - int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; - return result; - } - ``` - -5. Register and start an SA. - - Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA. - - ``` - // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - samgr->AddSystemAbility(saId, new TestAbility()); - - // Register the TestAbilityStub instance with the SystemAbilityManager on a different device. - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - ISystemAbilityManager::SAExtraProp saExtra; - saExtra.isDistributed = true; // Set a distributed SA. - int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra); - ``` - -6. Obtain the SA. - - Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance. - - ``` - // Obtain the proxy of the SA registered on the local device. - sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(saId); - sptr testAbility = iface_cast(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. - - // Obtain the proxies of the SAs registered with other devices. - sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(saId, deviceId); // deviceId identifies a device. - sptr proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. - ``` + + int TestAbilityStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + switch (code) { + case TRANS_ID_PING_ABILITY: { + std::u16string dummy = data.ReadString16(); + int result = TestPingAbility(dummy); + reply.WriteInt32(result); + return 0; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + ``` + +4. Define the **TestAbility** class that implements functions for the stub. + + ```c++ + #include "iability_server_test.h" + + class TestAbility : public TestAbilityStub { + public: + int TestPingAbility(const std::u16string &dummy); + } + + int TestAbility::TestPingAbility(const std::u16string &dummy) { + return 0; + } + ``` + +5. Define and implement **TestAbilityProxy**. + + This class is implemented on the proxy and inherits **IRemoteProxy<ITestAbility>**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub. + + ```c++ + #include "iability_test.h" + #include "iremote_proxy.h" + #include "iremote_object.h" + + class TestAbilityProxy : public IRemoteProxy { + public: + explicit TestAbilityProxy(const sptr &impl); + int TestPingAbility(const std::u16string &dummy) override; + private: + static inline BrokerDelegator delegator_; // Use the iface_cast macro. + } + + TestAbilityProxy::TestAbilityProxy(const sptr &impl) + : IRemoteProxy(impl) + { + } + + int TestAbilityProxy::TestPingAbility(const std::u16string &dummy){ + MessageOption option; + MessageParcel dataParcel, replyParcel; + dataParcel.WriteString16(dummy); + int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; + } + ``` + +6. Register and start an SA. + + Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA. + + ```c++ + // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + samgr->AddSystemAbility(saId, new TestAbility()); + + // Register the TestAbilityStub instance with the SystemAbilityManager on a different device. + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + ISystemAbilityManager::SAExtraProp saExtra; + saExtra.isDistributed = true; // Set a distributed SA. + int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra); + ``` + +7. Obtain the SA. + + Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance. + + ```c++ + // Obtain the proxy of the SA registered on the local device. + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + sptr remoteObject = samgr->GetSystemAbility(saId); + sptr testAbility = iface_cast(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. + + // Obtain the proxy of the SA registered with any other devices. + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + + // networkId is the device identifier and can be obtained through GetLocalNodeDeviceInfo. + sptr remoteObject = samgr->GetSystemAbility(saId, networkId); + sptr proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. + ``` + +### **Using JS APIs** + +1. Add dependencies. + + ```ts + import rpc from "@ohos.rpc" + import featureAbility from "@ohos.ability.featureAbility" + ``` + + + +2. Bind the desired ability. + + Construct the **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through **deviceManager**. Then, construct the **connect** variable, and specify the callback that is called when the binding is successful, the binding fails, or the ability is disconnected. After that, call the API provided by **featureAbility** to bind an ability. + + ```ts + import rpc from "@ohos.rpc" + import featureAbility from "@ohos.ability.featureAbility" + + let proxy = null + let connectId = null + + // Bind the ability on a single device. + let want = { + // Enter the bundle name and ability name. + "bundleName": "ohos.rpc.test.server", + "abilityName": "ohos.rpc.test.server.ServiceAbility", + } + let connect = { + onConnect:function(elementName, remote) { + proxy = remote + }, + onDisconnect:function(elementName) { + }, + onFailed:function() { + proxy = null + } + } + connectId = featureAbility.connectAbility(want, connect) + + // If you're binding the ability across devices, use deviceManager to obtain the network ID of the target device. + import deviceManager from '@ohos.distributedHardware.deviceManager' + function deviceManagerCallback(deviceManager) { + let deviceList = deviceManager.getTrustedDeviceListSync() + let networkId = deviceList[0].networkId + let want = { + "bundleName": "ohos.rpc.test.server", + "abilityName": "ohos.rpc.test.service.ServiceAbility", + "networkId": networkId, + "flags": 256 + } + connectId = featureAbility.connectAbility(want, connect) + } + // The first parameter specifies the bundle name of the application, and the second parameter specifies the callback used to return the device ID obtained by using DeviceManager. + deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback) + ``` + + + +3. Process requests sent from the client. + + Call the **onConnect** API to return a proxy object inherited from **rpc.RemoteObject** after the ability is successfully bound. Implement the **onRemoteMessageRequest** API for the proxy object to process requests sent from the client. + + ```ts + onConnect(want: Want) { + var robj:rpc.RemoteObject = new Stub("rpcTestAbility") + return robj + } + class Stub extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor) + } + onRemoteMessageRequest(code, data, reply, option) { + // Process requests sent from the client based on the code. + return true + } + } + ``` + + + +4. Process responses sent from the server. + + Obtain the proxy object from the **onConnect** callback, call **sendRequestAsync** to send a request, and receive the response using a callback or a promise (an object representing the eventual completion or failure of an asynchronous operation and its result value). + + ```ts + // Use a promise. + let option = new rpc.MessageOption() + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + // Write parameters to data. + proxy.sendRequestAsync(1, data, reply, option) + .then(function(result) { + if (result.errCode != 0) { + console.error("send request failed, errCode: " + result.errCode) + return + } + // Read the result from result.reply. + }) + .catch(function(e) { + console.error("send request got exception: " + e) + } + .finally(() => { + data.reclaim() + reply.reclaim() + }) + + // Use a callback. + function sendRequestCallback(result) { + try { + if (result.errCode != 0) { + console.error("send request failed, errCode: " + result.errCode) + return + } + // Read the result from result.reply. + } finally { + result.data.reclaim() + result.reply.reclaim() + } + } + let option = new rpc.MessageOption() + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + // Write parameters to data. + proxy.sendRequest(1, data, reply, option, sendRequestCallback) + ``` + +5. Tear down the connection. + Use the API provided by **featureAbility** to tear down the connection when the communication is over. + ```ts + import rpc from "@ohos.rpc" + import featureAbility from "@ohos.ability.featureAbility" + function disconnectCallback() { + console.info("disconnect ability done") + } + featureAbility.disconnectAbility(connectId, disconnectCallback) + ``` diff --git a/en/application-dev/connectivity/ipc-rpc-overview.md b/en/application-dev/connectivity/ipc-rpc-overview.md index e75536863b1ae1b5c5371f51b0d7e26e4db97ed6..29fdec791c9a6b96d2ae2138b47a9b8dc48c050b 100755 --- a/en/application-dev/connectivity/ipc-rpc-overview.md +++ b/en/application-dev/connectivity/ipc-rpc-overview.md @@ -3,20 +3,42 @@ ## Basic Concepts -Inter-process communication (IPC) and remote procedure call (RPC) are used to implement cross-process communication. IPC uses the Binder driver to implement inter-process communication within a device, whereas RPC uses the intelligent software bus driver to implement inter-process communication across devices. +The inter-process communication (IPC) and remote procedure call (RPC) mechanisms are used to implement cross-process communication. The difference between them lies in that IPC uses the Binder driver to implement cross-process communication within a device, whereas RPC uses the DSoftBus driver to implement cross-process communication across devices. -IPC and RPC generally use the client-server model for communication. The client (service requester) obtains the proxy of the server (service provider) and uses this proxy to read and write data. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides interfaces for clients. To interact with an SA, the client must obtain the proxy of the SA from SAMgr. +The reason why cross-process communication is needed is that each process has its own independent resources and memory space and one process is not allowed to access the resources and memory space of other processes. IPC and RPC usually use the client-server model, where the client (service requester, that is, the process that requests a service) obtains the proxy of the server (service provider, that is, the process that provides the service) and uses the proxy to read and write data to implement data communication across processes. More specifically, the client constructs a proxy object of the server. The proxy object has the same functions as the server. To access a certain API of the server, you only need to access the corresponding API in the proxy object. The proxy object sends the request to the server, and the server processes the received request and returns the processing result to the proxy object through the driver. Then, the proxy object forwards the processing result to the client. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides APIs for clients. To communicate with a specific SA, the client must obtain the proxy of the SA from SAMgr. -In OpenHarmony documents, proxy represents the service requester, and stub represents the service provider. +In the following sections, proxy represents the service requester, and stub represents the service provider. + +![IPC&RPC communication mechanisms](figures/IPC_RPC_communication.PNG) ## Constraints -- The data transmitted for inter-process communication within a device cannot exceed 1 MB. If more data needs to be transmitted, use the anonymous shared memory. +- During cross-process communication within a single device, the maximum amount of data to be transmitted is about 1 MB. If the amount of data to be transmitted exceeds this limit, use the [anonymous shared memory](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-rpc.md#ashmem8). +- Subscription to death notifications of anonymous stub objects (not registered with SAMgr) is prohibited in RPC. +- During cross-process communication across processes, a proxy object cannot be passed back to the device that hosts the stub object pointed by the proxy object. That is, the proxy object pointing to the stub object of the remote device cannot be passed across processes twice on the local device. + +## **Recommendations** + +First, compile an API class and define message codes in the API class for both communication parties to identify operations. Unimplemented APIs are allowed in the API class because it must be inherited by both communication parties and its inheritance classes cannot be abstract classes. When inheriting the API class, both communication parties must implement the unimplemented APIs, so as to make sure that the inheritance classes are not abstract classes. + +Then, implement the API class specific to the stub, and override the **AsObject** and **OnRemoteRequest** APIs. In addition, compile the proxy to implement the APIs in the API class and override the **AsObject** API. You can also encapsulate an additional API for calling **SendRequest** to send data to the peer. + +After the preceding operations are done, register a system ability (SA) with SAMgr. Note that the registration should be completed in the process that hosts the stub. Then, obtain the proxy from SAMgr as needed to implement cross-process communication with the stub. + +Related steps are as follows: + +- Implementing the API class: Inherit **IRemoteBroker**, define message codes, and declare APIs that are not implemented in the API class. + +- Implementing the service provider (stub): Inherit **IRemoteStub** or **RemoteObject**, and override the **AsObject** and **OnRemoteRequest** APIs. + +- Implementing the service requester (proxy): Inherit **IRemoteProxy** or **RemoteProxy**, override the **AsObject** API, and encapsulate the required API to call **SendRequest**. + +- Registering the SA: Apply for a unique ID for the SA, and register the SA with SAMgr. -- The cross-device proxy object cannot be passed to the device hosting the stub object pointed by this proxy object. +- Obtaining the SA: Obtain the proxy based on the SA ID and device ID, and use the proxy to communicate with the remote end. ## Related Modules -[Distributed Scheduler](https://gitee.com/openharmony/ability_dmsfwk) +[Distributed Ability Manager Service Framework](https://gitee.com/openharmony/ability_dmsfwk) diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md index 8d9365d6bbba940bb85d9ac7493b7069c48845eb..4168d4645a8dd122eaf331017a91da0d8ecc2594 100755 --- a/en/application-dev/connectivity/subscribe-remote-state.md +++ b/en/application-dev/connectivity/subscribe-remote-state.md @@ -1,30 +1,172 @@ # Subscribing to State Changes of a Remote Object -IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** callback and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. +IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered. -Note that the proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered. +## When to Use +This subscription mechanism is applicable when the local proxy object needs to detect death of the process hosting the remote stub object or network detach of the device hosting the remote stub object. When the proxy detects death of the remote stub object, the proxy can clear local resources. Currently, IPC supports death notification for anonymous objects, but RPC does not. That is, you can only subscribe to death notifications of services that have been registered with SAMgr. +## **Using Native APIs** -## **Development Using Native APIs** +| API| Return Value Type| Feature Description| +| -------- | -------- | -------- | +| AddDeathRecipient(const sptr\ &recipient); | bool | Adds a recipient for death notifications of a remote stub object.| +| RemoveDeathRecipient(const sptr\ &recipient); | bool | Removes the recipient for death notifications of a remote stub object.| +| OnRemoteDied(const wptr\ &object); | void | Called when the remote stub object dies.| -| API| Description| -| -------- | -------- | -| AddDeathRecipient(const sptr\ &recipient); | Adds a recipient for death notifications of a remote stub object.| -| RemoveDeathRecipient(const sptr\ &recipient); | Removes the recipient for death notifications of a remote stub object.| -| OnRemoteDied(const wptr\ &object); | Called when the remote stub object dies.| +### Sample Code +```C++ +#include "iremote_broker.h" +#include "iremote_stub.h" -## Sample Code +// Define message codes. +enum { + TRANS_ID_PING_ABILITY = 5, + TRANS_ID_REVERSED_MONITOR +}; +const std::string DESCRIPTOR = "test.ITestAbility"; + +class ITestService : public IRemoteBroker { +public: + // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. + DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR)); + virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. +}; + +class TestServiceProxy : public IRemoteProxy { +public: + explicit TestAbilityProxy(const sptr &impl); + virtual int TestPingAbility(const std::u16string &dummy) override; + int TestAnonymousStub(); +private: + static inline BrokerDelegator delegator_; // Use the iface_cast macro. +}; + +TestServiceProxy::TestServiceProxy(const sptr &impl) + : IRemoteProxy(impl) +{ +} + +int TestServiceProxy::TestPingAbility(const std::u16string &dummy){ + MessageOption option; + MessageParcel dataParcel, replyParcel; + dataParcel.WriteString16(dummy); + int error = PeerHolder::Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; +} ``` + + + + +```c++ +#include "iremote_object.h" + class TestDeathRecipient : public IRemoteObject::DeathRecipient { public: virtual void OnRemoteDied(const wptr& remoteObject); } + +void TestDeathRecipient::OnRemoteDied(const wptr& remoteObject) +{ +} +``` + +```c++ +sptr object = new IPCObjectProxy(1, to_utf16(DESCRIPTOR)); sptr deathRecipient (new TestDeathRecipient());// Construct a death notification recipient. -bool result = proxy->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications. -result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications. +bool result = object->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications. +result = object->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications. +``` + +## **Using JS APIs** + +| API | Return Value Type| Feature Description | +| -------------------- | ---------- | ------------------------------------------------------------ | +| addDeathRecippient | boolean | Adds a recipient for death notifications of the remote object, including death notifications of the remote proxy.| +| removeDeathRecipient | boolean | Removes the recipient for death notifications of the remote object. | +| onRemoteDied | void | Called to perform subsequent operations when a death notification of the remote object is received.| + +### Sample Code + +```ts +import FA from "@ohos.ability.featureAbility"; +let proxy; +let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } +}; +let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.EntryAbility", +}; +FA.connectAbility(want, connect); +class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } +} +let deathRecipient = new MyDeathRecipient(); +proxy.addDeathRecippient(deathRecipient, 0); +proxy.removeDeathRecipient(deathRecipient, 0); +``` + +## Reverse Death Notification (Anonymous Stub) + +Forward dead notification is a mechanism that allows the proxy to detect death notifications of the stub. To achieve reverse dead notification, we can leverage the forward dead notification mechanism to allow the stub to detect death notifications of the proxy. + +Suppose there are two processes, A (the process hosting the original stub) and B (the process hosting the original proxy). After obtaining the proxy object of process A, process B creates an anonymous stub object (that is, a stub object not registered with SAMgr), which can be called a callback stub. Then, process B calls **SendRequest** to send the callback stub to the original stub of process A. As a result, process A obtains the callback proxy of process B. When process B dies or the device hosting process B detaches from the network, the callback stub dies. The callback proxy detects the death of the callback stub and sends a death notification to the original stub. In this way, reverse death notification is implemented. + +> NOTE +> - Reverse death notification can only be used for cross-process communication within a device. +> - When an anonymous stub object is not pointed by any proxy, the kernel automatically reclaims the object. + +### Sample Code + +```c++ +// Proxy +int TestAbilityProxy::TestAnonymousStub() +{ + MessageOption option; + MessageParcel dataParcel, replyParcel; + dataParcel.UpdateDataVersion(Remote()); + dataParcel.WriteRemoteObject(new TestAbilityStub()); + int error = Remote()->SendRequest(TRANS_ID_REVERSED_MONITOR,dataParcel, replyParcel, option); + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; +} + +// Stub + +int TestAbilityStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + switch (code) { + case TRANS_ID_REVERSED_MONITOR: { + sptr obj = data.ReadRemoteObject(); + if (obj == nullptr) { + reply.WriteInt32(ERR_NULL_OBJECT); + return ERR_NULL_OBJECT; + } + bool result = obj->AddDeathRecipient(new TestDeathRecipient()); + result ? reply.WriteInt32(ERR_NONE) : reply.WriteInt32(-1); + break; + } + default: + break; + } + return ERR_NONE; +} ``` diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 53e3ca5aeaa25ecea55f3e27272043e6b533e594..df633d8449281b12557bb3d39f333f97148af1a4 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -7,7 +7,7 @@ A relational database (RDB) store allows you to operate local data with or witho ## Available APIs -Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For details about the APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). +Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). ### Creating or Deleting an RDB Store @@ -17,8 +17,8 @@ The following table describes the APIs for creating and deleting an RDB store. | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> | Obtains an **RdbStoreV9** instance. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: version of the RDB store. Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported.| -| deleteRdbStoreV9(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: context of the application or function.
- **name**: name of the RDB store to delete.| +| getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | Obtains an **RdbStore** object. This API uses a promise to return the result. You can set parameters for the **RdbStore** object based on service requirements and use **RdbStore** APIs to perform data operations.
- **context**: application context.
- **config**: configuration of the RDB store.| +| deleteRdbStore(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: application context.
- **name**: name of the RDB store to delete.| ### Managing Data in an RDB Store @@ -33,29 +33,29 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| + | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating Data** - Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicatesV9**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. + Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. **Table 3** API for updating data - | Class | API | Description | + | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | update(values: ValuesBucket, predicates: RdbPredicatesV9): Promise<number> | Updates data based on the specified **RdbPredicatesV9** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data. | + | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data. | - **Deleting Data** - Call **delete()** to delete the data that meets the conditions specified by **RdbPredicatesV9**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. + Call **delete()** to delete the data that meets the conditions specified by **RdbPredicates**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. **Table 4** API for deleting data - | Class | API | Description | + | Class | API | Description | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | - | RdbStoreV9 | delete(predicates: RdbPredicatesV9): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicatesV9** object. This API uses a promise to return the number of rows updated.
- **predicates**: conditions for deleting data. | + | RdbStore | delete(predicates: RdbPredicates): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.
- **predicates**: conditions for deleting data. | - **Querying Data** @@ -66,50 +66,48 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 5** APIs for querying data - -| Class | API | Description | -| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | query(predicates: RdbPredicatesV9, columns?: Array<string>): Promise<ResultSetV9> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| -| RdbStoreV9 | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSetV9> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| -| RdbStoreV9 | remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicatesV9** that specifies the query conditions.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | Class | API | Description | + | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicates** that specifies the query condition.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| ### Using Predicates -The **RDB** module provides **RdbPredicatesV9** for you to set database operation conditions. +The **RDB** module provides **RdbPredicates** for you to set database operation conditions. -The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). +The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-relationalStore.md#rdbpredicates). **Table 6** APIs for using RDB store predicates -| Class | API | Description | +| Class | API | Description | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbPredicatesV9 | equalTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | -| RdbPredicatesV9 | notEqualTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | -| RdbPredicatesV9 | or(): RdbPredicatesV9 | Adds the OR condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the OR condition. | -| RdbPredicatesV9 | and(): RdbPredicatesV9 | Adds the AND condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the AND condition. | -| RdbPredicatesV9 | contains(field: string, value: string): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the OR condition.| +| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the AND condition.| +| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| ### Using the Result Set -You can use the APIs provided by **ResultSetV9** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. +You can use the APIs provided by **ResultSet** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. -For details about how to use result set APIs, see [Result Set](../reference/apis/js-apis-data-resultset.md). +For details about how to use **ResultSet** APIs, see [ResultSet](../reference/apis/js-apis-data-relationalStore.md#resultset). -> **NOTICE** -> +> **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly. **Table 7** APIs for using the result set | Class | API | Description | | ----------- | ---------------------------------------- | ------------------------------------------ | -| ResultSetV9 | goToFirstRow(): boolean | Moves to the first row of the result set. | -| ResultSetV9 | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. | -| ResultSetV9 | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| -| ResultSetV9 | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. | -| ResultSetV9 | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. | -| ResultSetV9 | close(): void | Closes the result set. | +| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set. | +| ResultSet | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. | +| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| +| ResultSet | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. | +| ResultSet | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. | +| ResultSet | close(): void | Closes the result set. | @@ -117,7 +115,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis > **NOTE** > -> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore V9**. +> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore**. > - The devices must be connected over network before the distributed tables are used. For details about the APIs and usage, see [Device Management](../reference/apis/js-apis-device-manager.md). **Setting Distributed Tables** @@ -126,7 +124,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** @@ -136,7 +134,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** @@ -144,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** @@ -152,7 +150,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| RdbStore | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** @@ -160,7 +158,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.| +| RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.| ### Backing Up and Restoring an RDB Store @@ -170,7 +168,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| +| RdbStore | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| **Restoring an RDB Store** @@ -178,17 +176,17 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| +| RdbStore | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| -**Transaction** +### Transaction Table 15 Transaction APIs | Class | API | Description | | -------- | ----------------------- | --------------------------------- | -| RdbStoreV9 | beginTransaction(): void | Starts the transaction before executing SQL statements.| -| RdbStoreV9 | commit(): void | Commits the executed SQL statements. | -| RdbStoreV9 | rollBack(): void | Rolls back the SQL statements that have been executed. | +| RdbStore | beginTransaction(): void | Starts the transaction before executing SQL statements.| +| RdbStore | commit(): void | Commits the executed SQL statements. | +| RdbStore | rollBack(): void | Rolls back the SQL statements that have been executed. | ## How to Develop @@ -203,27 +201,27 @@ Table 15 Transaction APIs FA model: ```js - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' let context = featureAbility.getContext() const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIGV9 = { name: "RdbTest.db", + const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` Stage model: ```ts - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // Obtain the context. - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; let context = null - class MainAbility extends Ability { + class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { context = this.context } @@ -231,10 +229,10 @@ Table 15 Transaction APIs const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIGV9 = { name: "rdbstore.db", + const STORE_CONFIG = { name: "rdbstore.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` @@ -248,14 +246,29 @@ Table 15 Transaction APIs The sample code is as follows: ```js - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - let insertPromise = rdbStoreV9.insert("test", valueBucket) + let insertPromise = rdbStore.insert("test", valueBucket) + ``` + + ```js + // Use a transaction to insert data. + beginTransaction() + try { + let u8 = new Uint8Array([1, 2, 3]) + const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } + const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 } + let insertPromise1 = rdbStore.insert("test", valueBucket1) + let insertPromise2 = rdbStore.insert("test", valueBucket2) + commit() + } catch (e) { + rollBack() + } ``` 3. Query data. - (1) Create an **RdbPredicatesV9** object to specify query conditions. + (1) Create an **RdbPredicates** object to specify query conditions. (2) Call the **query()** API to query data. @@ -264,17 +277,17 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let predicatesV9 = new data_rdb.RdbPredicatesV9("test"); - predicatesV9.equalTo("name", "Tom") - let promisequery = rdbStoreV9.query(predicatesV9) - promisequery.then((resultSetV9) => { - resultSetV9.goToFirstRow() - const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id")) - const name = resultSetV9.getString(resultSetV9.getColumnIndex("name")) - const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age")) - const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary")) - const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType")) - resultSetV9.close() + let predicates = new data_rdb.RdbPredicates("test"); + predicates.equalTo("name", "Tom") + let promisequery = rdbStore.query(predicates) + promisequery.then((resultSet) => { + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("id")) + const name = resultSet.getString(resultSet.getColumnIndex("name")) + const age = resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) + resultSet.close() }) ``` @@ -302,7 +315,7 @@ Table 15 Transaction APIs context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { console.info(`result.requestCode=${result.requestCode}`) }) - let promise = rdbStoreV9.setDistributedTables(["test"]) + let promise = rdbStore.setDistributedTables(["test"]) promise.then(() => { console.info("setDistributedTables success.") }).catch((err) => { @@ -312,7 +325,7 @@ Table 15 Transaction APIs 5. Synchronize data across devices. - (1) Construct an **RdbPredicatesV9** object to specify remote devices within the network to be synchronized. + (1) Construct an **RdbPredicates** object to specify remote devices within the network to be synchronized. (2) Call **rdbStore.sync()** to synchronize data. @@ -321,9 +334,9 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let predicateV9 = new data_rdb.RdbPredicatesV9('test') - predicateV9.inDevices(['12345678abcde']) - let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicateV9) + let predicate = new data_rdb.RdbPredicates('test') + predicate.inDevices(['12345678abcde']) + let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) promise.then((result) => { console.log('sync done.') for (let i = 0; i < result.length; i++) { @@ -350,7 +363,7 @@ Table 15 Transaction APIs } try { - rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { console.log('register observer failed') } @@ -365,8 +378,8 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let tableName = rdbStoreV9.obtainDistributedTableName(deviceId, "test"); - let resultSetV9 = rdbStoreV9.querySql("SELECT * FROM " + tableName) + let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); + let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` 8. Query data of a remote device. @@ -379,17 +392,17 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let rdbPredicateV9 = new data_rdb.RdbPredicatesV9('employee') - predicatesV9.greaterThan("id", 0) - let promiseQuery = rdbStoreV9.remoteQuery('12345678abcde', 'employee', rdbPredicateV9) - promiseQuery.then((resultSetV9) => { - while (resultSetV9.goToNextRow()) { - let idx = resultSetV9.getLong(0); - let name = resultSetV9.getString(1); - let age = resultSetV9.getLong(2); + let rdbPredicate = new data_rdb.RdbPredicates('employee') + predicates.greaterThan("id", 0) + let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) + promiseQuery.then((resultSet) => { + while (resultSet.goToNextRow()) { + let idx = resultSet.getLong(0); + let name = resultSet.getString(1); + let age = resultSet.getLong(2); console.info(idx + " " + name + " " + age); } - resultSetV9.close(); + resultSet.close(); }).catch((err) => { console.info("failed to remoteQuery, err: " + err) }) @@ -402,7 +415,7 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let promiseBackup = rdbStoreV9.backup("dbBackup.db") + let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(() => { console.info('Backup success.') }).catch((err) => { @@ -414,7 +427,7 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let promiseRestore = rdbStoreV9.restore("dbBackup.db") + let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(() => { console.info('Restore success.') }).catch((err) => { diff --git a/en/application-dev/device/device-location-geocoding.md b/en/application-dev/device/device-location-geocoding.md index c29b1a0ed206cde027d3002d8b110722a473bfda..e18c3fbcce93e40b87c3af9e473b3e1b2828fd4c 100644 --- a/en/application-dev/device/device-location-geocoding.md +++ b/en/application-dev/device/device-location-geocoding.md @@ -10,42 +10,40 @@ The geographic description helps users understand a location easily by providing ## Available APIs -The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md). +The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md). **Table1** APIs for geocoding and reverse geocoding | API | Description | | -------- | -------- | -| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result.| -| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result.| -| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. | -| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>> | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. | +| isGeocoderAvailable(): boolean; | Checks whether the (reverse) geocoding service is available.| +| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. | +| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>> | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. | +| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. | +| getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. | ## How to Develop -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > > The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network. -1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. +1. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. ```ts - import geolocation from '@ohos.geolocation'; + import geoLocationManager from '@ohos.geolocation'; ``` 2. Query whether geocoder service is available. - Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3. ```ts - geolocation.isGeoServiceAvailable((err, data) => { - if (err) { - console.log('isGeoServiceAvailable err: ' + JSON.stringify(err)); - } else { - console.log('isGeoServiceAvailable data: ' + JSON.stringify(data)); - } - }); + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var isAvailable = geoLocationManager.isGeocoderAvailable(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } ``` 3. Obtain the conversion result. @@ -53,13 +51,17 @@ The following table describes APIs available for mutual conversion between coord ```ts var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; - geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); - } - }); + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); + } else { + console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } ``` Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). @@ -67,13 +69,17 @@ The following table describes APIs available for mutual conversion between coord ```ts var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; - geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); - } - }); + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); + } else { + console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } ``` Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index 235ef590861ceb1a8b2f9b878954ea3d3cecccc9..1a386fe6bbfd44009b3aa8ab5ea48e36ad87f3c3 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -10,11 +10,11 @@ Real-time location of the device is recommended for location-sensitive services. ## Available APIs -For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md). +For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md). ## How to Develop -To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md). +To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geoLocationManager.md). 1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. The system provides the following location permissions: @@ -41,10 +41,10 @@ To learn more about the APIs for obtaining device location information, see [Geo You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md). -2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. +2. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities. - ``` - import geolocation from '@ohos.geolocation'; + ```ts + import geoLocationManager from '@ohos.geolocation'; ``` 3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.
@@ -78,7 +78,7 @@ To learn more about the APIs for obtaining device location information, see [Geo Sample code for initializing **requestInfo** for navigation: ```ts - var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` **Method 2:** @@ -107,7 +107,7 @@ To learn more about the APIs for obtaining device location information, see [Geo Sample code for initializing **requestInfo** for the location accuracy priority policy: ```ts - var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` 4. Instantiate the **Callback** object for the system to report location results. @@ -122,25 +122,24 @@ To learn more about the APIs for obtaining device location information, see [Geo 5. Start device location. ```ts - geolocation.on('locationChange', requestInfo, locationChange); + geoLocationManager.on('locationChange', requestInfo, locationChange); ``` 6. (Optional) Stop device location. ```ts - geolocation.off('locationChange', locationChange); + geoLocationManager.off('locationChange', locationChange); ``` If your application does not need the real-time device location, it can use the last known device location cached in the system instead. ```ts - geolocation.getLastLocation((err, data) => { - if (err) { - console.log('getLastLocation: err: ' + JSON.stringify(err)); - } else { - console.log('getLastLocation: data: ' + JSON.stringify(data)); - } - }); + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var location = geoLocationManager.getLastLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } ``` To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user. diff --git a/en/application-dev/device/inputdevice-guidelines.md b/en/application-dev/device/inputdevice-guidelines.md index 1037520e553246d42d2da80f572637af310b4adc..d29d1ae340f5f2c569559791fe2b001e07adce4a 100644 --- a/en/application-dev/device/inputdevice-guidelines.md +++ b/en/application-dev/device/inputdevice-guidelines.md @@ -40,8 +40,8 @@ try { // 1. Obtain the list of input devices and check whether a physical keyboard is connected. inputDevice.getDeviceList().then(data => { for (let i = 0; i < data.length; ++i) { - inputDevice.getKeyboardType(data[i]).then(res => { - if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) { + inputDevice.getKeyboardType(data[i]).then(type => { + if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) { // The physical keyboard is connected. isPhysicalKeyboardExist = true; } @@ -53,7 +53,7 @@ try { console.log(`Device event info: ${JSON.stringify(data)}`); inputDevice.getKeyboardType(data.deviceId, (error, type) => { console.log("The keyboard type is: " + type); - if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { + if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { // The physical keyboard is inserted. isPhysicalKeyboardExist = true; } else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { diff --git a/en/application-dev/device/pointerstyle-guidelines.md b/en/application-dev/device/pointerstyle-guidelines.md index d8ceab11829f1d5e717a61ec53ecfec19261226d..06a904a5c5ed3a52dba9bf93bc0fa5a9e8a48690 100644 --- a/en/application-dev/device/pointerstyle-guidelines.md +++ b/en/application-dev/device/pointerstyle-guidelines.md @@ -7,7 +7,7 @@ Mouse pointer management provides the functions such as displaying or hiding the ## Modules to Import ```js -import inputDevice from '@ohos.multimodalInput.pointer'; +import pointer from '@ohos.multimodalInput.pointer'; ``` ## Available APIs diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 768866b4974eb59a81aa3d17f9d099d03fbdc415..63723d92c64c1c1e7ecc6f74fcd82fe73e904ad7 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -14,11 +14,10 @@ The following table lists the USB APIs currently available. For details, see the | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. | -| requestRight(deviceName: string): Promise\ | Requests the temporary permission for a given application to access the USB device. | -| removeRight(deviceName: string): boolean | Removes the permission for a given application to access the USB device. | -| connectDevice(device: USBDevice): Readonly\ | Connects to the USB device based on the device information returned by `getDevices()`. | -| getDevices(): Array> | Obtains the USB device list. | +| hasRight(deviceName: string): boolean | Checks whether the user has the device access permissions. | +| requestRight(deviceName: string): Promise\ | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. | +| connectDevice(device: USBDevice): Readonly\ | Connects to the USB device based on the device list returned by `getDevices()`. | +| getDevices(): Array> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. | @@ -37,7 +36,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ```js // Import the USB API package. - import usb from '@ohos.usb'; + import usb from '@ohos.usbV9'; // Obtain the USB device list. let deviceList = usb.getDevices(); /* diff --git a/en/application-dev/faqs/faqs-ability.md b/en/application-dev/faqs/faqs-ability.md index ed3cfcc4412379ea61974895ca111256b68ae696..bff181efb95a1c3363b2183ca86965c7fad731ba 100644 --- a/en/application-dev/faqs/faqs-ability.md +++ b/en/application-dev/faqs/faqs-ability.md @@ -60,7 +60,7 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Configure the **startWindowIcon** attribute under **abilities** in the **module.json5** file. -Reference: [Application Package Structure Configuration File](../quick-start/stage-structure.md) +Reference: [Application Package Structure (Stage Model)](../quick-start/module-configuration-file.md) Example: @@ -83,17 +83,15 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change. -Reference: [Ability Development](../ability/stage-ability.md) - ## Can I obtain the context through globalThis in the stage model? Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 Do not use **globalThis** to obtain the context in the stage model. This is because all the processes of an application share a JS VM instance in the stage model. Multiple abilities can run on these processes and share the same global object. If **globalThis** is used, the context of different abilities of the same JS VM instance may be returned. -For details about the recommended operation, see [Context in the Stage Model](../ability/context-userguide.md#context-in-the-stage-model). +Reference of the recommended operation: [Context (Stage Model)](../application-models/application-context-stage.md) -## How do I obtain the HAP file installation path of application B from application A? +## How do I obtain the HAP installation path of application B from application A? Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9 @@ -109,7 +107,7 @@ The callee uses **AbilityContext.terminateSelfWithResult** to destroy its abilit Applicable to: OpenHarmony SDK 3.2.5.5, FA model of API version 8 -After a widget is added, the **onCreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed. +After a widget is added, the **oncreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed. ## How do I obtain the context? @@ -214,3 +212,5 @@ The following conditions must be met: 1. Before the redirection to the previous page, a confirm dialog box will be displayed. Note that **router.disableAlertBeforeBackPage** is used to disable the display of a confirm dialog box before returning to the previous page (default), and **router.enableAlertBeforeBackPage** is used to enable the display. 2. The system return key is used. + + \ No newline at end of file diff --git a/en/application-dev/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md index 4bb5fe54817e245807612eaac1a0b6d235101f7a..fff002316e8ad2364dedd6c870d3a64ca234a94b 100644 --- a/en/application-dev/file-management/Readme-EN.md +++ b/en/application-dev/file-management/Readme-EN.md @@ -3,4 +3,7 @@ - [MediaLibrary Overview](medialibrary-overview.md) - [Media Asset Management](medialibrary-resource-guidelines.md) - [File Path Management](medialibrary-filepath-guidelines.md) - - [Album Management](medialibrary-album-guidelines.md) \ No newline at end of file + - [Album Management](medialibrary-album-guidelines.md) + +- File Access Framework + - [File Access Framework Overview](file-access-framework-overview.md) diff --git a/en/application-dev/file-management/figures/faf-data-flow.png b/en/application-dev/file-management/figures/faf-data-flow.png new file mode 100644 index 0000000000000000000000000000000000000000..d3c6fd90b59712bf2728208f247d531b919b4b3b Binary files /dev/null and b/en/application-dev/file-management/figures/faf-data-flow.png differ diff --git a/en/application-dev/file-management/figures/public-file-operation.png b/en/application-dev/file-management/figures/public-file-operation.png new file mode 100644 index 0000000000000000000000000000000000000000..bb434a499da63e2245bd806bfc6e0d42686d883d Binary files /dev/null and b/en/application-dev/file-management/figures/public-file-operation.png differ diff --git a/en/application-dev/file-management/file-access-framework-overview.md b/en/application-dev/file-management/file-access-framework-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..1cdf4f6c3513606c7361b951f24d3424bb065113 --- /dev/null +++ b/en/application-dev/file-management/file-access-framework-overview.md @@ -0,0 +1,44 @@ +# File Access Framework Overview + +On devices running OpenHarmony 3.2 (API version 9) or later, applications can access public files on the local device, remote device, and external storage device, as well as files shared by multiple users, based on the File Access Framework (FAF). + +To ensure user data privacy, this framework allows users to create, open, delete, rename, and move files on the file access server only through the **File Manager** and **File Picker** applications. + +The user data of an application is stored on the device even after the application is uninstalled. + +If a system application needs to access public files on the local device, use [File Path Management](medialibrary-filepath-guidelines.md). + +> **NOTE** +> 1. For a non-management system application, for example, **Gallery**, use the **mediaLibrary** APIs for direct file operation. +> 2. In principle, do not mix use the FAF APIs with the mediaLibrary APIs. + +## FAF Mechanism +Based on the OpenHarmony [ExtensionAbility mechanism](../application-models/extensionability-overview.md), the FAF provides unified APIs for external systems. With these APIs, applications can preview and operate public files to implement their own logic. + +You can visit the [source repository](https://gitee.com/openharmony/filemanagement_user_file_service) for more details. + +The following figure shows the FAF-based file operation process. + +**Figure 1** Hierarchy of public file operations + +![](figures/public-file-operation.png) + +- **File access client**: an application that needs to access or operate public files. By starting the file selector application, it enables users to perform file operations on the UI. +- **File selector application**: a system application that allows users to access all shared datasets. You can use the FAF APIs to operate the datasets. +- **File access server**: a service that supports dataset sharing in the system. Currently, [UserFileManager](https://gitee.com/openharmony/multimedia_medialibrary_standard) and ExternalFileManager are available. UserFileManager manages datasets on local disks and distributed devices, and ExternalFileManager manages datasets on external storage devices such as SD cards and USB flash drives. You can also share your own datasets based on the FAF server configuration. + +The FAF has the following features: +- Users can browse the datasets provided by all file server applications in the system, rather than those provided by a single application. +- The file access client can operate files through the file selector application, without obtaining the permission to use the FAF. +- Multiple temporarily mounted devices, such as external storage cards and distributed devices, can be accessed at the same time. + +## Data Models +Data models in the FAF are transferred through URI, FileInfo, and RootInfo. For details, see [fileExtension](../reference/apis/js-apis-fileExtensionInfo.md). Applications on the file access server can use the **FileAccessExtensionAbility** APIs to securely share their data. + +**Figure 2** Data flow of the public file access framework + +![](figures/faf-data-flow.png) + +NOTE +- In the FAF, the file access client does not directly interact with the file access server. The client only needs to have the permission to start the file selector application. +- The file selector application provides a standard document access UI for users, even if the underlying file access servers differ greatly. diff --git a/en/application-dev/file-management/medialibrary-filepath-guidelines.md b/en/application-dev/file-management/medialibrary-filepath-guidelines.md index fc9b327031cfee8ea6de601b3c3d268bbf161c53..23b7604f4dde99c832b59305595e94b06ea1baa2 100644 --- a/en/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/en/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -69,7 +69,7 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o **How to Develop** -1. Call [Context.getFilesDir](../reference/apis/js-apis-Context.md#contextgetfilesdir) to obtain the directory of the application sandbox. +1. Call [Context.getFilesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox. 2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. 3. Call **fileio.open** to open the file in the sandbox. 4. Call **fileAsset.open** to open the file in the public directory. diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index 699eb7cb6cae5f198c1620e22b7c3f0df4a90813..0b5b382d72fec98bfa18c3cfdee7bd61ef713da1 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -3,27 +3,30 @@ ## Introduction **AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. - Before calling the APIs, be familiar with the following terms: - **Audio interruption**: When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. - **Status check**: During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. - **Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). -- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus preemption occurs. Focus preemption triggers focus transfer, and the **AudioRenderer** instance that originally has the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to set the independent mode. +- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus transfer is triggered by focus preemption. When focus transfer occurs, the **AudioRenderer** instance that is having the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to switch to the independent mode. ## Working Principles The following figure shows the audio renderer state transitions. -Figure 1 Audio renderer state transitions +**Figure 1** Audio renderer state transitions ![audio-renderer-state](figures/audio-renderer-state.png) - **PREPARED**: The audio renderer enters this state by calling **create()**. + - **RUNNING**: The audio renderer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state. -- **PAUSED**: The audio renderer in the **RUNNING** state can call **pause()** to pause the audio playback. After the audio playback is paused, it can call **start()** to resume the playback. -- **STOPPED**: The audio renderer in the **PAUSED** or **RUNNING** state can call **stop()** to stop the playback. -- **RELEASED**: The audio renderer in the **PREPARED**, **PAUSED**, or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state. + +- **PAUSED**: The audio renderer enters this state by calling **pause()** when it is in the **RUNNING** state. When the audio playback is paused, it can call **start()** to resume the playback. + +- **STOPPED**: The audio renderer enters this state by calling **stop()** when it is in the **PAUSED** or **RUNNING** state. + +- **RELEASED**: The audio renderer enters this state by calling **release()** when it is in the **PREPARED**, **PAUSED**, or **STOPPED** state. In this state, the audio renderer releases all occupied hardware and software resources and will not transit to any other state. ## How to Develop @@ -62,7 +65,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ```js async function startRenderer() { let state = audioRenderer.state; - // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started. + // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state when start() is called. if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); @@ -258,8 +261,8 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; await audioRenderer.setInterruptMode(interruptMode); - // Set the volume of the stream to 10. - let volume : number = 10; + // Set the volume of the stream to 0.5. + let volume : number = 0.5; await audioRenderer.setVolume(volume); ``` @@ -303,7 +306,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th case audio.InterruptHint.INTERRUPT_HINT_RESUME: startRenderer(); break; - // Notify the application that the audio stream is interrupted. The application determines whether to continue. (In this example, the application pauses the rendering.) + // Notify the application that the audio stream is interrupted. The application then determines whether to continue. (In this example, the application pauses the rendering.) case audio.InterruptHint.INTERRUPT_HINT_PAUSE: isPlay = false; pauseRenderer(); @@ -312,7 +315,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th } }); - audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be received. + audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be listened for. ``` 10. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. @@ -358,7 +361,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ```js try { - audioRenderer.on('invalidInput', () => { // The string does not match. + audioRenderer.on('invalidInput', () => { // The string is invalid. }) } catch (err) { console.info(`Call on function error, ${err}`); // The application throws exception 401. @@ -373,7 +376,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th 14. (Optional) Refer to the complete example of **on('audioInterrupt')**. - Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRenderer1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. + Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRender1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. ```js async runningAudioRender1(){ @@ -429,7 +432,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th let rlen = 0; rlen += bufferSize; - // 1.7 Render the original audio data in the buffer by using audioRenderer. + // 1.7 Render the original audio data in the buffer by using audioRender. let id = setInterval(async () => { if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. ss1.closeSync(); @@ -505,7 +508,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th let rlen = 0; rlen += bufferSize; - // 2.7 Render the original audio data in the buffer by using audioRenderer. + // 2.7 Render the original audio data in the buffer by using audioRender. let id = setInterval(async () => { if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. ss2.closeSync(); diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md index 420d09121f86b7a4612c2e7ad6fe5f29831be80b..3dde56c84f321a6200c45b1839eccdabcba942aa 100644 --- a/en/application-dev/napi/mindspore-lite-guidelines.md +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -61,7 +61,7 @@ The development process consists of the following main steps: The required model can be downloaded directly or obtained using the model conversion tool. - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example. - - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format. + - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/zh-CN/r1.5/use/downloads.html#id1) to convert it to the `.ms` format. 2. Create a context, and set parameters such as the number of runtime threads and device type. diff --git a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md deleted file mode 100644 index 71ffeb0b07acfb088988163a68f72882d267f49b..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md +++ /dev/null @@ -1,167 +0,0 @@ -# Agent-Powered Scheduled Reminder Development - -## When to Use - -You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. - - -## Available APIs - -**reminderAgent** encapsulates the APIs for publishing and canceling reminders. - -For details about the APIs, see [reminderAgent](../reference/apis/js-apis-reminderAgent.md). - -**Table 1** Major APIs in reminderAgent - -| Name| Description| -| -------- | -------- | -| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | -| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| -| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application.| -| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application.| -| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder.| -| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type.| - -## How to Develop - -> **NOTE** -> -> 1. To publish a reminder through the reminder agent, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. -> -> 2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8). - -1. Define a reminder agent. - - Sample code for defining a reminder agent for a countdown timer: - ```js - import reminderAgent from '@ohos.reminderAgent'; - import notification from '@ohos.notification'; - export default { - // ArkTS project: - let timer : reminderAgent.ReminderRequestTimer = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10, - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - } - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION - } - } - ``` - - Sample code for defining a reminder agent for a calendar event: - - ```js - // ArkTS project: - let calendar : reminderAgent.ReminderRequestCalendar = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, - dateTime: { - year: 2050, - month: 7, - day: 30, - hour: 11, - minute: 14, - second: 30 - }, - repeatMonths: [1], - repeatDays: [1], - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION - } - ``` - - Sample code for defining a reminder agent for an alarm: - - ```js - // ArkTS project: - let alarm : reminderAgent.ReminderRequestAlarm = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, - hour: 11, - minute: 14, - daysOfWeek: [0], - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION - } - ``` - -2. Publish a countdown reminder. - ```js - startTimer() { - reminderAgent.publishReminder(this.timer, (err, reminderId) =>{ - this.printInfo(JSON.stringify(err)); - this.printInfo("reminderId:" + reminderId); - }); - } - ``` - - HML page code: - ```html -
- -
- ``` diff --git a/en/application-dev/notification/background-agent-scheduled-reminder-overview.md b/en/application-dev/notification/background-agent-scheduled-reminder-overview.md deleted file mode 100644 index a9eccc77a9fecd9d1044eead091bfe9ffb097310..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/background-agent-scheduled-reminder-overview.md +++ /dev/null @@ -1,4 +0,0 @@ -# Agent-Powered Scheduled Reminder Overview - -Your application can call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. - diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index 9b89cfd83f8a3af29bda3fe76016d269561282cb..439bbdcb9d9455a36c75ceb8ba39e728d1aecebd 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -5,11 +5,30 @@ - [Getting Started with ArkTS in FA Model](start-with-ets-fa.md) - [Getting Started with JavaScript in FA Model](start-with-js-fa.md) - Development Fundamentals - - [Application Package Structure Configuration File (FA Model)](package-structure.md) - - [Application Package Structure Configuration File (Stage Model)](stage-structure.md) - - [SysCap](syscap.md) + - Application Package Fundamentals + - [Application Package Overview](application-package-overview.md) + - Application Package Structure + - [Application Package Structure in Stage Model](application-package-structure-stage.md) + - [Application Package Structure in FA Model](application-package-structure-fa.md) + - [HAR File Structure](har-structure.md) + - Multi-HAP Mechanism + - [Multi-HAP Design Objectives](multi-hap-objective.md) + - [Multi-HAP Build View](multi-hap-build-view.md) + - [Multi-HAP Development, Debugging, Release, and Deployment Process](multi-hap-release-deployment.md) + - [Multi-HAP Usage Rules](multi-hap-rules.md) + - [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md) + - [Application Installation and Uninstallation Process](application-package-install-uninstall.md) + - Application Configuration Files in Stage Model + - [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md) + - [app.json5 Configuration File](app-configuration-file.md) + - [module.json5 Configuration File](module-configuration-file.md) + - Application Configuration Files in FA Model + - [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md) + - [Internal Structure of the app Tag](app-structure.md) + - [Internal Structure of deviceConfig Tag](deviceconfig-structure.md) + - [Internal Structure of the module Tag](module-structure.md) - [Resource Categories and Access](resource-categories-and-access.md) - - Learning ArkTS +- Learning ArkTS - [Getting Started with ArkTS](arkts-get-started.md) - ArkTS Syntax (Declarative UI) - [Basic UI Description](arkts-basic-ui-description.md) diff --git a/en/application-dev/quick-start/app-configuration-file.md b/en/application-dev/quick-start/app-configuration-file.md new file mode 100644 index 0000000000000000000000000000000000000000..3fff90e0682c4f79e63fa0ee8306a5f8aa7e9385 --- /dev/null +++ b/en/application-dev/quick-start/app-configuration-file.md @@ -0,0 +1,56 @@ +# app.json5 Configuration File + + +This document gives an overview of the **app.json5** configuration file. To start with, let's go through an example of what this file contains. + +```json +{ + "app": { + "bundleName": "com.application.myapplication", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "description": "$string:description_application", + "distributedNotificationEnabled": true, + "minAPIVersion": 9, + "targetAPIVersion": 9, + "apiReleaseType": "Release", + "debug": false, + "entityType": "media", + "car": { + "minAPIVersion": 8, + } + }, +} +``` + + +As shown above, the **app.json5** file contains several tags. + + + **Table 1** Tags in the app.json5 file + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:
- Consists of letters, digits, underscores (_), and periods (.).
- Starts with a letter.
- Contains 7 to 127 bytes.
You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No| +| debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.
- **true**: The application can be debugged.
- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)| +| icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index. | String| No| +| label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index. | String| No| +| description | Description of the application. The value is a string with a maximum of 255 bytes or a resource index to the description. | String| Yes (initial value: left empty)| +| vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| versionCode | Version number of the application. The value is a 32-bit non-negative integer less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number| No| +| versionName | Version number of the application displayed to users.
The value consists of only digits and dots. The four-part format *A.B.C.D* is recommended, wherein:
Part 1 (*A*): major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Part 2 (*B*): minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Part 3 (*C*): feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Part 4 (*D*): maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.
The value contains a maximum of 127 bytes.| String| No| +| minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario.| Number| Yes (initial value: value of **versionCode**)| +| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| +| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| +| apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.
- **Canary**: indicates a restricted release.
- **Beta**: indicates a publicly released beta version.
- **Release**: indicates a publicly released official version.
The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| +| distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.
- **true**: Distributed notification is enabled.
- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)| +| entityType | Type of the application. The options are as follows:
- game
- media
- communication
- news
- travel
- utility
- shopping
- education
- kids
- business
- photography
- unspecified| String| Yes (initial value: **"unspecified"**)| +| multiProjects | Whether the application supports joint development of multiple projects.
- **true**: The application supports joint development of multiple projects.
- **false**: The application does not support joint development of multiple projects.| Boolean| Yes (initial value: **false**)| +| tablet | Tablet-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| tv | TV-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| wearable | Wearable-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on wearables, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| car | Head unit–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on head units, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| default | Default device–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on default devices, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| diff --git a/en/application-dev/quick-start/app-structure.md b/en/application-dev/quick-start/app-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..62b23fad4d660b1d3e516a696b0f7ce95bbde053 --- /dev/null +++ b/en/application-dev/quick-start/app-structure.md @@ -0,0 +1,49 @@ +# Internal Structure of the app Tag + + +The **app** tag contains application-wide configuration. The internal structure is as follows: + +### Internal Structure of the app Tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| bundleName | Bundle name, which uniquely identifies an application. The bundle name must start with a letter and can contain only letters, digits, underscores (_), and periods (.). The bundle name is a string with 7 to 127 bytes of a reverse domain name, for example, **"com.example.myapplication"**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String| No| +| vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +|version | Version of the application.| Object| No| +| apiVersion | OpenHarmony API version on which the application depends.| Object| Yes (initial value: left empty)| +| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)| +| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)| + +#### Internal Structure of the version Atttribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:
For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.
*A* indicates the major version number.
*B* indicates the minor version number.
*C* indicates the patch version number. For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
*A* indicates the major version number.
*B* indicates the minor version number.
*C* indicates the feature version number.
*D* indicates the patch version number.| Number| No| +| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:
API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No| +| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)| + +#### Internal Structure of the apiVersion Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| compatible | Minimum API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| +| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| +| releaseType | SDK status when the application is running.
**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.
**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| + +### Example of the **app** Tag + +```json +"app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 8, + "name": "8.0.1" + }, + "apiVersion": { + "compatible": 8, + "target": 9, + "releaseType": "Beta1" + } + } +``` diff --git a/en/application-dev/quick-start/application-configuration-file-overview-fa.md b/en/application-dev/quick-start/application-configuration-file-overview-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..73bc7ebb53a70742bf5d2f0e581ddcae1db673bc --- /dev/null +++ b/en/application-dev/quick-start/application-configuration-file-overview-fa.md @@ -0,0 +1,118 @@ +# Application Configuration File Overview (FA Model) + + +Each application project must have configuration files in its code directory. These configuration files provide basic application information for OpenHarmony build tools, the operating system, and application markets. + + +The application configuration file must contain the following information: + + +- Basic information of the application, including the bundle name, vendor, and version number. Such information must be set under the **app** tag. + +- Component information of the application, including all abilities, device types, component types, and syntax types in use. + +- Device-specific information of the application. Such information affects the functioning of the application on the device. + + +When developing an application in the Feature Ability (FA) model, you must declare the package structure of the application in the **config.json** file. + + +## Configuration File Internal Structure + +The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| [app](app-structure.md) | Application-wide configuration. Different HAP files of an application must use the same **app** configuration. | Object| No| +| [deviceConfig](deviceconfig-structure.md) | Device-specific configuration. | Object| No| +| [module](module-structure.md) | HAP configuration. It is valid only for the current HAP file.| Object| No| + +Example of the **config.json** file: + + +```json +{ + "app": { + "vendor": "example", + "bundleName": "com.example.demo", + "version": { + "code": 1000000, + "name": "1.0.0" + } + }, + "deviceConfig": { + }, + "module": { + "mainAbility": ".MainAbility_entry", + "deviceType": [ + "tablet" + ], + "commonEvents": [ + { + "name": ".MainAbility", + "permission": "ohos.permission.GET_BUNDLE_INFO", + "data": [ + "com.example.demo", + "100" + ], + "events": [ + "install", + "update" + ] + } + ], + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "MainAbility_entry", + "name": ".MainAbility_entry", + "srcLanguage": "ets", + "icon": "$media:icon", + // $string:MainAbility_entry_desc is a resource index. + "description": "$string:MainAbility_entry_desc", + "formsEnabled": false, + // $string:MainAbility_entry_label is a resource index. + "label": "$string:MainAbility_entry_label", + "type": "page", + "launchType": "standard" + } + ], + "distro": { + "moduleType": "entry", + "installationFree": false, + "deliveryWithInstall": true, + "moduleName": "myapplication" + }, + "package": "com.example.myapplication", + "srcPath": "", + "name": ".myapplication", + "js": [ + { + "mode": { + "syntax": "ets", + "type": "pageAbility" + }, + "pages": [ + "pages/index" + ], + "name": ".MainAbility_entry", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} +``` diff --git a/en/application-dev/quick-start/application-configuration-file-overview-stage.md b/en/application-dev/quick-start/application-configuration-file-overview-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..ff66e3d405738a44f0c645593ffb0dbfb5beca97 --- /dev/null +++ b/en/application-dev/quick-start/application-configuration-file-overview-stage.md @@ -0,0 +1,25 @@ +# Application Configuration File Overview (Stage Model) + + +Each application project must have configuration files in its code directory. These configuration files provide basic application information for build tools, operating systems, and application markets. + + +In the code directory of an application project developed in stage model, there are two types of configuration files: one **app.json5** file and one or more **module.json5** files. + + +The [app.json5](app-configuration-file.md) file contains the following contents: + + +- Application-wide configuration, including the bundle name, developer, and version number. + +- Device-specific configuration. + + +The [module.json5](module-configuration-file.md) file contains the following contents: + + +- Basic module configuration, such as the name, type, description, and supported device types of the module. + +- Information about the [application components](../application-models/stage-model-development-overview.md), including the descriptions of the UIAbility and ExtensionAbility components. + +- Information about the permissions required during application running. diff --git a/en/application-dev/quick-start/application-package-install-uninstall.md b/en/application-dev/quick-start/application-package-install-uninstall.md new file mode 100644 index 0000000000000000000000000000000000000000..3ccafd9ad3da5f98b9fbd229ff7025863ca105d8 --- /dev/null +++ b/en/application-dev/quick-start/application-package-install-uninstall.md @@ -0,0 +1,8 @@ +# Application Installation and Uninstallation Process + + +The OpenHarmony bundle manager service module provides APIs for installing, updating, and uninstalling applications. You can call these APIs when needed. After you release your application to the application market, users can install and uninstall it on their device. + + + **Figure 1** Process of installing and uninstalling an application +![hap-intall-uninstall](figures/hap-intall-uninstall.png) diff --git a/en/application-dev/quick-start/application-package-overview.md b/en/application-dev/quick-start/application-package-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..c9c16ad5ec6a70b48180fc277d46c54664ca2182 --- /dev/null +++ b/en/application-dev/quick-start/application-package-overview.md @@ -0,0 +1,18 @@ +# Application Package Overview + + +A user application, also known as an application or app, runs on the operating system of devices and provides particular services for users. The software package corresponding to an application is called an application package. + + +OpenHarmony provides an efficient management mechanism for application packages. By harnessing this mechanism, you can easily develop, install, query, update, and uninstall application packages. +- To accelerate application deployment, you can use the integrated development tool provided by OpenHarmony to integrate executable code, resources, and third-party libraries into an OpenHarmony application package. + +- To distribute your application package by device type, you can specify the device types for distribution in the application package configuration file provided by OpenHarmony. + +- An application may provide a wide range of features. It is a good practice to divide and manage application features by module. OpenHarmony provides a multi-package management mechanism on an application-by-application basis. You can aggregate different application features into different packages to facilitate subsequent maintenance and expansion. + +- To allow an application to run across various chip platforms, such as x86, Arm, and other 32-bit or 64-bit platforms, OpenHarmony abstracts away the differences between chip platforms for application packages. + +- With a myriad of query APIs in OpenHarmony, you can quickly check the information about applications, including the application versions, names, components, and permissions. + +- To facilitate resource search and use, the bundle management service in OpenHarmony archives resources by type (media, native, string, internationalization, and more) in different directories and integrates resource index files. diff --git a/en/application-dev/quick-start/application-package-structure-fa.md b/en/application-dev/quick-start/application-package-structure-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..6909481445ecb1219c30ed3ae425d6b475662805 --- /dev/null +++ b/en/application-dev/quick-start/application-package-structure-fa.md @@ -0,0 +1,24 @@ +# Application Package Structure in FA Model + + +To develop an application based on the [FA model](application-configuration-file-overview-fa.md), it is essential to understand the application package structure in this model. + + +The difference between the application package structures in the FA model and stage model lies in where the internal files of a HAP file are stored. In the FA model, all the resource files, library files, and code files are stored in the **assets** folder, where the files are further organized. + + +- **config.json** is an application configuration file, where the template code is automatically created by DevEco Studio. You can modify the configuration as required. For details about the fields in this file, see [Internal Structure of the app Tag](app-structure.md). + +- The **assets** folder is a collection of all the resource files, library files, and code files in a HAP file. It can be further organized into the **entry** folder and the **js** folder. The **entry** folder stores the **resources** folder and the **resources.index** file. + +- The **resources** folder stores resource files (such as strings and images) of the application. + +- The **resources.index** file provides a resource index table, which is generated by DevEco Studio invoking the specific SDK tool. + +- The **js** folder stores code files created after compilation. + +- The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle. + +**Figure 1** Application package structure in FA model + +![app-pack-fa](figures/app-pack-fa.png) \ No newline at end of file diff --git a/en/application-dev/quick-start/application-package-structure-stage.md b/en/application-dev/quick-start/application-package-structure-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..b9bd91d798c6a57c06c74cebb38bf558c8fa011d --- /dev/null +++ b/en/application-dev/quick-start/application-package-structure-stage.md @@ -0,0 +1,32 @@ +# Application Package Structure in Stage Model + + +To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it is essential to understand the structure of the application package created after the application is built and packaged. + + +- In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file in .hap format, and a module of the Library type is built into a [Harmony Ability Resources (HAR) file](har-structure.md) in .tgz format. + A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below. + + **Figure 1** Relationship between modules and UIAbility components + + ![ability-and-module](figures/ability-and-module.png) + + Unless otherwise specified, the modules described in this document refer to the modules of the Ability type. + +- As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature. + - HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature. + - HAP of the feature type: dynamic feature module of the application, whose **type** field is set to **"feature"** in the [module.json5](module-configuration-file.md) file. Each application can contain zero, one, or more HAP files of the feature type, which are used to implement the application features. You can configure this type of HAP file to be downloaded and installed independently as required or to be downloaded and installed together with the HAP file of the entry type. For details, see **deliveryWithInstall** in [module.json5 Configuration File](module-configuration-file.md). + +- All the HAP files in an application are integrated into a bundle, and the bundle name is the unique identifier of the application. For details, see **bundleName** tag in [app.json5 Configuration File](app-configuration-file.md). Note that to release an application to the application market, all HAP files (that is, the bundle) contained in the application must be packed into an Application Package (App Pack) in .app format, which also contains the **pack.info** file that describes the attributes of the App Pack. The App Pack is distributed and installed on the cloud and on the device on a HAP-by-HAP basis. + +- The HAP file includes folders such as **ets**, **libs**, and **resources** and files such as **resources.index**, **module.json**, and **pack.info**. + - The **ets** folder stores bytecode files generated after application code build. + - The **libs** folder stores library files, which are .so binary files that contain third-party code on which the OpenHarmony application depends. + - The **resources** folder stores resource files (such as strings and images) of the application. + - The **resources.index** file provides a resource index table, which is generated when the application project is built in DevEco Studio. + - The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md). + - The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle. + + **Figure 2** Application package structure in stage model + + ![app-pack-stage](figures/app-pack-stage.png) \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-state-mgmt-application-level.md b/en/application-dev/quick-start/arkts-state-mgmt-application-level.md index 145827cd820399e5078b7e395b3c23b3719e1a03..8e1bfd1a19ae568b5db641fb83b1b37e49eeb9c5 100644 --- a/en/application-dev/quick-start/arkts-state-mgmt-application-level.md +++ b/en/application-dev/quick-start/arkts-state-mgmt-application-level.md @@ -60,26 +60,15 @@ struct ComponentA { this.label = (this.languageCode === 'en') ? 'Number' : 'Count' }) } - .margin({ bottom: 50 }) + .margin({ top: 50, bottom: 50 }) Row() { Button (`Change @StorageLink decorated variable: ${this.varA}`).height(40).fontSize(14) .onClick(() => { this.varA++ }) - }.margin({ bottom: 50 }) - - Row() { - Button (`Change @StorageProp decorated variable: ${this.languageCode}`).height(40).fontSize(14) - .onClick(() => { - if (this.languageCode === 'zh') { - this.languageCode = 'en' - } else { - this.languageCode = 'zh' - } - }) } - } + }.width('100%') } } ``` @@ -110,27 +99,26 @@ One-way data binding can be established between a component and the **LocalStora > **NOTE** > -> If a **LocalStorage** instance has initial values assigned when being created, these values will be used for the **@LocalStorageLink** and **@LocalStorageProp** decorated state variables in the component. Otherwise, the initial values assigned for **@LocalStorageLink** and **@LocalStorageProp** will be used instead. +> If a **LocalStorage** instance does not have an initial value assigned when being created, it can use the initial value defined by **@LocalStorageLink** or **@LocalStorageProp** in the component. ### Example 1: Creating a LocalStorage Instance in an Ability The **LocalStorage** is loaded through the **loadContent** API. For details, see [loadContent](../reference/apis/js-apis-window.md#loadcontent9-1). ```ts -// MainAbility.ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { storage: LocalStorage onCreate() { this.storage = new LocalStorage() this.storage.setOrCreate('storageSimpleProp', 121) - console.info('[Demo MainAbility onCreate]') + console.info('[Demo EntryAbility onCreate]') } onDestroy() { - console.info('[Demo MainAbility onDestroy]') + console.info('[Demo EntryAbility onDestroy]') } onWindowStageCreate(windowStage) { @@ -139,15 +127,15 @@ export default class MainAbility extends Ability { } onWindowStageDestroy() { - console.info('[Demo] MainAbility onWindowStageDestroy') + console.info('[Demo] EntryAbility onWindowStageDestroy') } onForeground() { - console.info('[Demo] MainAbility onForeground') + console.info('[Demo] EntryAbility onForeground') } onBackground() { - console.info('[Demo] MainAbility onBackground') + console.info('[Demo] EntryAbility onBackground') } } ``` diff --git a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md index d3f1002dca22fe4522134d662d4c640742d86952..2eae06eca22030673ef35bcf756279444fcd9c60 100644 --- a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md +++ b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md @@ -15,8 +15,8 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c | @Link | Primitive data types, classes, and arrays | This decorator is used to establish two-way data binding between the parent and child components. The internal state data of the parent component is used as the data source. Any changes made to one component will be reflected to the other.| | @Observed | Class | This decorator is used to indicate that the data changes in the class will be managed by the UI page. | | @ObjectLink | Objects of **@Observed** decorated classes| When the decorated state variable is modified, the parent and sibling components that have the state variable will be notified for UI re-rendering.| -| @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.| | @Provide | Primitive data types, classes, and arrays | As the data provider, **@Provide** can update the data of child nodes and trigger page re-rendering.| +| @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.| ## State Management with Application-level Variables @@ -25,5 +25,8 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c - **@StorageLink**: works in a way similar to that of **@Consume**. The difference is that the target object is obtained from the **AppStorage** based on the given name. **@StorageLink** establishes two-way binding between the decorated UI component and **AppStorage** to synchronize data. - **@StorageProp**: synchronizes UI component attributes with the **AppStorage** unidirectionally. That is, the value change in the **AppStorage** will trigger an update of the corresponding UI component, but the change of the UI component will not cause an update of the attribute value in the **AppStorage**. - Service logic implementation API: adds, reads, modifies, or deletes the state data of applications. The changes made by this API will be synchronized to the UI component for UI update. +- **LocalStorage**: provides ability-specific storage. +- **@LocalStorageLink**: establishes two-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. +- **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. - **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key. - **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started. diff --git a/en/application-dev/quick-start/arkts-state-mgmt-page-level.md b/en/application-dev/quick-start/arkts-state-mgmt-page-level.md index accda367a04ab0c77bdce7557bf47cc73f48c8a3..19326001c088a85dee94f3beaff4676db604c4f3 100644 --- a/en/application-dev/quick-start/arkts-state-mgmt-page-level.md +++ b/en/application-dev/quick-start/arkts-state-mgmt-page-level.md @@ -82,18 +82,22 @@ struct MyComponent { ## @Prop -**@Prop** and **@State** have the same semantics but different initialization modes. Variables decorated by **@Prop** must be initialized using the **@State** decorated variable provided by their parent components. The **@Prop** decorated variable can be modified in the component, but the modification is not updated to the parent component; that is, **@Prop** uses one-way data binding. +**@Prop** and **@State** have the same semantics but different initialization modes. A **@Prop** decorated variable in a component must be initialized using the **@State** decorated variable in its parent component. The **@Prop** decorated variable can be modified in the component, but the modification is not updated to the parent component; the modification to the **@State** decorated variable is synchronized to the **@Prop** decorated variable. That is, **@Prop** establishes one-way data binding. The **@Prop** decorated state variable has the following features: - Support for simple types: The number, string, and boolean types are supported. - Private: Data is accessed only within the component. - Support for multiple instances: A component can have multiple attributes decorated by **@Prop**. -- Support for initialization with a value passed to the @Prop decorated variable: When a new instance of the component is created, all **@Prop** decorated variables must be initialized. Initialization inside the component is not supported. +- Support for initialization with a value passed to the @Prop decorated variable: When a new instance of the component is created, all **@Prop** variables must be initialized. Initialization inside the component is not supported. + +> **NOTE** +> +> A **@Prop** decorated variable cannot be initialized inside the component. **Example** -In the preceding example, when the user presses **+1** or **-1**, the status of the parent component changes and the **build** method is executed again. In this case, a new **CountDownComponent** instance is created. The **countDownStartValue** attribute of the parent component is used to initialize the **@Prop** decorated variable of the child component. When the **count - costOfOneAttempt** button of the child component is touched, the value of the **@Prop** decorated variable **count** is changed. As a result, the **CountDownComponent** is rendered again. However, the change of the **count** value does not affect the **countDownStartValue** value of the parent component. +In the following example, when the user presses **+1** or **-1**, the status of the parent component changes and the **build** method is executed again. In this case, a new **CountDownComponent** instance is created. The **countDownStartValue** attribute of the parent component is used to initialize the **@Prop** decorated variable of the child component. When the **count - costOfOneAttempt** button of the child component is touched, the value of the **@Prop** decorated variable **count** is changed. As a result, the **CountDownComponent** is rendered again. However, the change of the **count** value does not affect the **countDownStartValue** value of the parent component. ```ts // xxx.ets @@ -152,13 +156,13 @@ Two-way binding can be established between the **@Link** decorated variable and - Support for multiple types: The **@Link** decorated variables support the data types the same as the **@State** decorated variables; that is, the value can be of the following types: class, number, string, boolean, or arrays of these types. - Private: Data is accessed only within the component. -- Single data source: The variable of the parent component used for initializing the **@Link** decorated variable must be a **@State** decorated variable. +- Single data source: The variable used to initialize the **@Link** decorated variable in a component must be a state variable defined in the parent component. - **Two-way binding**: When a child component changes the **@Link** decorated variable, the **@State** decorated variable of its parent component is also changed. - Support for initialization with the variable reference passed to the @Link decorated variable: When creating an instance of the component, you must use the naming parameter to initialize all **@Link** decorated variables. **@Link** decorated variables can be initialized by using the reference of the **@State** or **@Link** decorated variable. Wherein, the **@State** decorated variables can be referenced using the **'$'** operator. > **NOTE** > -> **@Link** decorated variables cannot be initialized within the component. +> A **@Link** decorated variable cannot be initialized inside the component. **Simple Type Example** @@ -391,13 +395,13 @@ struct ViewB { ``` -## @Consume and @Provide +## @Provide and @Consume As the data provider, **@Provide** can update the data of child nodes and trigger page rendering. After **@Consume** detects that the **@Provide** decorated variable is updated, it will initiate re-rendering of the current custom component. > **NOTE** > -> To avoid infinite loops caused by circular reference, exercise caution when using **@Provide** and **@Consume**. +> When using **@Provide** and **@Consume**, avoid circular reference that may lead to infinite loops. ### @Provide diff --git a/en/application-dev/quick-start/deviceconfig-structure.md b/en/application-dev/quick-start/deviceconfig-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..7386e27ea69a33efc2e7bca6dfcb2413e3479799 --- /dev/null +++ b/en/application-dev/quick-start/deviceconfig-structure.md @@ -0,0 +1,72 @@ +# Internal Structure of deviceConfig Tag + + +The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. + +### Table 1 Internal Structure of the deviceConfig Tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| default | Application configuration specific to the OpenHarmony device that provides full access to system capabilities.| Object| Yes (initial value: left empty)| +| tablet | Application configuration specific to tablets.| Object| Yes (initial value: left empty)| +| tv | Application configuration specific to smart TVs.| Object| Yes (initial value: left empty)| +| car | Application configuration specific to head units.| Object| Yes (initial value: left empty)| +| wearable | Application configuration specific to wearables.| Object| Yes (initial value: left empty)| + + +Table 2 describes the internal structure of the **deviceConfig** attributes. + +#### Table 2 Internal Structure of the deviceConfig Attributes + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| 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 value can contain a maximum of 31 characters.| String| Yes (initial value: left empty)| +| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application will start during the OS startup and keep alive. If the application process exits, the OS will restart it.| Boolean| Yes (initial value: **false**)| +| supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.| Boolean| Yes (initial value: **false**)| +| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)| +| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)| + +#### Table 3 Internal Structure of the network Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.
**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)| +| securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)| + +#### Table 4 Internal Structure of the securityConfig Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| + +#### Table 5 Internal Structure of the domainSettings Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)| +| domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)| + +### Example of the deviceConfig Tag + +```json +"deviceConfig": { + "default": { + "process": "com.example.test.example", + "supportBackup": false, + "network": { + "cleartextTraffic": true, + "securityConfig": { + "domainSettings": { + "cleartextPermitted": true, + "domains": [ + { + "subdomains": true, + "name": "example.ohos.com" + } + ] + } + } + } + } +} +``` diff --git a/en/application-dev/quick-start/figures/ability-and-module.png b/en/application-dev/quick-start/figures/ability-and-module.png new file mode 100644 index 0000000000000000000000000000000000000000..8910b0f30e8fc6808498155263939dbcb1a21336 Binary files /dev/null and b/en/application-dev/quick-start/figures/ability-and-module.png differ diff --git a/en/application-dev/quick-start/figures/app-pack-fa.png b/en/application-dev/quick-start/figures/app-pack-fa.png new file mode 100644 index 0000000000000000000000000000000000000000..51c78e2625228cfbce44d694a0eefae2b0f22782 Binary files /dev/null and b/en/application-dev/quick-start/figures/app-pack-fa.png differ diff --git a/en/application-dev/quick-start/figures/app-pack-stage.png b/en/application-dev/quick-start/figures/app-pack-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..355681fd15a3d8365ab690002fdb9f88b35e2360 Binary files /dev/null and b/en/application-dev/quick-start/figures/app-pack-stage.png differ diff --git a/en/application-dev/quick-start/figures/appstorage.gif b/en/application-dev/quick-start/figures/appstorage.gif index c500542314c4d9182155122729e6b7b15e3abc16..cb1489a13820351450099a973f09a26ec6963c71 100644 Binary files a/en/application-dev/quick-start/figures/appstorage.gif and b/en/application-dev/quick-start/figures/appstorage.gif differ diff --git a/en/application-dev/quick-start/figures/arkts-get-started.png b/en/application-dev/quick-start/figures/arkts-get-started.png index 8858c1d09bc4624ad9ace341b8d4aff2f2c4f2fa..0a83234882aecf0c1cfe390d1b9d49bccdbd0362 100644 Binary files a/en/application-dev/quick-start/figures/arkts-get-started.png and b/en/application-dev/quick-start/figures/arkts-get-started.png differ diff --git a/en/application-dev/quick-start/figures/hap-intall-uninstall.png b/en/application-dev/quick-start/figures/hap-intall-uninstall.png new file mode 100644 index 0000000000000000000000000000000000000000..de04aa18f5053de48dd0b595c8265c781e36fee5 Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-intall-uninstall.png differ diff --git a/en/application-dev/quick-start/figures/hap-multi-view.png b/en/application-dev/quick-start/figures/hap-multi-view.png new file mode 100644 index 0000000000000000000000000000000000000000..be727ebd53ebffbd29e52b78a750462489008892 Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-multi-view.png differ diff --git a/en/application-dev/quick-start/figures/hap-release.png b/en/application-dev/quick-start/figures/hap-release.png new file mode 100644 index 0000000000000000000000000000000000000000..527cefcf7e466e105f74065c3d8b59b18802d94b Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-release.png differ diff --git a/en/application-dev/quick-start/har-structure.md b/en/application-dev/quick-start/har-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..f3b1189d37b9292f4ff4e814726c2f9a8f58c493 --- /dev/null +++ b/en/application-dev/quick-start/har-structure.md @@ -0,0 +1,10 @@ +# HAR File Structure + + +The Harmony Ability Resources (HAR) file enables code to be shared among multiple modules or projects. Unlike a Harmony Ability Package (HAP) file, a HAR file cannot be independently installed on a device. Instead, it can only be referenced as the dependency of an application module. + + +A HAR file is the build product of a [module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) of the Library type in a DevEco Studio project. + + +The HAR file reuses the standard [npm package](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434) release mode and is packed into a .tar package with the file name extension .tgz. The packed HAR file contains the source code, resource files, and the **module.json** file (in stage model) or **config.json** file (in FA model). diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md new file mode 100644 index 0000000000000000000000000000000000000000..f06e9f911b9d1cb949097e23d24163f7afaa09c2 --- /dev/null +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -0,0 +1,637 @@ +# module.json5 Configuration File + + +This document gives an overview of the **module.json5** configuration file. To start with, let's go through an example of what this file contains. + +```json +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "virtualMachine": "ark", + "metadata": [ + { + "name": "string", + "value": "string", + "resource": "$profile:distrofilter_config" + } + ], + "abilities": [ + { + "name": "EntryAbility", + "srcEntrance": "./ets/entryability/EntryAbility.ts", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + { + "name": "ohos.abilitydemo.permission.PROVIDER", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "FormAbility" + ], + "when": "inuse" + } + } + ] + } +} +``` + + +As shown above, the **module.json5** file contains several tags. + + + **Table 1** Tags in the module.json5 file + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application.| String| No| +| type | Type of the module. The value can be **entry** or **feature**.
- **entry**: main module of the application.
- **feature**: dynamic feature module of the application.| String| No| +| srcEntrance | Code path corresponding to the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)| +| description | Description of the module. The value is a string with a maximum of 255 bytes or a string resource index. | String| Yes (initial value: left empty)| +| process | Process name of the current module. The value is a string with a maximum of 31 bytes. If **process** is configured under **HAP**, all UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility components of the application run in the specified process.
**NOTE**
This tag applies only to system applications and does not take effect for third-party applications.| String| Yes (initial value: value of **bundleName** under **app** in the **app.json5** file)| +| mainElement | Name of the entry UIAbility or ExtensionAbility of the module. The value contains a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| [deviceTypes](#devicetypes) | Type of the device on which the module can run.| String array| No (can be left empty)| +| deliveryWithInstall | Whether the HAP file of the module will be installed when the user installs the application.
- **true**: The HAP file will be installed when the user installs the application.
- **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| +| installationFree | Whether the module supports the installation-free feature.
- **true**: The module supports the installation-free feature and meets installation-free constraints.
- **false**: The module does not support the installation-free feature.
**NOTE**
- If this tag is set to **true** for an entry-type module, it must also be set to **true** for feature-type modules of the same application.
- If this tag is set to **false** for an entry-type module, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| +| virtualMachine | Type of the target virtual machine (VM) where the module runs. It is used for cloud distribution, such as distribution by the application market and distribution center.
If the target VM type is ArkTS engine, the value is **ark**+*version number*. | String| Yes (initial value: automatically inserted when DevEco Studio builds the HAP file)| +| uiSyntax (deprecated)| Syntax type of the JS component defined by the module syntax. This tag is deprecated since API version 9.
- **"hml"**: The JS component is developed using HML, CSS, or JS.
- **"ets"**: The JS component is developed using ArkTS. | String| Yes (initial value: **"hml"**)| +| [pages](#pages)| Profile that represents information about each page in the JS component. The value can contain a maximum of 255 bytes.| String| No in the UIAbility scenario| +| [metadata](#metadata)| Custom metadata of the module. The setting is valid only for the current module, UIAbility, or ExtensionAbility.| Object array| Yes (initial value: left empty)| +| [abilities](#abilities) | UIAbility configuration of the module, which is valid only for the current UIAbility component.| Object| Yes (initial value: left empty)| +| [extensionAbilities](#extensionabilities) | ExtensionAbility configuration of the module, which is valid only for the current ExtensionAbility component.| Object| Yes (initial value: left empty)| +| [requestPermissions](#requestpermissions) | A set of permissions that the application needs to request from the system for running correctly.| Object| Yes (initial value: left empty)| +| [testRunner](#testrunner) | Test runner configuration of the module.| Object| Yes (initial value: left empty)| + + +## deviceTypes + + **Table 2** deviceTypes + +| Device Type| Value| Description| +| -------- | -------- | -------- | +| Tablet| tablet | - | +| Smart TV| tv | - | +| Smart watch| wearable | Watch that provides call features.| +| Head unit| car | - | +| Default device| default | OpenHarmony device that provides full access to system capabilities.| + +Example of the **deviceTypes** structure: + + +```json +{ + "module": { + "name": "myHapName", + "type": "feature", + "deviceTypes" : [ + "tablet" + ] + } +} +``` + + +## pages + +The **pages** tag is a profile that represents information about specified pages. + + +```json +{ + "module": { + // ... + "pages": "$profile:main_pages", // Configured through the resource file in the profile + } +} +``` + +Define the **main_pages.json** file under **resources/base/profile** in the development view. The base name of the file (**main_pages** in this example) can be customized, but must be consistent with the information specified by the **pages** tag. The file lists the page information of the current application. + + +```json +{ + "src": [ + "pages/index/mainPage", + "pages/second/payment", + "pages/third/shopping_cart", + "pages/four/owner" + ] +} +``` + + +## metadata + +The **metadata** tag represents the custom metadata of the HAP file. The tag value is an array and contains three subtags: **name**, **value**, and **resource**. + + **Table 3** metadata + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| resource | Custom data format. The value is a resource index. It contains a maximum of 255 bytes. | String| Yes (initial value: left empty)| + + +```json +{ + "module": { + "metadata": [{ + "name": "module_metadata", + "value": "a test demo for module metadata", + "resource": "$profile:shortcuts_config", + }], + + "abilities": [{ + "metadata": [{ + "name": "ability_metadata", + "value": "a test demo for ability", + "resource": "$profile:config_file" + }, + { + "name": "ability_metadata_2", + "value": "a string test", + "resource": "$profile:config_file" + }], + }], + + "extensionAbilities": [{ + "metadata": [{ + "name": "extensionAbility_metadata", + "value": "a test for extensionAbility", + "resource": "$profile:config_file" + }, + { + "name": "extensionAbility_metadata_2", + "value": "a string test", + "resource": "$profile:config_file" + }], + }] + } +} +``` + + +## abilities + +The **abilities** tag describes the UIAbility configuration of the component, which is valid only for the current UIAbility component. The tag value is an array. + + **Table 4** abilities + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the UIAbility component, which must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String| No| +| srcEntrance | Code path of the entry UIAbility component. The value is a string with a maximum of 127 bytes.| String| No| +| [launchType](../application-models/uiability-launch-type.md) | Launch type of the UIAbility component. The options are as follows:
- **standard**: A new UIAbility instance is created each time the UIAbility component is started.
- **singleton**: A new UIAbility instance is created only when the UIAbility component is started for the first time.
- **specified**: You can determine whether to create a new UIAbility instance when the application is running.| String| Yes (initial value: **"singleton"**)| +| description | Description of the UIAbility component. The value is a string with a maximum of 255 bytes or a resource index to the description in multiple languages. | String| Yes (initial value: left empty)| +| icon | Icon of the UIAbility component. The value is an icon resource index.
If **UIAbility** is set to **MainElement** of the current module, this attribute is mandatory. | String| Yes (initial value: left empty) | +| label | Name of the UIAbility component displayed to users. The value is a string resource index.
If **UIAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application. | String| No| +| permissions | Permissions required for another application to access the UIAbility component.
The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)| +| [metadata](#metadata)| Metadata information of the UIAbility component.| Object array| Yes (initial value: left empty)| +| visible | Whether the UIAbility component can be called by other applications.
- **true**: The UIAbility component can be called by other applications.
- **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| +| continuable | Whether the UIAbility component can be [migrated](../application-models/hop-cross-device-migration.md).
- **true**: The UIAbility component can be migrated.
- **false**: The UIAbility component cannot be migrated.| Boolean| Yes (initial value: **false**)| +| [skills](#skills) | Feature set of [wants](../application-models/want-overview.md) that can be received by the current UIAbility or ExtensionAbility component.
Configuring rule:
- For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an OpenHarmony application. (A **skills** attribute with the entry capability is the one that has **action.system.home** and **entity.system.home** configured.)
- For HAPs of the feature type, you can configure **skills** attributes with the entry capability for an OpenHarmony application, but not for an OpenHarmony service.| Object array| Yes (initial value: left empty)| +| backgroundModes | Continuous tasks of the UIAbility component.
Continuous tasks are classified into the following types:
- **dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.
- **audioPlayback**: audio playback service.
- **audioRecording**: audio recording service.
- **location**: location and navigation services.
- **bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables).
- **multiDeviceConnection**: multi-device interconnection service.
- **wifiInteraction**: Wi-Fi scanning, connection, and transmission services (as used in the Multi-screen Collaboration and clone features)
- **voip**: voice/video call and VoIP services.
- **taskKeeping**: computing service.| String array| Yes (initial value: left empty)| +| startWindowIcon | Index to the icon file of the UIAbility component startup page. Example: **$media:icon**.
The value is a string with a maximum of 255 bytes.| String| No| +| startWindowBackground | Index to the background color resource file of the UIAbility component startup page. Example: **$color:red**.
The value is a string with a maximum of 255 bytes.| String| No| +| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the UIAbility component is destroyed.
- **true**: Remove the relevant task from the task list after the UIAbility component is destroyed.
- **false**: Do not remove the relevant task from the task list after the UIAbility component is destroyed.| Boolean| Yes (initial value: **false**)| +| orientation | Orientation of the UIAbility component when it is started. The options are as follows:
- **unspecified**: automatically determined by the system.
- **landscape**: landscape mode.
- **portrait**: portrait mode.
- **landscape_inverted**: inverted landscape mode.
- **portrait_inverted**: inverted portrait mode.
- **auto_rotation**: determined by the sensor.
- **auto_rotation_landscape**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes.
- **auto_rotation_portrait**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes.
- **auto_rotation_restricted**: determined by the sensor when the sensor switch is enabled.
- **auto_rotation_landscape_restricted**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes, when the sensor switch is enabled.
- **auto_rotation_portrait_restricted**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes, when the sensor switch is enabled.
- **locked**: auto rotation disabled.| String| Yes (initial value: **"unspecified"**)| +| supportWindowMode | Window mode supported by the UIAbility component. The options are as follows:
- **fullscreen**: full-screen mode.
- **split**: split-screen mode.
- **floating**: floating window mode.| String array| Yes (initial value:
["fullscreen", "split", "floating"])| +| priority | Priority of the UIAbility component. This attribute applies only to system applications and does not take effect for third-party applications. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.| Number| Yes (initial value: **0**)| +| maxWindowRatio | Maximum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: maximum aspect ratio supported by the platform)| +| minWindowRatio | Minimum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: minimum aspect ratio supported by the platform)| +| maxWindowWidth | Maximum window width supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: maximum window width supported by the platform)| +| minWindowWidth | Minimum window width supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: minimum window width supported by the platform)| +| maxWindowHeight | Maximum window height supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: maximum window height supported by the platform)| +| minWindowHeight | Minimum window height supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: minimum window height supported by the platform)| +| excludeFromMissions | Whether the UIAbility component is displayed in the recent task list.
- **true**: displayed in the recent task list.
- **false**: not displayed in the recent task list.
**NOTE**
This tag applies only to system applications and does not take effect for third-party applications.| Boolean| Yes (initial value: **false**)| + +Example of the **abilities** structure: + + +```json +{ + "abilities": [{ + "name": "EntryAbility", + "srcEntrance": "./ets/entryability/EntryAbility.ts", + "launchType":"standard", + "description": "$string:description_main_ability", + "icon": "$media:icon", + "label": "Login", + "permissions": [], + "metadata": [], + "visible": true, + "continuable": true, + "skills": [{ + "actions": ["action.system.home"], + "entities": ["entity.system.home"], + "uris": [] + }], + "backgroundModes": [ + "dataTransfer", + "audioPlayback", + "audioRecording", + "location", + "bluetoothInteraction", + "multiDeviceConnection", + "wifiInteraction", + "voip", + "taskKeeping" + ], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true, + "orientation": " ", + "supportWindowMode": ["fullscreen", "split", "floating"], + "maxWindowRatio": 3.5, + "minWindowRatio": 0.5, + "maxWindowWidth": 2560, + "minWindowWidth": 1400, + "maxWindowHeight": 300, + "minWindowHeight": 200, + "excludeFromMissions": false + }] +} +``` + + +## skills + +The **skills** tag represents the feature set of [wants](../application-models/want-overview.md) that can be received by the UIAbility or ExtensionAbility component. + + **Table 5** skills + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| actions | [Actions](../application-models/actions-entities.md) of wants that can be received, which can be predefined or customized.| String array| Yes (initial value: left empty)| +| entities | [Entities](../application-models/actions-entities.md) of wants that can be received.| String array| Yes (initial value: left empty)| +|uris | URIs that match the wants.| Object array| Yes (initial value: left empty)| + + **Table 6** uris + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| scheme | Scheme of the URI, such as HTTP, HTTPS, file, and FTP.| String| Yes when only **type** is set in **uris** (initial value: left empty) | +| host | Host address of the URI. This attribute is valid only when **schema** is set. Common methods:
- domain name, for example, **example.com**.
- IP address, for example, **10.10.10.1**.| String| Yes (initial value: left empty)| +| port | Port number of the URI. For example, the default HTTP port number is 80, the default HTTPS port number is 443, and the default FTP port number is 21. This attribute is valid only when both **scheme** and **host** are set.| String| Yes (initial value: left empty)| +| path \| pathStartWith \| pathRegex | Path of the URI. **path**, **pathStartWith**, and **pathRegex** represent different matching modes between the paths in the URI and the want. Set any one of them as needed. **path** indicates full matching, **pathStartWith** indicates prefix matching, and **pathRegex** indicates regular expression matching. This attribute is valid only when both **scheme** and **host** are set.| String| Yes (initial value: left empty)| +| type | Data type that matches the want. The value compiles with the [Multipurpose Internet Mail Extensions (MIME)](https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com %E3%80%82) type specification. This attribute can be configured together with **scheme** or be configured separately. | String| Yes (initial value: left empty)| + +Example of the **skills** structure: + + +```json +{ + "abilities": [ + { + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ], + "uris": [ + { + "scheme":"http", + "host":"example.com", + "port":"80", + "path":"path", + "type": "text/*" + } + ] + } + ] + } + ] +} +``` + + +## extensionAbilities + +The **extensionAbilities** tag represents the configuration of extensionAbilities, which is valid only for the current extensionAbility. + + **Table 7** extensionAbilities + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the ExtensionAbility component. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String| No| +| srcEntrance | Code path corresponding to the ExtensionAbility component. The value is a string with a maximum of 127 bytes.| String| No| +| description | Description of the ExtensionAbility component. The value is a string with a maximum of 255 bytes or a resource index to the description. | String| Yes (initial value: left empty)| +| icon | Icon of the ExtensionAbility component. The value is the index to an icon resource file. If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| Yes (initial value: left empty)| +| label | Name of the ExtensionAbility component displayed to users. The value is the index to a string resource.
**NOTE**
If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| No| +| type | Type of the ExtensionAbility component. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a Work Scheduler task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **dataShare**: ExtensionAbility for data sharing.
- **fileShare**: ExtensionAbility for file sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
**NOTE**
The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications. | String| No| +| permissions | Permissions required for another application to access the ExtensionAbility component.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)| +| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.
**NOTE**
This attribute is mandatory when **type** of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| +|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.
Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **action.system.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.
**NOTE**
The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application, but not for an OpenHarmony service. | Array| Yes (initial value: left empty)| +| [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| +| visible | Whether the ExtensionAbility component can be called by other applications.
- **true**: The ExtensionAbility component can be called by other applications.
- **false**: The ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| + +Example of the **extensionAbilities** structure: + + +```json +{ + "extensionAbilities": [ + { + "name": "FormName", + "srcEntrance": "./form/MyForm.ts", + "icon": "$media:icon", + "label" : "$string:extension_name", + "description": "$string:form_description", + "type": "form", + "permissions": ["ohos.abilitydemo.permission.PROVIDER"], + "readPermission": "", + "writePermission": "", + "visible": true, + "uri":"scheme://authority/path/query", + "skills": [{ + "actions": [], + "entities": [], + "uris": [] + }], + "metadata": [ + { + "name": "ohos.extension.form", + "resource": "$profile:form_config", + } + ] + } + ] +} +``` + + +## requestPermissions + +The **requestPermissions** tage represents a set of permissions that the application needs to request from the system for running correctly. + + **Table 8** requestPermissions + +| Name| Description| Data Type| Value Range| Default Value| +| -------- | -------- | -------- | -------- | -------- | +| name | Permission name. This attribute is mandatory.| String| Custom| –| +| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**.
**NOTE**
If the permission to request is **user_grant**, this attribute is required for the application to be released to the application market, and multi-language adaptation is required. | String| Resource reference of the string type in $string: \*\*\* format| A null value| +| usedScene | Scene under which the permission is used. It consists of the **abilities** and **when** sub-attributes. Multiple abilities can be configured.
**NOTE**
This attribute is optional by default. If the permission to request is **user_grant**, the **abilities** sub-attribute is mandatory and **when** is optional. | **abilities**: string array
**when**: string| **abilities**: array of names of UIAbility or ExtensionAbility components
**when**: **inuse** or **always**| **abilities**: null
**when**: null| + +Example of the **requestPermissions** structure: + + +```json +{ + "module" : { + "requestPermissions": [ + { + "name": "ohos.abilitydemo.permission.PROVIDER", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "EntryFormAbility" + ], + "when": "inuse" + } + } + ] + } +} +``` + + +## shortcuts + +The **shortcuts** tag provides the shortcut information of an application. The value is an array of up to four shortcuts. It consists of four sub-attributes: **shortcutId**, **label**, **icon**, and **wants**. + +The **shortcut** information is identified in **metadata**, where: + +- **name** indicates the name of the shortcut, identified by **ohos.ability.shortcuts**. + +- **resource** indicates where the resources of the shortcut are stored. + +| Attribute| Description| Data Type | Default Value| +| -------- | -------- | -------- | -------- | +| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes.| String| No| +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the label, with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| icon | Icon of the shortcut. The value is an icon resource index. | String| Yes (initial value: left empty)| +| [wants](../application-models/want-overview.md) | Wants to which the shortcut points. Each want consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut. The value is a string.
**abilityName**: target component name of the shortcut. The value is a string.| Object| Yes (initial value: left empty)| + + +1. Configure the **shortcuts_config.json** file in **/resource/base/profile/**. + + ```json + { + "shortcuts": [ + { + "shortcutId": "id_test1", + "label": "$string:shortcut", + "icon": "$media:aa_icon", + "wants": [ + { + "bundleName": "com.ohos.hello", + "abilityName": "EntryAbility" + } + ] + } + ] + } + ``` + +2. In the **abilities** tag of the **module.json5** file, configure the **metadata** tag for the UIAbility component to which a shortcut needs to be added so that the shortcut configuration file takes effect for the UIAbility. + + ```json + { + "module": { + // ... + "abilities": [ + { + "name": "EntryAbility", + "srcEntrance": "./ets/entryability/EntryAbility.ts", + // ... + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "metadata": [ + { + "name": "ohos.ability.shortcuts", + "resource": "$profile:shortcuts_config" + } + ] + } + ] + } + } + ``` + + +## distroFilter + +The **distroFilter** tag defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover five factors: API version, screen shape, screen size, screen resolution, and country code. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these five factors. This tag must be configured in the **/resource/profile resource** directory. + + **Table 9** distroFilter + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| apiVersion | Supported API versions.| Object array| Yes (initial value: left empty)| +| screenShape | Supported screen shapes.| Object array| Yes (initial value: left empty)| +| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)| +| screenDensity | Pixel density of the screen, in dots per inch (DPI). This attribute is optional. The options are as follows:
- **sdpi**: small-scale DPI. This value is applicable to devices with a DPI range of (0, 120].
- **mdpi**: medium-scale DPI. This value is applicable to devices with a DPI range of (120, 160].
- **ldpi**: large-scale DPI. This value is applicable to devices with a DPI range of (160, 240].
- **xldpi**: extra-large-scale DPI. This value is applicable to devices with a DPI range of (240, 320].
- **xxldpi**: extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (320, 480].
- **xxxldpi**: extra-extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (480, 640]. | Object array| Yes (initial value: left empty)| +| countryCode | Code of the country or region to which the application is to be distributed. The value is subject to the [ISO-3166-1](https://developer.harmonyos.com/en/docs/documentation/doc-guides/basic-resource-file-categories-0000001052066099) standard. Enumerated definitions of multiple countries and regions are supported.| Object array| Yes (initial value: left empty)| + + **Table 10** apiVersion + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | API versions, for example, 4, 5, or 6. Example: If an application comes with two versions developed using API version 5 and API version 6 for the same device model, two installation packages of the entry type can be released for the application.| Array| No| + + **Table 11** screenShape + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Screen shapes. The value can be **circle**, **rect**, or both. Example: Different HAP files can be provided for a smart watch with a circular face and that with a rectangular face.| String array| No| + + **Table 12** screenWindow + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Screen width and height, in pixels. The value an array of supported width and height pairs, each in the "width * height" format, for example, **"454 * 454"**.| String array| No| + + **Table 13** screenDensity + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Pixel density of the screen, in DPI.| String array| No| + + **Table 14** countryCode + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Code of the country or region to which the application is to be distributed.| String array| No| + +Configure the **distro_filter_config.json** file (this file name is customizable) in **resources/base/profile** under the development view. + + +```json +{ + "distroFilter": { + "apiVersion": { + "policy": "include", + "value": [ + 3, + 4 + ] + }, + "screenShape": { + "policy": "include", + "value": [ + "circle", + "rect" + ] + }, + "screenWindow": { + "policy": "include", + "value": [ + "454*454", + "466*466" + ] + }, + "screenDensity": { + "policy": "exclude", + "value": [ + "ldpi", + "xldpi" + ] + }, + "countryCode": {// Distribution to the Chinese mainland and Hong Kong, China is supported. + "policy": "include", + "value": [ + "CN", + "HK" + ] + } + } +} +``` + +Configure **metadata** in the **module** tag in the **module.json5** file. + + +```json +{ + "module": { + // ... + "metadata": [ + { + "name": "ohos.module.distro", + "resource": "$profile:distro_filter_config", + } + ] + } +} +``` + + +## testRunner + +The **testRunner** tag represents the supported test runner. + + **Table 15** testRunner + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the test runner object. The value is a string with a maximum of 255 bytes.| String| No| +| srcPath | Code path of the test runner. The value is a string with a maximum of 255 bytes. | String| No| + +Example of the / structure: + + +```json +{ + "module": { + // ... + "testRunner": { + "name": "myTestRunnerName", + "srcPath": "etc/test/TestRunner.ts" + } + } +} +``` diff --git a/en/application-dev/quick-start/module-structure.md b/en/application-dev/quick-start/module-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..a8df69c1846a1ff6f7647aff4490da5d4990d431 --- /dev/null +++ b/en/application-dev/quick-start/module-structure.md @@ -0,0 +1,640 @@ +# Internal Structure of the module Tag + + +The **module** tag contains the HAP configuration. + +### Table 1 Internal Structure of the module Tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| mainAbility | Ability whose icon is displayed in the Service Center. When the resident process is started, the **mainAbility** is started.| String| Yes (initial value: left empty)| +| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. | String| No| +| name | Class name of the HAP file. The value is a string with a maximum of 255 bytes, in the reverse domain name notation. The prefix must be the same as the **package** value specified for this module. Alternatively, the value can start with a period (.) followed by the class name.| String| Yes (initial value: left empty)| +| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description.| String| Yes (initial value: left empty)| +| supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty)| +|deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No| +|distro | Distribution description of the HAP file.| Object| No| +|metaData | Metadata of the HAP file.| Object| Yes (initial value: left empty)| +| abilities | All abilities in the current module. The value is an array of objects, each of which represents an ability.| Object array| Yes (initial value: left empty)| +| js | A set of JS modules developed using ArkUI. The value is an array of objects, each of which represents a JS module.| Object array| Yes (initial value: left empty)| +| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)| +| reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)| +| colorMode | Color mode of the application. The options are as follows:
- **dark**: Resources applicable for the dark mode are used.
- **light**: Resources applicable for the light mode are used.
- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)| +| distroFilter | Distribution rules of the application. This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. | Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| +|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the subscribed common events. When a subscribed event is sent, the static subscriber is started. Unlike the common dynamic subscriber, the static subscriber does not need to actively call the common event subscription API in the service code, and may not be started when the common event is released. In constrast, the dynamic subscriber actively calls the common event subscription API and therefore requires the application to stay active.| Object array| Yes (initial value: left empty)| +| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)| +|testRunner | Test runner configuration.| Object| Yes (initial value: left empty)| + +Example of the **module** tag structure: + +```json +{ + "module": { + "mainAbility": ".MainAbility", + "deviceType": [ + "default", + "tablet" + ], + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "MainAbility", + "name": ".MainAbility", + "srcLanguage": "ets", + "icon": "$media:icon", + "description": "$string:MainAbility_desc", + "formsEnabled": false, + "label": "$string:MainAbility_label", + "type": "page", + "launchType": "standard" + } + ], + "distro": { + "moduleType": "entry", + "installationFree": false, + "deliveryWithInstall": true, + "moduleName": "entry" + }, + "package": "com.example.entry", + "srcPath": "", + "name": ".entry", + "js": [ + { + "mode": { + "syntax": "ets", + "type": "pageAbility" + }, + "pages": [ + "pages/Index" + ], + "name": ".MainAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} +``` + +#### Table 2 Internal structure of the distro attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| moduleName | Name of the HAP file. The maximum length is 31 bytes.| String| No| +| moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No| +| installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| +| deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| + + +Example of the **distro** attribute structure: + +```json +"distro": { + "moduleName": "ohos_entry", + "moduleType": "entry", + "installationFree": true, + "deliveryWithInstall": true +} +``` + +#### Table 3 Internal structure of the metadata attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| parameters | Metadata of the parameters to be passed for calling the ability. The metadata of each parameter consists of the **description**, **name**, and **type** sub-attributes.| Object array| Yes (initial value: left empty)| +| results | Metadata of the ability return value. The metadata of each return value consists of the **description**, **name**, and **type** sub-attributes.| Object array| Yes (initial value: left empty)| +| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| Object array| Yes (initial value: left empty)| + +#### Table 4 Internal structure of the parameters attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| description | Description of the parameter. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| name | Name of the parameter passed for calling the ability. The value can contain a maximum of 255 bytes.| String| No| +| type | Type of the parameter passed for calling the ability, for example, **Integer**.| String| No| + +#### Table 5 Internal structure of the results attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| description | Description of the return value. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| name | Name of the return value. The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| type | Type of the return value, for example, **Integer**.| String| No| + +#### Table 6 Internal structure of the customizeData attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Key of the data element. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| value | Value of the data element. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| extra | Custom format of the data element. The value is a resource index that identifies the data.| String| Yes (initial value: left empty)| + + +Example of the metadata attribute: + +```json +"metaData": { + "parameters" : [{ + "name" : "a test for metadata parameter", + "type" : "Float", + // "$string:parameters_description" is a file resource index. + "description" : "$string:parameters_description" + }], + "results" : [{ + "name" : "a test for metadata result", + "type" : "Float", + "description" : "$string:results_description" + }], + "customizeData" : [{ + "name" : "a customizeData", + "value" : "string", + "extra" : "$string:customizeData_description" + }] +} +``` + +#### Table 7 Values of the deviceType attribute + +| Device Type| Value| Description| +| -------- | -------- | -------- | +| Tablet| tablet | - | +| Smart TV| tv | - | +| Smart watch| wearable | Watch that provides call features.| +| Head unit| car | - | +| Default device| default | OpenHarmony device that provides full access to system capabilities.| + +#### Table 8 Internal structure of the abilities attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| 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. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. The value can contain a maximum of 31 bytes.| String| Yes (initial value: left empty)| +| name | Ability name. The value can be a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created by default, and its configuration will be saved to the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 bytes.| String| No| +| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String| Yes (initial value: left empty)| +| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)| +| launchType | Launch type of the ability. The value can be **standard** or **singleton**.
**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)| +| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)| +| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)| +|skills | Types of the **want** that can be accepted by the ability.| Object array| Yes (initial value: left empty)| +| deviceCapability | Device capabilities required to run the ability. The value is an array of up to 512 elements, each of which contains a maximum of 64 bytes.| String array| Yes (initial value: left empty)| +| metaData | Metadata.| Object| Yes (initial value: left empty)| +| type | Ability type. The options are as follows:
**page**: FA developed using the Page template to provide the capability of interacting with users.
**service**: PA developed using the Service template to provide the capability of running tasks in the background.
**data**: PA developed using the Data template to provide unified data access for external systems.
**CA**: ability that can be started by other applications as a window.| String| No| +| orientation | Display orientations of the ability. This attribute applies only to the ability using the Page template. The options are as follows:
**unspecified**: indicates that the system automatically determines the display orientation of the ability.
**landscape**: indicates the landscape orientation.
**portrait**: indicates the portrait orientation.
**followRecent**: indicates that the orientation follows the most recent application in the stack.| String| Yes (initial value: **"unspecified"**)| +| backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This field applies only to the ability using the Service template. The options are as follows:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.
**audioPlayback**: audio playback service.
**audioRecording**: audio recording service.
**pictureInPicture**: picture in picture (PiP) and small-window video playback services.
**voip**: voice/video call and VoIP services.
**location**: location and navigation services.
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services.
**wifiInteraction**: WLAN scanning, connection, and transmission services.
**screenFetch**: screen recording and screenshot services.
**multiDeviceConnection**: multi-device interconnection service.| String array| Yes (initial value: left empty)| +| grantPermission | Whether permissions can be granted for any data in the ability.| Boolean| Yes (initial value: left empty)| +| readPermission | Permission required for reading data in the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: left empty)| +| writePermission | Permission required for writing data to the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. The options are as follows:
**mcc**: indicates that the mobile country code (MCC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MCC is updated.
**mnc**: indicates that the mobile network code (MNC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MNC is updated.
**locale**: indicates that the locale is changed. Typical scenario: The user selectes a new language for the text display of the device.
**layout**: indicates that the screen layout is changed. Typical scenario: Currently, different display forms are all in the active state.
**fontSize**: indicates that font size is changed. Typical scenario: A new global font size is set.
**orientation**: indicates that the screen orientation is changed. Typical scenario: The user rotates the device.
**density**: indicates that the display density is changed. Typical scenario: The user may specify different display ratios, or different display forms are active at the same time.
**size**: indicates that the size of the display window is changed.
**smallestSize**: indicates that the length of the shorter side of the display window is changed.
**colorMode**: indicates that the color mode is changed.| String array| Yes (initial value: left empty)| +| mission | Task stack of the ability. This attribute applies only to the ability using the Page template. By default, all abilities in an application belong to the same task stack.| String| Yes (initial value: bundle name of the application)| +| targetAbility | Target ability that this ability alias points to. This attribute applies only to the ability using the Page template. If the **targetAbility** attribute is set, only **name**, **icon**, **label**, **visible**, **permissions**, and **skills** take effect in the current ability (ability alias). Other attributes use the values of the **targetAbility** attribute. The target ability must belong to the same application as the alias and must be declared in **config.json** ahead of the alias.| String| Yes (initial value: left empty, indicating that the current ability is not an alias)| +| formsEnabled | Whether the ability can provide widgets. This attribute applies only to the ability using the Page template.
**true**: This ability can provide widgets.
**false**: This ability cannot provide widgets.| Boolean| Yes (initial value: **false**)| +| forms | Information about the widgets used by the ability. This attribute is valid only when **formsEnabled** is set to **true**.| Object array| Yes (initial value: left empty)| +| srcLanguage | Programming language of the ability, which you can specify when creating the project.| String| Yes (initial value: **"js"**)| +| srcPath | JS code path corresponding to the ability. The value can contain maximum of 127 bytes.| String| No| +| uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider.| Object| Yes (initial value: left empty)| +| startWindowIcon | Index to the icon file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$media:icon**.| String| Yes (initial value: left empty)| +| startWindowBackground | Index to the background color resource file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$color:red**.| String| Yes (initial value: left empty)| +| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. This attribute applies only to the ability using the Page template. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean| Yes (initial value: **false**)| + +#### Table 9 Internal structure of the uriPermission attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| path | Path. The value can contain maximum of 255 bytes.| String| No| +| mode | Matching mode.| String| Yes (initial value: **default**)| + + +Example of the **abilities** attribute structure: + +```json +"abilities": [ + { + "name": ".MainAbility", + "description": "test main ability", + // $media:ic_launcher is a media resource. + "icon": "$media:ic_launcher", + // $string:example is a string resource. + "label": "$string:example", + "launchType": "standard", + "orientation": "unspecified", + "permissions": [], + "visible": true, + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ], + "configChanges": [ + "locale", + "layout", + "fontSize", + "orientation" + ], + "type": "page", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true + }, + { + "name": ".PlayService", + "description": "example play ability", + "icon": "$media:ic_launcher", + "label": "$string:example", + "launchType": "standard", + "orientation": "unspecified", + "visible": false, + "skills": [ + { + "actions": [ + "action.play.music", + "action.stop.music" + ], + "entities": [ + "entity.audio" + ] + } + ], + "type": "service", + "backgroundModes": [ + "audioPlayback" + ] + }, + { + "name": ".UserADataAbility", + "type": "data", + "uri": "dataability://com.example.world.test.UserADataAbility", + "visible": true + } +] +``` + +#### Table 10 Internal structure of the skills attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)| +| entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)| +| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both.
The URI is specified by separate attributes of each part: <scheme>://<host>:<port>[<path>\|<pathStartWith>\|<pathRegex>].
**scheme** is mandatory when the specification is of the URI type and is optional when the specification is of data type only.| Object array| Yes (initial value: left empty)| + +#### Table 11 Internal structure of the uris attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| scheme | Scheme of the URI.| String| No| +| host | Host value of the URI.| String| Yes (initial value: left empty)| +| port | Port number of the URI.| String| Yes (initial value: left empty)| +| pathStartWith | **pathStartWith** value of the URI.| String| Yes (initial value: left empty)| +| path | **path** value of the URI.| String| Yes (initial value: left empty)| +| pathRegx | **pathRegx** value of the URI.| String| Yes (initial value: left empty)| +| type | **type** value of the URI. The value is a MIME type. Typical values include **"audio/aac"** and **"text/css"**.| String| Yes (initial value: left empty)| + + +Example of the **skills** attribute structure: + +```json +"skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ], + "uris": [ + { + "scheme": "http", + "host": "www.example.com", + "port": "8080", + "path": "query/student/name", + "type": "text/*" + } + ] + } +] +``` + +#### Table 12 reqPermissions attributes + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the permission to request.| String| No| +| reason | Reason for requesting the permission. Multi-language adaptation is required.| String| No if the permission to request is **user_grant**, yes in other cases (initial value: left empty)
If the permission to request is **user_grant** this attribute is required for the application to be released to the application market, and multi-language adaptation is required. | +| usedScene | Scene under which the permission is used. It consists of the **abilities** and **when** sub-attributes.
- **ability**: ability name. Multiple ability names can be configured.
- **when**: time for using the permission. The options are **inuse** and **always**.| Object| Yes (initial value: left empty)
**when**: initial value (**inuse**) allowed| + +#### Table 13 Internal structure of the usedScene attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| ability | Names of abilities that require the permission.| String array| Yes (initial value: all ability names)| +| when | Time when the permission is used.
**inuse**: The permission is required when the ability is in use.
**always**: The permission is required at all times.| Value| Yes (initial value: left empty)| + +#### Table 14 Internal structure of the js attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the JS component. The default value is **default**.| String| No| +| pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JS FA.| String array| No| +| window | Window-related configurations.| Object| Yes (initial value: see Table 15)| +| type | Type of the JS component. The options are as follows:
**normal**: indicates an application instance.
**form**: indicates a widget instance.| String| Yes (initial value: **"normal"**)| +|mode | Development mode of the JS component.| Object| Yes (initial value: left empty)| + +#### Table 15 Internal structure of the window attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number| Yes (initial value: 720px)| +| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| + +#### Table 16 Internal structure of the mode attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| type | Type of the JS component. The value can be **pageAbility** or **form**.| String| Yes (initial value: **pageAbility**)| +| syntax | Syntax type of the JS component. The value can be **"hml"** or **"ets"**.| String| Yes (initial value: **"hml"**)| + + +Example of the **js** attribute structure: + +```json +"js": [ + { + "name": "default", + "pages": [ + "pages/index/index", + "pages/detail/detail" + ], + "window": { + "designWidth": 720, + "autoDesignWidth": false + }, + "type": "form" + } +] +``` + +#### Table 17 Internal structure of the shortcuts attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes.| String| No| +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the label. The value is a string with a maximum of 63 bytes.| String| Yes (initial value: left empty)| +| icon | Icon of the shortcut. The value is a resource index to the description.| String| Yes (initial value: left empty)| +| intents | Wants to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes.| Object array| Yes (initial value: left empty)| + +#### Table 18 Internal structure of the intents attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| targetClass | Target class of the shortcut.| String| Yes (initial value: left empty)| +| targetBundle | Application bundle name for the target ability of the shortcut.| String| Yes (initial value: left empty)| + + +Example of the **shortcuts** attribute structure: + +```json +"shortcuts": [ + { + "shortcutId": "id", + // $string:shortcut is a string resource index. + "label": "$string:shortcut", + "intents": [ + { + "targetBundle": "com.example.world.test", + "targetClass": "com.example.world.test.entry.MainAbility" + } + ] + } +] +``` + +#### Table 19 Internal structure of the forms attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Class name of the widget. The value is a string with a maximum of 127 bytes.| String| No| +| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean| No| +| type | Type of the widget. The options are as follows:
**JS**: indicates a JavaScript-programmed widget.| String| No| +| colorMode | Color mode of the widget. The options are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String| Yes (initial value: **auto**)| +| supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 1**: indicates a grid with two rows and one column.
**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 from the **supportDimensions** array of the widget.| String| No| +| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated 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.| 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 attribute does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.| Number| Yes (initial value: **0**)| +| formConfigAbility | Name of the ability used to adjust the widget.| String| Yes (initial value: left empty)| +| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String| No| +| metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute.| Object| Yes (initial value: left empty)| +| customizeData | Custom information of the widget.| Object array| Yes (initial value: left empty)| + +#### Table 20 Internal structure of the customizeData attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| extra | Format of the current custom data. The value is the resource value of **extra**.| String| Yes (initial value: left empty)| + + +Example of the **forms** attribute structure: + +```json +"forms": [ + { + "name": "Form_Js", + "description": "It's Js Form", + "type": "JS", + "jsComponentName": "card", + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "11:00", + "updateDuration": 1, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2", + "2*4", + "4*4" + ] + }, + { + "name": "Form_Js", + "description": "It's JS Form", + "type": "Js", + "colorMode": "auto", + "isDefault": false, + "updateEnabled": true, + "scheduledUpdateTime": "21:05", + "updateDuration": 1, + "defaultDimension": "1*2", + "supportDimensions": [ + "1*2" + ], + "landscapeLayouts": [ + "$layout:ability_form" + ], + "portraitLayouts": [ + "$layout:ability_form" + ], + "formConfigAbility": "ability://com.example.myapplication.fa/.MainAbility", + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "com.example.weather.testWidget" + } + ] + } + } +] +``` + +#### Table 21 Internal structure of the distroFilter attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| apiVersion | Supported API versions.| Object array| Yes (initial value: left empty)| +|screenShape | Supported screen shapes.| Object array| Yes (initial value: left empty)| +| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)| +|screenDensity | Pixel density of the screen, in dots per inch (DPI).| Object array| Yes (initial value: left empty)| +| countryCode | Country code used for distributing the application. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported.| Object array| Yes (initial value: left empty)| + +#### Table 22 Internal structure of the apiVersion attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | API versions, for example, 4, 5, or 6. Example: If an application comes with two versions developed using API version 5 and API version 6 for the same device model, two installation packages of the entry type can be released for the application.| Array| No| + +#### Table 23 Internal structure of the screenShape attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Screen shapes. The value can be **circle**, **rect**, or both. Example: Different HAP files can be provided for a smart watch with a circular face and that with a rectangular face. | Array| No| + +#### Table 24 Internal structure of the screenWindow attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Screen width and height, in pixels. The value an array of supported width and height pairs, each in the "width * height" format, for example, **"454 * 454"**. | Array| No| + +#### Table 25 Internal structure of the screenDensity attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Pixel density of the screen, in dots per inch (DPI). The options are as follows:
**sdpi**: small-scale DPI. This value is applicable to devices with a DPI range of (0, 120].
**mdpi**: medium-scale DPI. This value is applicable to devices with a DPI range of (120, 160].
**ldpi**: large-scale DPI. This value is applicable to devices with a DPI range of (160, 240].
**xldpi**: extra-large-scale DPI. This value is applicable to devices with a DPI range of (240, 320].
**xxldpi**: extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (320, 480].
**xxxldpi**: extra-extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (480, 640].| Array| No| + +#### Table 26 Internal structure of the countryCode attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**.
- **exclude**: Exclude the matches of the sub-attribute value.
- **include**: Include the matches of the sub-attribute value.| String| No| +| value | Country code of the area to which the application is to be distributed. The value is a string array, of which each substring indicates a country or region. The substring consists of two uppercase letters.| String array| No| + + +Example of the **distroFilter** attribute structure: + +```json +"distroFilter": { + "apiVersion": { + "policy": "include", + "value": [4,5] + }, + "screenShape": { + "policy": "include", + "value": ["circle","rect"] + }, + "screenWindow": { + "policy": "include", + "value": ["454*454","466*466"] + }, + "screenDensity":{ + "policy": "exclude", + "value": ["ldpi","xldpi"] + }, + "countryCode": { + "policy":"include", + "value":["CN","HK"] + } +} +``` + +#### Table 27 Internal structure of the commonEvents attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the static common event. The value can contain a maximum of 127 bytes.| String| No| +| permission | Permission required to implement static common events. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| data | Additional data array to be carried by the current static common event.| String array| Yes (initial value: left empty)| +| type | Type array of the current static common event.| String array| Yes (initial value: left empty)| +| events | A set of events for the wants that can be received. The value can be system predefined or custom.| String array| No| + + +Example of the **commonEvents** attribute structure: + +```json +"commonEvents": [ + { + "name": ".MainAbility", + "permission": "ohos.permission.GET_BUNDLE_INFO", + "data": [ + "com.example.demo", + "100" + ], + "events": [ + "install", + "update" + ] + } +] +``` + +#### Table 28 Internal structure of the testRunner attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the test runner object. The value can contain a maximum of 255 bytes.| String| No| +| srcPath | Code path of the test runner. The maximum length of this tag is 255 bytes.| String| No| + +```json +"testRunner": { + "name": "myTestRunnerName", + "srcPath": "etc/test/TestRunner.ts" +} +``` + + +**definePermission** applies only to system applications and does not take effect for third-party applications. + +#### Table 29 Internal structure of the definePermissions attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of a permission. The value can contain a maximum of 255 bytes.| String| No| +| grantMode | Permission grant mode. The options are as follows:
- **system_grant**: The permission is automatically granted by the system after the application is installed.
- **user_grant**: The permission is dynamically requested when needed and must be granted by the user.| String| Yes (initial value: **"system_grant"**)| +| availableLevel | Permission type. The options are as follows:
- **system_core**: system core permission.
- **system_basic**: basic system permission.
- **normal**: normal permission, which can be requsted by all applications.| String| Yes (initial value: **"normal"**)| +| provisionEnable | Whether the permission can be requested in provision mode, including high-level permissions. The value **true** means that the permission can be requested in provision mode.| Boolean| Yes (initial value: **true**)| +| distributedSceneEnabled | Whether the permission can be used in distributed scenarios.| Boolean| Yes (initial value: **false**)| +| label | Brief description of the permission. The value is a resource index to the description.| String| Yes (initial value: left empty)| +| description | Detailed description of the permission. The value is a string with a maximum of 255 bytes or a string resource index.| String| Yes (initial value: left empty)| diff --git a/en/application-dev/quick-start/multi-hap-build-view.md b/en/application-dev/quick-start/multi-hap-build-view.md new file mode 100644 index 0000000000000000000000000000000000000000..3266828fdbda2b969668410a98ce4b64cce54411 --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-build-view.md @@ -0,0 +1,28 @@ +# Multi-HAP Build View + + +DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below. + + + **Figure 1** Multi-HAP build view +![hap-multi-view](figures/hap-multi-view.png) + + +1. Development view in DevEco Studio + - AppScope folder + - [app.json5](app-configuration-file.md): application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number. + - **resources** folder: stores application icon resources and application name string resources. + + **NOTE** + - The folder is automatically generated by DevEco Studio and its name cannot be changed. + - The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module directories. Otherwise, DevEco Studio reports an error. + - Entry- or feature-type module directories (the names are customizable) + - You implement service logic of your application in these module directories. In this example, the module folders are **entry.hap** and **feature.hap**. + - **resources** directory: stores the resources used by the module. + - **ets** folder: stores the service logic. + - [module.json5](module-configuration-file.md): module configuration, such as the module name, entry code path of the module, and component information. + +2. View after build and packaging + - After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file. + - The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view. + - All HAP files are finally built into an Application Package (App Pack) in .app format for release to the application market. diff --git a/en/application-dev/quick-start/multi-hap-objective.md b/en/application-dev/quick-start/multi-hap-objective.md new file mode 100644 index 0000000000000000000000000000000000000000..ad43c84fd7799be1e3277400c6c5dfb1926d5b7c --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-objective.md @@ -0,0 +1,10 @@ +# Multi-HAP Design Objectives + + +- Modular management: A well-designed application is generally managed in a modular manner, where modules are loosely coupled. In light of this, the multi-HAP mechanism is designed, allowing you to divide services into multiple modules and store each module in an independent HAP file. For example, If you are developing a payment application and its home screen consists of multiple modules, such as the scan, pay, messaging, and finance modules, you can implement the logic of the home screen for managing other modules in the entry-type HAP file, and implement specific modules in feature-type HAP files. The feature-type HAP files are independent. You can develop and test each of them separately, and then integrate them with the entry-type HAP file. + +- Flexible deployment: You can combine multiple HAP files and deploy them on different devices. Assume that an application contains one entry-type HAP file (**Entry.hap**) and two feature-type HAP files (**Feature1.hap** and **Feature2.hap**). The **Entry.hap** file can be deployed on device A and device B, the **Feature1.hap** file can be deployed only on device A, and the **Feature2.hap** can be deployed only on device B. In this way, you can easily combine the **Entry.hap** and **Feature1.hap** files and deploy them on device A, and combine the **Entry.hap** and **Feature2.hap** files and deploy them on device B. + +- On-demand loading: You can load modules only when they are needed, reducing the package size. Specifically, you can configure some HAP files of an application to be loaded on demand. For example, if some features are not used during application startup, you can configure them to be loaded only when they are needed, rather than being loaded at startup. This can reduce the size of the application package to some extent. + +- Easier resource sharing: The resources (including public resource files and public pages) and shared objects (.so library files) required by multiple HAP files can be stored in an independent HAP file. In this way, other HAP files can obtain the resources and files by accessing the HAP, which reduces the size of the application package to some extent. diff --git a/en/application-dev/quick-start/multi-hap-principles.md b/en/application-dev/quick-start/multi-hap-principles.md new file mode 100644 index 0000000000000000000000000000000000000000..9268c0ddafacf26962d8a3d46d9f2adf98e6aac4 --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-principles.md @@ -0,0 +1,21 @@ +# Multi-HAP Operation Mechanism and Data Communication Modes + + +The multi-HAP mechanism is used to facilitate modular management for developers. There is no one-to-one mapping between the HAP and the running process of the application. The detailed running mechanism is as follows: + + +- By default, all UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in the same independent process, and other ExtensionAbility components of the same type run in separate processes. + +- The HAP file supports the process configuration through the **process** tag in the **module.json5** (stage model) or **config.json** (FA model) file. This feature is supported only by system applications. If **process** is configured for an HAP file, all components of the HAP file run in an independent process. Multiple HAP files can be configured with the same process, in which case the HAP files run in the same process. For details about the process configuration, see [module.json5 Configuration File](module-configuration-file.md). + +- When an application is running, the resources and code of the corresponding HAP file are loaded only when the UIAbility component in the same process is started. + + +Based on the preceding mechanism, the multi-HAP data communication modes are as follows: + + +- For details about data communication in the same process, see [Thread Model (Stage Model)](../application-models/thread-model-stage.md). + +- For details about cross-process data communication, see [Process Model (Stage Model)](../application-models/process-model-stage.md). + +- If multiple HAPs run in the same process, the communication mode between the components of multiple HAP files is the same as that between the components of the same HAP file. diff --git a/en/application-dev/quick-start/multi-hap-release-deployment.md b/en/application-dev/quick-start/multi-hap-release-deployment.md new file mode 100644 index 0000000000000000000000000000000000000000..785f476bf2fa508470d433477f4e1139e76589fd --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-release-deployment.md @@ -0,0 +1,51 @@ +# Multi-HAP Development, Debugging, Release, and Deployment Process + +Below is the process of developing, debugging, releasing, and deploying multiple HAP files. + +**Figure 1** Process of developing, debugging, releasing, and deploying multiple HAP files +![hap-release](figures/hap-release.png) + +## Development +You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules based on service requirements and develop services in independent modules. + +## Debugging +You can use DevEco Studio to build code into one or more HAP files. Then, you can debug the HAP files. +* Using DevEco Studio for debugging + + Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520). + +* Using [hdc_std](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) for debugging + + You can obtain the hdc_std tool from the **toolchains** directory of the SDK. When using this tool to install an HAP file, the HAP file path is the one on the operating platform. In this example, the Windows operating platform is used. The command reference is as follows: + ``` + // Installation and update: Multiple file paths can be specified. + hdc_std install C:\entry.hap C:\feature.hap + // The execution result is as follows: + install bundle successfully. + // Uninstall + hdc_std uninstall com.example.myapplication + // The execution result is as follows: + uninstall bundle successfully. + ``` + +* Using Bundle Manager (bm) for debugging + + When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows: + ``` + // Installation and update: Multiple file paths can be specified. + bm install -p /data/app/entry.hap /data/app/ feature.hap + // The execution result is as follows: + install bundle successfully. + // Uninstall + bm uninstall -n com.example.myapplication + // The execution result is as follows: + uninstall bundle successfully. + ``` +## Release +When your application package meets the release requirements, you can package and build it into an App Pack and release it to the application market on the cloud. The application market verifies the signature of the App Pack. If the signature verification is successful, the application market obtains the HAP files from the App Pack, signs them, and distributes the signed HAP files. + +## Deployment +The application market on the cloud distributes the applications to application market clients. These applications can contain one or more HAP files. After the user selects an application to download, the application market downloads all the HAP files contained in this application. + +## Installation on a Device +After the download is complete, the application market client calls the installation API of the bundle manager service in the system to install the downloaded HAP files. The bundle manager service deploys HAP files by application in the specified directory to complete the application installation. diff --git a/en/application-dev/quick-start/multi-hap-rules.md b/en/application-dev/quick-start/multi-hap-rules.md new file mode 100644 index 0000000000000000000000000000000000000000..34b7824cb62b7e1ca73232faa9f58685df2077ac --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-rules.md @@ -0,0 +1,14 @@ +# Multi-HAP Usage Rules + + +- The App Pack cannot be directly installed on the device. It is only a unit that is released to AppGallery. + +- All HAP files in the App Pack must share the same **bundleName** value in the configuration files. + +- All HAP files in the App Pack must share the same **versionCode** value in the configuration files. + +- In an application, each type of device supports only one HAP of the entry type. Each application can contain zero, one, or more HAP files of the feature type. + +- Each HAP file in the App Pack must have **moduleName** configured. The **moduleName** value corresponding to all HAP files of the same device type must be unique. + +- The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of all HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, you must ensure that their signing certificates are the same. Otherwise, the installation will fail. diff --git a/en/application-dev/quick-start/package-structure.md b/en/application-dev/quick-start/package-structure.md deleted file mode 100644 index 6c1ecfe7be836e8b17dcb7d6d1045354d5aa386d..0000000000000000000000000000000000000000 --- a/en/application-dev/quick-start/package-structure.md +++ /dev/null @@ -1,797 +0,0 @@ - - -# Application Package Structure Configuration File - -When developing an application in the Feature Ability (FA) model, you must declare the package structure of the application in the **config.json** file. - -## Internal Structure of the config.json File - -The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. For details, see Table 1. - -Table 1 Internal structure of the config.json file - -| Tag | Description | Data Type| Initial Value Allowed| -| ------------ | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of the application. Different HAP files of the same application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| deviceConfig | Application configuration applied to a specific type of device. For details, see [Internal Structure of the deviceconfig Tag](#internal-structure-of-the-deviceconfig-tag).| Object | No | -| module | Configuration of a HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | - -Example of the **config.json** file: - -```json -{ - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5, - "releaseType": "Beta1" - } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.myapplication.entrymodule", - "name": ".MyApplication", - "deviceType": [ - "default" - ], - "distro": { - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.entrymodule.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "$string:app_name", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } -} -``` - -### Internal Structure of the app Tag - -The **app** tag contains the global configuration information of the application. For details about the internal structure, see Table 2. - -Table 2 Internal structure of the app tag - -| Attribute | Description | Data Type| Initial Value Allowed | -| ----------------- | ------------------------------------------------------------ | -------- | --------------------------- | -| bundleName | Bundle name, which uniquely identifies an application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The value is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String | No | -| vendor | Description of the application vendor. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | -| version | Version of the application. For details, see Table 3. | Object | No | -| apiVersion | OpenHarmony API version on which the application depends. For details, see Table 4. | Object | Yes (initial value: left empty) | -| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8.| Boolean | Yes (initial value: **false**)| -| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8. | Boolean | Yes (initial value: **true**) | -| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | - -Table 3 Internal structure of version - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------------ | ------------------------------------------------------------ | -------- | -------------------------- | -| name | Application version number visible to users. The value can be customized and cannot exceed 127 bytes. The customization rules are as follows:
API 5 and earlier versions: A three-segment version number is recommended, for example, A.B.C (also compatible with A.B). In the version number, A, B, and C are integers ranging from 0 to 999. Other formats are not supported.
A indicates the major version number.
B indicates the minor version number.
C indicates the patch version number.
API 6 and later versions: A four-segment version number is recommended, for example, A.B.C.D. In the version number, A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
A indicates the major version number.
B indicates the minor version number.
C indicates the feature version number.
D indicates the patch version number.| Number | No | -| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The value rules are as follows:
API 5 and earlier versions: It is a non-negative integer less than 32 bits in binary mode, converted from the value of version.name as follows: The conversion rules are as follows:
Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001.
API 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer ranging from 2 to 31. Note that the value must be updated each time the application version is updated. The value for a later version must be greater than that for an earlier version.| Number | No | -| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices.
The value rules are the same as those of **version.code**.| Number | No (initial value: **code** attribute value)| - -Table 4 Internal structure of apiVersion - -| Attribute | Description | Data Type| Initial Value Allowed| -| ----------- | ----------------------------------------------------------- | -------- | ---------- | -| compatible | Minimum API version required for running the application. The value ranges from 0 to 2147483647. | Integer | Yes | -| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Integer | Yes | -| releaseType | Type of the target API version required for running the application. | String | Yes | - -Example of the app tag structure: - -```json -"app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5, - "releaseType": "Beta1" - } -} -``` - -### Internal Structure of the deviceConfig Tag - -The **deviceConfig** tag contains the application configuration information on the device, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. For details about the internal structure, see Table 5. - -Table 5 Internal structure of the deviceConfig tag - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ----------------------------------------- | -------- | ------------------ | -| default | Application configuration applied to all types of devices. For details, see Table 6.| Object | No | -| tablet | Application configuration specific to tablets. For details, see Table 6. | Object | Yes (initial value: left empty)| -| tv | Application configuration specific to smart TVs. For details, see Table 6. | Object | Yes (initial value: left empty)| -| car | Application configuration specific to head units. For details, see Table 6. | Object | Yes (initial value: left empty)| -| wearable | Application configuration specific to wearables. For details, see Table 6.| Object | Yes (initial value: left empty)| - -For details about the internal structures of device attributes, see Table 6. - -Table 6 Internal structure of device attributes - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------ | ------------------------------------------------------------ | -------- | ----------------------- | -| process | 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. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. The value can contain a maximum of 31 characters.| String | Yes | -| keepAlive | Whether the application is always kept alive. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | -| supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**)| -| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **true**) | -| directLaunch | Whether the application can be started when the device is locked. The value **true** means that the application can be started when the device is locked. Devices running OpenHarmony do not support this attribute.| Boolean | Yes (initial value: **false**)| -| ark | Maple configuration. For details, see Table 7. | Object | Yes (initial value: left empty) | -| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code. For details, see Table 9.| Object | Yes (initial value: left empty) | - -Table 7 Internal structure of the ark attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | -------------------------------- | -------- | ------------------------------ | -| reqVersion | Maple version required for the application. For details, see Table 8.| Object | No | -| flag | Type of the Maple application. | String | No (available options: **m**, **mo**, **z**).| - -Table 8 Internal structure of the reqVersion attribute - -| Attribute | Description | Data Type| Initial Value Allowed| -| ---------- | --------------------------------------------------------- | -------- | ---------- | -| compatible | Minimum Maple version required for the application. The value is a 32-bit unsigned integer.| Integer | No | -| target | Type of the Maple application. The value is a 32-bit unsigned integer. | Integer | No | - -Table 9 Internal structure of the network attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------------- | ------------------------------------------------------------ | -------- | ----------------------- | -| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.
**true**: The application is allowed to use plaintext traffic.
**false**: The application is not allowed to use plaintext traffic.| Boolean | Yes (initial value: **false**)| -| securityConfig | Network security configuration of the application. For details, see Table 10. | Object | Yes (initial value: left empty) | - -Table 10 Internal structure of the securityConfig attribute - -| Attribute | Sub-attribute | Description | Data Type| Initial Value Allowed | -| -------------- | ------------------ | ------------------------------------------------------------ | -------- | ---------------- | -| domainSettings | - | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| -| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute.
**true**: Plaintext traffic can be transmitted.
**false**: Plaintext traffic cannot be transmitted.| Boolean| No | -| | domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**.
**subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches.
**name** (string): indicates the domain name.| Object array| No | - -Example of the deviceConfig tag structure: - -```json -"deviceConfig": { - "default": { - "process": "com.example.test.example", - "supportBackup": false, - "network": { - "cleartextTraffic": true, - "securityConfig": { - "domainSettings": { - "cleartextPermitted": true, - "domains": [ - { - "subdomains": true, - "name": "example.ohos.com" - } - ] - } - } - } - } -} -``` - -### Internal Structure of the module Tag - -The **module** tag contains the configuration information of the HAP file. For details about the internal structure, see Table 11. - -Table 11 Internal structure of the module tag - -| Attribute | Description | Data Type | Initial Value Allowed | -| ----------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| String | No if any ability using the Page template exists | -| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | No | -| name | Class name of the HAP file. The value is in the reverse domain name notation, with the prefix same as the package name specified by **package** at the same level. It can also start with a period (.). The value is a string with a maximum of 255 bytes.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | -| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| supportedModes | Mode supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty) | -| deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No | -| distro | Distribution description of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 12.| Object | No | -| metaData | Metadata of the HAP file. For details, see Table 13. | Object | Yes (initial value: left empty) | -| abilities | All abilities in the current module. The value is an array of objects, each of which represents a shortcut object. For details, see Table 17.| Object array | Yes (initial value: left empty) | -| js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module. For details, see Table 22.| Object array | Yes (initial value: left empty) | -| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object. For details, see Table 25.| Object array | Yes (initial value: left empty) | -| reqPermissions | Permissions that the application requests from the system when it is running. For details, see Table 21. | Object array | Yes (initial value: left empty) | -| colorMode | Color mode of the application. Available values are as follows:
**"dark"**: Resources applicable for the dark mode are selected.
**"light"**: Resources applicable for the light mode are selected.
**"auto"**: Resources are selected based on the color mode of the system.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **auto**) | -| distroFilter | Distribution rules of the application.
AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29.| Object | Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| -| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | -| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | -| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | -| testRunner | Test runner configuration. For details, see Table 36. | Object | Yes (initial value: left empty) | -| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The caller of the application must have these permissions to properly call the app. For details, see Table 37.| Object | Yes (initial value: left empty) | - -Example of the **module** tag structure: - -```json -"module": { - "mainAbility": "MainAbility", - "package": "com.example.myapplication.entry", - "name": ".MyOHOSAbilityPackage", - "description": "$string:description_application", - "supportModes": [ - "drive" - ], - "deviceType": [ - "car" - ], - "distro": { - "moduleName": "ohos_entry", - "moduleType": "entry" - }, - "abilities": [ - ... - ], - "shortcuts": [ - ... - ], - "js": [ - ... - ], - "reqPermissions": [ - ... - ], - "colorMode": "light" -} -``` - -Table 12 Internal structure of the distro attribute - -| Attribute | Description | Data Type| Initial Value Allowed| -| ---------------- | ------------------------------------------------------------ | -------- | ---------- | -| moduleName | Name of the HAP file. The maximum length is 31 characters. | String | No | -| moduleType | Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this attribute to **har**.| String | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.
Pay attention to the following:
- When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap **must be **true**.
- When **entry.hap** is set to **false**, **feature.hap** related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| deliveryWithInstall | Whether the HAP file is installed with application.
**true**: The HAP file is installed together with the application.
**false**: The HAP file is not installed together with the application.| Boolean| No| - -Example of the **distro** attribute structure: - -```json -"distro": { - "moduleName": "ohos_entry", - "moduleType": "entry", - "installationFree": true, - "deliveryWithInstall": true -} -``` - -Table 13 Internal structure of the metaData attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | ------------------------------------------------------------ | -------- | -------------------- | -| parameters | Metadata of the parameters to be passed for calling the ability. The metadata of each parameter consists of the **description**, **name**, and **type** sub-attributes. For details, see Table 14.| Object array| Yes (initial value: left empty) | -| results | Metadata of the ability return value. The metadata of each return value consists of the **description**, **name**, and **type** sub-attributes. For details, see Table 15.| Object array| Yes (initial value: left empty)| -| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**. For details, see Table 16.| Object array| Yes (initial value: left empty)| - -Table 14 Internal structure of the parameters attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ----------- | ------------------------------------------------------------ | -------- | ------------------ | -| description | Description of the parameter passed for calling the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| -| name | Name of the parameter passed for calling the ability. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the parameter passed for calling the ability, for example, **Integer**. | String | No | - -Table 15 Internal structure of the results attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ----------- | ------------------------------------------------------------ | -------- | -------------------- | -| description | Description of the return value. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| -| name | Name of the return value. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the return value, for example, **Integer**. | String | No | - -Table 16 Internal structure of the customizeData attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ---------------------------------------------------------- | -------- | -------------------- | -| name | Key of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Custom format of the data item. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty)| - -Example of the **metaData** attribute structure: - -```json -"metaData": { - "parameters" : [{ - "name" : "string", - "type" : "Float", - "description" : "$string:parameters_description" - }], - "results" : [{ - "name" : "string", - "type" : "Float", - "description" : "$string:results_description" - }], - "customizeData" : [{ - "name" : "string", - "value" : "string", - "extra" : "$string:customizeData_description" - }] -} -``` - -Table 17 Internal structure of the abilities attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- | -| 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. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) | -| name | Ability name. The value can be a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 characters. | String | No | -| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | -| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. | String | Yes (initial value: left empty) | -| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty) | -| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 characters. | String | Yes (No for abilities using the Data template) | -| launchType | Launch type of the ability. Available values are as follows:
**"standard"**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**"singleton"**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton startup type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **"singleton"**) | -| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean | Yes (initial value: **false**) | -| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | -| skills | Types of the **want** that can be accepted by the ability. | Object array | Yes (initial value: left empty) | -| deviceCapability | Device capabilities required to run the ability.| String array| Yes (initial value: left empty) | -| metaData | Metadata. For details, see Table 13. | Object | Yes (initial value: left empty) | -| type | Ability type. Available values are as follows:
**"page"**: FA developed using the Page template to provide the capability of interacting with users.
**"service"**: PA developed using the Service template to provide the capability of running tasks in the background.
**"data"**: PA developed using the Data template to provide unified data access for external systems.
**"CA"**: ability that can be started by other applications as a window. | String | No | -| orientation | Display orientation of the ability. This attribute applies only to the ability using the Page template. Available values are as follows:
**"unspecified"**: indicates that the system automatically determines the display orientation of the ability.
**"landscape"**: indicates the landscape orientation.
**"portrait"**: indicates the portrait orientation.
**"followRecent"**: indicates that the orientation follows the most recent application in the stack. | String | Yes (initial value: **"unspecified"**) | -| backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This attribute applies only to the ability using the Service template. Available values are as follows:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**pictureInPicture**: picture in picture (PiP) and small-window video playback services
**voip**: voice/video call and VoIP services
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services
**wifiInteraction**: WLAN scanning, connection, and transmission services
**screenFetch**: screen recording and screenshot services
**multiDeviceConnection**: multi-device interconnection service| String array| Yes (initial value: left empty) | -| grantPermission | Whether permissions can be granted for any data in the ability. | Boolean | Yes (initial value: left empty) | -| readPermission | Permission required for reading data in the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| writePermission | Permission required for writing data to the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. Available values are as follows:
**mcc**: indicates that the mobile country code (MCC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MCC is updated.
**mnc**: indicates that the mobile network code (MNC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MNC is updated.
**locale**: indicates that the locale is changed. Typical scenario: The user has selected a new language for the text display of the device.
**layout**: indicates that the screen layout is changed. Typical scenario: Currently, different display forms are all in the active state.
**fontSize**: indicates that font size is changed. Typical scenario: A new global font size is set.
**orientation**: indicates that the screen orientation is changed. Typical scenario: The user rotates the device.
**density**: indicates that the display density is changed. Typical scenario: The user may specify different display ratios, or different display forms are active at the same time.
**size**: indicates that the size of the display window is changed.
**smallestSize**: indicates that the length of the shorter side of the display window is changed.
**colorMode**: indicates that the color mode is changed.| String array| Yes (initial value: left empty) | -| mission | Task stack of the ability. This attribute applies only to the ability using the Page template. By default, all abilities in an application belong to the same task stack. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: bundle name of the application) | -| targetAbility | Target ability that this ability alias points to. This attribute applies only to the ability using the Page template. If the **targetAbility** attribute is set, only **name**, **icon**, **label**, **visible**, **permissions**, and **skills** take effect in the current ability (ability alias). Other attributes use the values of the **targetAbility** attribute. The target ability must belong to the same application as the alias and must be declared in **config.json** ahead of the alias. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty, indicating that the current ability is not an alias)| -| multiUserShared | Whether the ability supports data sharing among multiple users. This attribute applies only to the ability using the Data template. If this attribute is set to **true**, only one copy of data is stored for multiple users. Note that this attribute will invalidate the **visible** attribute. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | -| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | -| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean| Yes (initial value: **false**) | -| forms | Information about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | -| srcLanguage | Programming language used to develop the ability. The value can be **"js"** or **"ets"**. | String | Yes | -| srcPath | Path of the JS component code corresponding to the ability. | String | Yes (initial value: left empty) | -| uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$media:icon**.| String | Yes (initial value: left empty)| -| startWindowBackground | Index to the background color resource file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$color:red**.| String | Yes (initial value: left empty)| -| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. This attribute applies only to the ability using the Page template. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| - -Table 18 Internal structure of the uriPermission attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ----------------------- | -------- | ------------------------- | -| path | Path identified by **uriPermission**.| String | No | -| mode | Mode matching the **uriPermission**.| String | Yes (initial value: *default***)| - -Example of the **abilities** attribute structure: - -```json -"abilities": [ - { - "name": ".MainAbility", - "description": "test main ability", - "icon": "$media:ic_launcher", - "label": "$media:example", - "launchType": "standard", - "orientation": "unspecified", - "permissions": [], - "visible": true, - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ] - } - ], - "configChanges": [ - "locale", - "layout", - "fontSize", - "orientation" - ], - "type": "page", - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red", - "removeMissionAfterTerminate": true - }, - { - "name": ".PlayService", - "description": "example play ability", - "icon": "$media:ic_launcher", - "label": "$media:example", - "launchType": "standard", - "orientation": "unspecified", - "visible": false, - "skills": [ - { - "actions": [ - "action.play.music", - "action.stop.music" - ], - "entities": [ - "entity.audio" - ] - } - ], - "type": "service", - "backgroundModes": [ - "audioPlayback" - ] - }, - { - "name": ".UserADataAbility", - "type": "data", - "uri": "dataability://com.example.world.test.UserADataAbility", - "visible": true - } -] -``` - -Table 19 Internal structure of the skills attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | ------------------------------------------------------------ | ---------- | -------------------- | -| actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)| -| entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)| -| uris | URIs of the **want** that can be accepted by the ability. For details, see Table 20.| Object array | Yes (initial value: left empty)| - -Table 20 Internal structure of the uris attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | -------------------------- | -------- | -------------------- | -| scheme | Scheme of the URI. | String | No | -| host | Host value of the URI. | String | Yes (initial value: left empty)| -| port | Port number of the URI. | String | Yes (initial value: left empty)| -| pathStartWith | **pathStartWith** value of the URI.| String | Yes (initial value: left empty)| -| path | **path** value of the URI. | String | Yes (initial value: left empty)| -| pathRegx | **pathRegx** value of the URI. | String | Yes (initial value: left empty)| -| type | **type** value of the URI. | String | Yes (initial value: left empty)| - -Example of the **skills** attribute structure: - -```json -"skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ - { - "scheme": "http", - "host": "www.example.com", - "port": "8080", - "path": "query/student/name", - "type": "text/*" - } - ] - } -] -``` - -Table 21 reqPermissions - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| name | Name of the permission to request.| String| No| -| reason | Reason for requesting the permission. The value cannot exceed 256 bytes. Multi-language adaptation is required.| String| No if the requested permission is **user_grant** (if it is left empty, application release will be rejected)| -| usedScene | Application scenario and timing for using the permission. This attribute consists of the **ability** and **when** sub-attributes. **ability**: ability name. Multiple ability names can be configured. **when**: time for using the permission. The options are **inuse** and **always**.| Object| **ability**: mandatory for the **user_grant** permission and can be left empty in other cases
**when**: initial value allowed (initial value: **inuse**)| -For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). - -Table 22 Internal structure of the js attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | ------------------------ | -| name | Name of the JS component. The default value is **default**. | String | No | -| pages | Route information about all pages in the JS component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | -| window | Window-related configurations. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 23.| Object | Yes | -| type | Type of the JS component. Available values are as follows:
**"normal"**: indicates that the JavaScript component is an application instance.
**"form"**: indicates that the JavaScript component is a widget instance. | String | Yes (initial value: **"normal"**) | -| mode | Development mode of the JS component. For details, see Table 24. | Object | Yes (initial value: left empty) | - -Table 23 Internal structure of the window attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | -------- | ----------------------- | -| designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number | Yes (initial value: 720px) | -| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean | Yes (initial value: **false**)| - -Table 24 Internal structure of the mode attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | -------------------- | ----------------------------------- | --------------------------- | -| type | Type of the JS component. The value can be **"pageAbility"** or **"form"**. | String | Yes (initial value: **"pageAbility"**) | -| syntax | Syntax type of the JS component. The value can be **"hml"** or **"ets"**. | String | Yes (initial value: **"hml"**) | - -Example of the **js** attribute structure: - -```json -"js": [ - { - "name": "default", - "pages": [ - "pages/index/index", - "pages/detail/detail" - ], - "window": { - "designWidth": 720, - "autoDesignWidth": false - }, - "type": "form" - } -] -``` - -Table 25 Internal structure of the shortcuts attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty)| -| icon | Icon of the shortcut. The value is a resource index to the description. | String | Yes (initial value: left empty)| -| intents | Intents to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes. For details, see Table 26.| Object array| Yes (initial value: left empty)| - -Table 26 Internal structure of the intents attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------ | --------------------------------------- | -------- | -------------------- | -| targetClass | Target class of the shortcut. | String | Yes (initial value: left empty)| -| targetBundle | Application bundle name for the target ability of the shortcut.| String | Yes (initial value: left empty)| - -Example of the **shortcuts** attribute structure: - -```json -"shortcuts": [ - { - "shortcutId": "id", - "label": "$string:shortcut", - "intents": [ - { - "targetBundle": "com.example.world.test", - "targetClass": "com.example.world.test.entry.MainAbility" - } - ] - } -] -``` - -Table 27 Internal structure of the forms attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | -| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | -| type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | -| colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| -| supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 1: indicates a grid with two rows and one column.
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 from the **supportDimensions** array of the widget.| String | No | -| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | -| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | -| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | -| formConfigAbility | Name of the facility or activity used to adjust the ability. | String | Yes (initial value: left empty) | -| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | -| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String | No | -| metaData | Metadata of the widget. The value contains value of the **customizeData** attribute. For details, see Table 13. | Object | Yes (initial value: left empty) | -| customizeData | Custom information of the widget. For details, see Table 28. | Object array | Yes (initial value: left empty) | - -Table 28 Internal structure of the customizeData attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | --------------------------------------------------- | -------- | -------------------- | -| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Current format of the custom data. The value indicates the resource.| String | Yes (initial value: left empty)| - -Example of the **forms** attribute structure: - -```json -"forms": [ - { - "name": "Form_Js", - "description": "It's Js Form", - "type": "JS", - "jsComponentName": "card", - "colorMode": "auto", - "isDefault": true, - "updateEnabled": true, - "scheduledUpdateTime": "11:00", - "updateDuration": 1, - "defaultDimension": "2*2", - "supportDimensions": [ - "2*2", - "2*4", - "4*4" - ] - }, - { - "name": "Form_Js", - "description": "It's JS Form", - "type": "Js", - "colorMode": "auto", - "isDefault": false, - "updateEnabled": true, - "scheduledUpdateTime": "21:05", - "updateDuration": 1, - "defaultDimension": "1*2", - "supportDimensions": [ - "1*2" - ], - "landscapeLayouts": [ - "$layout:ability_form" - ], - "portraitLayouts": [ - "$layout:ability_form" - ], - "formConfigAbility": "ability://com.example.myapplication.fa/.MainAbility", - "metaData": { - "customizeData": [ - { - "name": "originWidgetName", - "value": "com.example.weather.testWidget" - } - ] - } - } -] -``` - -Table 29 Internal structure of the distroFilter attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | ------------------------------------------------------------ | -------- | -------------------- | -| apiVersion | Supported API versions. For details, see Table 30. | Object | Yes (initial value: left empty)| -| screenShape | Supported screen shapes. For details, see Table 31. | Object array| Yes (initial value: left empty)| -| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables. For details, see Table 32.| Object array| Yes (initial value: left empty)| -| screenDensity | Pixel density of the screen, in dots per inch (dpi). For details, see Table 33. | Object array| Yes (initial value: left empty)| -| countryCode | Country code used for distributing the application. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported. For details, see Table 34.| Object array| Yes (initial value: left empty)| - -Table 30 Internal structure of the apiVersion attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | An integer of the existing API version, for example, 4, 5, or 6. Example: If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| - -Table 31 Internal structure of the screenShape attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | The value can be **circle** or **rect**. Example: Different HAPs can be provided for a smart watch with a circular face and that with a rectangular face.| Array | Yes (initial value: left empty)| - -Table 32 Internal structure of the screenWindow attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Width and height of the screen. The value of a single string is in the format of Width x Height in pixels, for example, **454*454**.| Array | Yes (initial value: left empty)| - -Table 33 Internal structure of the screenDensity attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Available values are as follows:
**sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: screen density with medium-scale dots per inch (MDPI). This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].
**xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].
**xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].
**xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640].| Array | Yes (initial value: left empty)| - -Table 34 Internal structure of the countryCode attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | ------------------------------------------------------------ | ---------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Country code of the area to which the application is to be distributed. The value is a string array, of which each substring indicates a country or region. The substring consists of two uppercase letters.| String array| Yes (initial value: left empty)| - -Example of the **distroFilter** attribute structure: - -```json -"distroFilter": { - "apiVersion": { - "policy": "include", - "value": [4,5] - }, - "screenShape": { - "policy": "include", - "value": ["circle","rect"] - }, - "screenWindow": { - "policy": "include", - "value": ["454*454","466*466"] - }, - "screenDensity":{ - "policy": "exclude", - "value": ["ldpi","xldpi"] - }, - "countryCode": { - "policy":"include", - "value":["CN","HK"] - } -} -``` - -Table 35 Internal structure of the commonEvents attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | ---------- | ------------------ | -| name | Name of a static broadcast. | String | No | -| permission | Permission needed to implement the static common event. | String array| Yes (initial value: left empty)| -| data | Additional data array to be carried by the current static common event. | String array| Yes (initial value: left empty)| -| type | Type array of the current static common event. | String array| Yes (initial value: left empty)| -| events | A set of events for the wants that can be received. The value can be system predefined or custom.| String array| No | - -Example of the **commonEvents** attribute structure: - -```json -"commonEvents": [ - { - "name":"MainAbility", - "permission": "string", - "data":[ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - } -] -``` - -Table 36 Internal structure of the testRunner attribute - -| Attribute| Description | Data Type| Initial Value Allowed| -| -------- | -------------------- | -------- | ---------- | -| name | Name of the test runner object.| String | No | -| srcPath | Path of the test runner code.| String | No | - -```json -"testRunner": { - "name": "myTestRUnnerName", - "srcPath": "etc/test/TestRunner.ts" -} -``` - -Table 37 Internal structure of the definePermissions attribute -**definePermission** applies only to system applications and does not take effect for third-party applications. - -| Attribute | Description | Data Type| Initial Value Allowed| -| ----------------------- | ------------------------------------------------------------ | -------- | ---------- | -| name | Permission name. | String | No | -| grantMode | Permission grant mode.
Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user. | String | Yes (initial value: **"system_grant"**) | -| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | -| provisionEnable | Whether the permission can be requested in provision mode. | Boolean | Yes (initial value: **true**) | -| distributedSceneEnabled | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | -| label | Brief description of the permission. The value is a resource index. | String | Yes | -| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes | diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index 03845296847a43338cca31673b76e46b8c496bbf..ff66e3d405738a44f0c645593ffb0dbfb5beca97 100644 --- a/en/application-dev/quick-start/stage-structure.md +++ b/en/application-dev/quick-start/stage-structure.md @@ -1,843 +1,25 @@ +# Application Configuration File Overview (Stage Model) -# Application Package Structure Configuration File +Each application project must have configuration files in its code directory. These configuration files provide basic application information for build tools, operating systems, and application markets. -When developing an application in the Feature Ability (FA) model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json5** and **app.json** files. -## Configuration File Internal Structure +In the code directory of an application project developed in stage model, there are two types of configuration files: one **app.json5** file and one or more **module.json5** files. -The configuration files each consist of two mandatory tags, namely, **app** and **module**. For details, see Table 1. -Table 1 Configuration file internal structure +The [app.json5](app-configuration-file.md) file contains the following contents: -| Tag| Description | Data Type| Initial Value Allowed| -| -------- | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of the application. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| module | Configuration of the HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | -### Internal Structure of the app Tag +- Application-wide configuration, including the bundle name, developer, and version number. -Code snippet in the **app.json** file: +- Device-specific configuration. -```json -{ - "app": { - "bundleName": "com.application.music", - "vendor": "application", - "versionCode": 1, - "versionName": "1.0", - "minCompatibleVersionCode": 1, - "minAPIVersion": 7, - "targetAPIVersion": 8, - "apiReleaseType": "Release", - "debug": false, - "icon": "$media:app_icon", - "label": "$string:app_name", - "description": "$string:description_application", - "distributedNotificationEnabled": true, - "entityType": "game", - "car": { - "apiCompatibleVersion": 8 - } - } -} -``` -This tag is an application-level attribute that applies to all the HAP files and components in the application. For the internal structure of the tag, see Table 2. +The [module.json5](module-configuration-file.md) file contains the following contents: -Table 2 Internal structure of the app tag -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | -| bundleName | Bundle name that uniquely identifies the application. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
For an application compiled with the system source code, its bundle name must be in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony. | String | No | -| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | -| icon | Icon of the application. The value is the index to the resource file. | String | No | -| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | -| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | -| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | -| minCompatibleVersionCode | Earliest version that the application is compatible with. It is used to determine cross-device compatibility. | Number | Yes (initial value: value of **versionCode**)| -| minAPIVersion | Minimum API version required for running the application. | Integer | Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| -| targetAPIVersion | Target API version required for running the application. | Integer | Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| -| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | -| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | -| entityType | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: **"unspecified"**) | -| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8. | Boolean | Yes (initial value: **false**) | -| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | -| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | -| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | -| accessible | Whether the installation directory of the application is accessible. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the installation directory can be accessed by third-party applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| multiProjects | Whether multiple projects are supported.| Boolean| Yes (initial value: **false**)| -| deviceType | Supported device types, such as **tablet**, **tv**, **wearable**, and **car**. The following attributes may be included: **minAPIVersion**, **distributedNotificationEnabled**, **keepAlive**, and **removable**.| Object | Yes (initial value: settings under **"app"**)| +- Basic module configuration, such as the name, type, description, and supported device types of the module. -### Internal Structure of the module Tag +- Information about the [application components](../application-models/stage-model-development-overview.md), including the descriptions of the UIAbility and ExtensionAbility components. -Code snippet in the **module.json5** file: - -```json -{ - "module": { - "name": "myHapName", - "type": "entry|feature|har", - "srcEntrance" : "./MyAbilityStage.js", - "description" : "$string:description_application", - "mainElement": "MainAbility", - "deviceTypes": [ - "tablet", - "tv", - "wearable", - "car", - "router" - ], - "deliveryWithInstall": true, - "installationFree": false, - "virtualMachine": "ark | default", - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file1" - }, - { - "name": "string", - "value": "string", - "resource": "$profile:config_file2" - } - ], - "abilities": [ - { - "name": "MainAbility", - "srcEntrance" : "./login/MyMainAbility.ts", - "description": "$string:description_main_ability", - "icon": "$media:icon", - "label": "HiMusic", - "visible": true, - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ ] - } - ], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" - ], - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red" - }, - { - "name": "sampleAbility", - "srcEntrance" : "./login/sampleAbility.ts", - "description": "$string:description_sample_ability", - "icon": "$media:icon", - "label": "HiMusic", - "visible": true, - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red" - } - ], - "requestPermissions": [ - { - "name": "ohos.abilitydemo.permission.PROVIDER", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "FormAbility" - ], - "when": "inuse" - } - } - ] - } -} -``` - -This tag stores the HAP configuration, which only applies to the current HAP file. - -Table 3 Internal structure of the module tag - -| Attribute | Description | Data Type | Initial Value Allowed | -| -------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | Name of the current module. After the module is packed into a HAP file, this attribute indicates the name of the HAP file. The value is a string with a maximum of 31 bytes and must be unique in the entire application.| String | No | -| type | Type of the HAP file. There are three types: **entry**, **feature**, and **har**.| String | No | -| srcEntrance | Path of the entry JS code corresponding to the HAP file. The value is a string with a maximum of 127 bytes.| String | Yes | -| description | Description of the HAP file. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| process | Process of the HAP file. The value is a string with a maximum of 31 bytes. If a process is configured under **hap**, all abilities of the application run in this process. This attribute applies only to system applications.| String | Yes (initial value: value of **bundleName** under the **app** tag) | -| mainElement | Entrance ability name or extension name of the HAP file. Only the ability or extension whose value is **mainElement** can be displayed in the Service Center. This attribute cannot be left at the initial value for an OpenHarmony atomic service.| String | Yes for an OpenHarmony application | -| deviceTypes | Types of the devices on which the HAP file can run. Table 4 lists the device types predefined by the system.
Unlike **syscap**, which is based on the device capability (such as Bluetooth and Wi-Fi), **deviceTypes** is based on the device type.| String array| No (can be left empty) | -| deliveryWithInstall | Whether the current HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| Boolean | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.

When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap** must be **true**.
When **entry.hap** is set to **false**, **feature.hap** fields related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| virtualMachine | Type of the target virtual machine (VM) where the current HAP file is running. It is used for cloud distribution, such as the application market and distribution center.
If the target VM type is Ark, the value is **ark**. Otherwise, the value is **default**. This attribute is automatically inserted when the IDE builds the HAP file. When the decompression tool parses the HAP file, if the HAP file does not contain this attribute, the value is set to **default**. | String | Yes (initial value: **default**) | -| uiSyntax(deprecated) | Syntax type of the JS component. This attribute is deprecated since API version 9.
**"hml"**: indicates that the JS component is developed using HML, CSS, or JS.
**"ets"**: indicates that the JS component is developed using the eTS declarative syntax.| String | Yes (initial value: **"hml"**) | -| pages | Profile resource used to list information about each page in the JS component. For details about how to use **pages**, see the **pages** example.| Object | No in the ability scenario | -| metadata | Custom metadata of the HAP file. The configuration is valid only for the current module, ability, or extensionAbility. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | -| abilities | Ability configuration, which is valid only for the current ability. For details, see [Internal Structure of the abilities Attribute](#internal-structure-of-the-abilities-attribute).| Object | Yes (initial value: left empty) | -| extensionAbilities | Extension ability configuration, which is valid only for the current Extension ability. For details, see [Internal structure of the extensionAbility attribute](#internal-structure-of-the-extensionability-attribute).| Object | Yes (initial value: left empty) | -| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The callers must acquire these permissions before calling the application. For details, see [Internal structure of the definePermissions attribute](#internal-structure-of-the-definepermissions-attribute).| Object | Yes (initial value: left empty)| -| requestPermissions | A set of permissions that the application needs to request from the system when the application is running. For details, see [Internal structure of the requestPermissions attribute](#internal-structure-of-the-requestpermissions-attribute). | Object | Yes (initial value: left empty) | -| testRunner | Test runner configuration. For details, see [Internal structure of the testRunner attribute](#internal-structure-of-the-testrunner-attribute).| Object | Yes (initial value: left empty) | - -Table 4 System-defined deviceTypes values - -| Value | Device Type | -| -------- | -------------------------------------------------------- | -| tablet | Tablet, speaker with a screen | -| tv | Smart TV | -| wearable | Smart watch, kids' watch, especially a watch that provides call features| -| car | Head unit | -| router | Router | - -Example of the **deviceTypes** attribute structure: - -```json -{ - "module": { - "name": "myHapName", - "type": "har", - "deviceTypes" : [ - "wearable" - ] - } -} -``` - -Example of the **pages** attribute structure: - -```json -{ - "module": { - "name": "myHapName", - "type": "har", - "deviceTypes" : [ - "wearable" - ], - "pages": "$profile:pages_config" - } -} -``` - -Example of the **pages_config** configuration file: - -```json -{ - "src": [ - "pages/index/index", - "pages/second/second", - "pages/third/third", - "pages/four/four" - ] -} -``` - - - -#### Internal Structure of the metadata Attribute - -The **metadata** attribute provides the configuration about the module, ability, and extensionAbility. The value is of the array type. The configuration is valid only for the current module, ability, or extensionAbility. - -Table 5 Internal structure of the metadata attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------------- | -| name | Name of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | -| resource | Custom data format. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty) | - -Example of the **metadata** attribute structure: - -```json -{ - "module": { - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - }, - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - } - ] - } -} -``` - -#### Internal Structure of the abilities Attribute - -The **abilities** attribute describes the ability configuration information. The value is of the array type. - -Table 6 Internal structure of the abilities attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | Logical name of the ability, which must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String | No | -| srcEntrance | JS code path corresponding to the ability. The value is a string with a maximum of 127 bytes.| String | No | -| launchType | Ability startup mode. Available values are as follows:
**"standard"**: indicates common multi-instance.
**"singleton"**: indicates a singleton.
**"specified"**: indicates one or more specified instances, depending on the internal service of the ability. | String | Yes (initial value: **singleton**) | -| description | Ability description. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the ability. The value is the index to the resource file. | String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| -| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | -| metadata | Metadata of the ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | -| visible | Whether the ability can be invoked by other applications. The value **true** means that the ability can be invoked by other applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| continuable | Whether the ability can be migrated. The value **true** means that the ability can be migrated, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | -| backgroundModes | Continuous task modes of the ability.
Continuous tasks are classified into the following types:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables)
**multiDeviceConnection**: multi-device interconnection service
**wifiInteraction**: Wi-Fi scanning, connection, and transmission services (multi-screen cloning)
**voip**: voice/video call and VoIP services
**taskKeeping**: computing service
| String | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. Example: **$media:icon**.| String | No| -| startWindowBackground | Index to the background color resource file of the ability startup page. Example: **$color:red**.| String | No| -| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| -| orientation | Display orientation of the ability when it is started. Available values are as follows:
**"unspecified"**: The device orientation is auto-set by the system.
**"landscape"**: The device is in landscape orientation.
**"portrait"**: The device is in portrait orientation.
**"landscape_inverted"**: The device is in inverted landscape orientation.
**"portrait_inverted"**: The device is in inverted portrait orientation.
**"auto_rotation"**: The device orientation is determined by the sensor.
**auto_rotation_landscape**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape.
**auto_rotation_portrait**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait.
**auto_rotation_restricted**: The device orientation is determined by the sensor when the sensor switch is enabled.
**auto_rotation_landscape_restricted**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape, when the sensor switch is enabled.
**auto_rotation_portrait_restricted**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait, when the sensor switch is enabled.
**locked**: Auto rotate is disabled.| String | Yes (initial value: **"unspecified"**)| -|supportWindowMode|Window display mode of the ability. Available values are as follows:
**fullscreen**: full-screen mode.
**split**: split-screen mode.
**floating**: floating window mode.|Array | Yes (initial value:
["fullscreen", "split", "floating"])| -|priority|Priority of the ability. This attribute applies only to system applications and does not take effect for third-party applications. During implicit query, an ability with a higher the priority is closer to the top of the returned list. The value is an integer ranging from 0 to 10. A larger value indicates a higher priority.|Number| Yes (initial value: **0**)| -|maxWindowRatio|Maximum aspect ratio of the ability.| Number |Yes (initial value: maximum aspect ratio of the platform)| -|minWindowRatio|Minimum aspect ratio of the ability.| Number |Yes (initial value: minimum aspect ratio supported by the platform)| -|maxWindowWidth|Maximum window width of the ability, in vp.| Number |Yes (initial value: maximum window width supported by the platform)| -|minWindowWidth|Minimum window width of the ability, in vp.| Number |Yes (initial value: minimum window width supported by the platform)| -|maxWindowHeight|Maximum window height of the ability, in vp.| Number |Yes (initial value: maximum window height supported by the platform)| -|minWindowHeight|Minimum window height of the ability, in vp.| Number |Yes (initial value: minimum window height supported by the platform)| -| excludeFromMissions | Whether the ability is excluded from the recent tasks list. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** indicates that the task is excluded from the recent tasks list, and **false** indicates that the task is displayed in the recent tasks list.| Boolean | Yes (initial value: **false**)| - -Example of the **abilities** attribute structure: - -```json -{ - "abilities": [{ - "name": "MainAbility", - "srcEntrance": "./ets/login/MyLoginAbility.ts", - "launchType":"standard", - "description": "$string:description_main_ability", - "icon": "$media:icon", - "label": "Login", - "permissions": [], - "metadata": [], - "visible": true, - "continuable": true, - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" - ], - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red", - "removeMissionAfterTerminate": true, - "orientation": " ", - "supportWindowMode": ["fullscreen", "split", "floating"], - "maxWindowRatio": 3.5, - "minWindowRatio": 0.5, - "maxWindowWidth": 2560, - "minWindowWidth": 1400, - "maxWindowHeight": 300, - "minWindowHeight": 200, - "excludeFromMissions": false - }] -} -``` - -#### Internal Structure of the skills Attribute - -This attribute identifies a want feature that can be received by the ability or extension. - -Table 7 Internal structure of the skills attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | ------------------------------------------------------------ | ---------- | -------------------- | -| actions | A set of want action values that can be received. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| -| entities | Categories of abilities that can receive the want. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| -| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details, see Table 8.| Object array | Yes (initial value: left empty)| - -Table 8 Internal structure of the uris attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------- | -------- | -------------------- | -| scheme | Scheme of the URI.| String | No | -| host | Host value of the URI. | String | Yes (initial value: left empty)| -| port | Port number of the URI. | String | Yes (initial value: left empty)| -| path | **path** value of the URI. | String | Yes (initial value: left empty)| -| type | **type** value of the URI. | String | Yes (initial value: left empty)| - -Example of the **skills** attribute structure: - -```json -{ - "abilities": [ - { - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ], - "extensionAbilities": [ - { - "skills": [ - { - "actions": [ - ], - "entities": [ - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ] -} -``` - -#### Internal Structure of the extensionAbility Attribute - -The **extensionAbility** attribute describes the configuration information of the current Extension ability. - -Table 9 Internal structure of the extensionAbility attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ----------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Logical name of the current Extension ability. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String | No | -| srcEntrance | JS code path corresponding to the Extension ability. The value is a string with a maximum of 127 bytes.| 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 | Icon of the Extension ability. The value is the index to the resource file. If **extensionAbility** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty) | -| label | Name of the Extension ability displayed to users. The value is a resource index to names in multiple languages.
If **extensionAbility** is set to **MainElement**, this attribute is mandatory and the value must be unique in the application.| String | No | -| type | Type of the Extension ability. The value can be **"form"**, **"workScheduler"**, **"inputMethod"**, **"service"**, **"accessibility"**, **"dataShare"**, **"fileShare"**, **"staticSubscriber"**, **"wallpaper"**, **"backup"**, **"window"**, **"enterpriseAdmin"**, **"thumbnail"**, or **"preview"**.| String | No | -| permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty) | -| uri | Data URI provided by the ability. The value is an array containing a maximum of 255 characters and is in the format of a reverse domain name. This attribute is mandatory when **type** is set to **extensionAbility** of the dataShare type.| String | Yes (initial value: left empty) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | -| metadata | Metadata of the Extension ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Object | Yes (initial value: left empty) | -| visible | Whether extensionAbility can be invoked by other applications. The value is of the Boolean type. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| Boolean | Yes (initial value: **false**)| - -Example of the **extensionAbility** attribute structure: - -```json -{ - "extensionAbilities": [ - { - "name": "FormName", - "srcEntrance": "./form/MyForm.ts", - "icon": "$media:icon", - "label" : "$string:extension_name", - "description": "$string:form_description", - "type": "form", - "permissions": ["ohos.abilitydemo.permission.PROVIDER"], - "readPermission": "", - "writePermission": "", - "visible": true, - "uri":"scheme://authority/path/query" - "skills": [{ - "actions": [], - "entities": [], - "uris": [] - }], - "metadata": [ - { - "name": "ohos.extability.form", - "resource": "$profile:form_config", - } - ] - } - ] -} - -``` - -#### Internal Structure of the definePermissions Attribute - -The **definePermissions** attribute indicates the permissions defined for the HAP file. - -Table 10 Internal structure of the definePermissions attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------------------- | ------------------------------------------------------------ | -------- | ------------------------------ | -| name | Permission name. | String | No | -| grantMode | Permission grant mode. Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user.| String | Yes (initial value: **"system_grant"**)| -| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | -| provisionEnable | Whether to enable provision mode for requesting permissions, including higher-level permissions. The value **true** indicates that provision mode is enabled.| Boolean | Yes (initial value: **true**) | -| distributedSceneEnable | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | -| label | Brief description of the permission. The value is a resource index. | String | Yes (initial value: left empty) | -| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes (initial value: left empty) | - -#### Internal Structure of the requestPermissions Attribute - -This attribute identifies a set of permissions that the application needs to request from the system when the application is running. - -Table 11 Internal structure of the requestPermissions attribute - -| Attribute | Description | Type | Value Range | Default Value | Restrictions | -| --------- | ------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ | -| name | Permission name. This attribute is mandatory. | String | Custom | N/A | Parsing will fail if this attribute is not set. | -| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**. | String | Resource reference of the string type in `$string: ***` format | Empty | If the permission to request is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required.| -| usedScene | Application scenario and timing for using the permission. This attribute is mandatory when the permission to request is **user_grant**. It consists of the **abilities** and **when** sub-attributes. Multiple abilities can be configured.| **abilities**: string array; **when**: string| **abilities**: array of ability names; **when**: **inuse** and **always**| **abilities**: left empty; **when**: left empty| If the permission to request is **user_grant**, the **abilities** sub-attribute is mandatory and **when** is optional. | - -Example of the **requestPermissions** attribute structure: - -```json -{ - "name": "ohos.abilitydemo.permission.PROVIDER", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "AudioAbility", - "VideoAbility", - ], - "when": "inuse" - } -} -``` -For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). - -#### Internal Structure of the form Attribute - -The **forms** attribute indicates the service widget configuration. The service widget is an application brief view that can be displayed on the home screen and periodically updated. You can include the **forms** attribute in any of the following modes: - -1. Set **type** to **form** in **extensions**. - -2. Specify the **form** information in **metadata**, where: - - **name** indicates the name of the service widget, for example, **ohos.extability.form**. - - **resource** indicates where the resources of the service widget are stored. - -Table 12 Internal structure of the forms attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ------------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | -| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| src | UI code of a JS service widget. It is recommended that you use the adaptive layout to display a service widget of different specifications. If the layout of a service widget of different specifications differs greatly, you are advised to use different service widgets.| String | Yes (initial value: left empty) | -| window | Adaptive capability of a JS service widget. For details, see Table 12. | Object | Yes (initial value: left empty) | -| isDefault | Whether the widget is a default one. Each ability has only one default widget. **true**: The service widget is the default one. **false**: The service widget is not the default one.| Boolean | No | -| colorMode | Color mode of the widget. The value can be **auto**, **dark**, or **light**.| String | Yes (initial value: **auto**) | -| supportDimensions | Dimensions supported by the service widget. The value can be **1 * 2**, **2 * 1**, **2 * 2**, **2 * 4**, or **4 * 4**, where the number before the asterisk (*) indicates the number of rows, and the number after the asterisk (*) indicates the number of columns.| String array| No | -| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String | No | -| updateEnabled | Whether the widget can be updated periodically. The value **true** indicates that the widget can be updated periodically, and **false** indicates that the widget cannot be updated periodically.| Boolean | No | -| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes | -| updateDuration | Update frequency of a widget. The unit is 30 minutes. The value is a multiple of 30. The highest frequency of refreshing a widget is once every 30 minutes. You can also use scheduled refresh to refresh a widget at a fixed time or once every 30 minutes. If both of them are configured, the scheduled refresh takes precedence.| Number | Yes (initial value: left empty) | -| metadata | Metadata of the widget. For details, see Table 5. | Object | Yes (initial value: left empty) | -| formConfigAbility | Ability name for widget adjustment. The value is a string of up to 127 characters. The value must be in the following format:
ability:// Name of an ability.
The name must be the same as that of the current application.| String | Yes (initial value: left empty) | -| formVisibleNotify | Whether the widget is allowed to use the visibility notification. The value is **true** or **false**.| Boolean | Yes (initial value: **false**)| - -Table 13 Internal structure of the window attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | -------- | -------------------- | -| designWidth | Baseline width of the page design, in pixels. The element size is scaled by the actual device width. The value is an integer.| Number | Yes (initial value: left empty)| -| autoDesignWidth | Whether to automatically calculate the baseline width of the page design. If this parameter is set to **true**, the **designWidth** attribute is invalid. The baseline width is calculated based on the device width and screen density.| Boolean | Yes (initial value: left empty)| - -Example of the **forms** attribute structure: - -Define the **form_config.json** file (this file name is customizable) in **resources/base/profile** of the development view. - -```json -{ - "forms": [ - { - "name": "Form_Js", - "description": "$string:form_description", - "src": "./js/pages/card/index", - "window": { - "designWidth": 720, - "autoDesignWidth": true - }, - "colorMode": "auto", - "formConfigAbility": "ability://xxxxx", - "formVisibleNotify": false, - "isDefault": true, - "updateEnabled": true, - "scheduledUpdateTime": "10:30", - "updateDuration": 1, - "defaultDimension": "2*2", - "updateEnabled": true, - "scheduledUpdateTime": "21:33", - "supportDimensions": [ - "2*2" - ], - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - } - ] - } - ] -} -``` - -Define metadata information in the **extension** component of the **module.json5** file. - -```json -{ - "extensionAbilities": [{ - "name": "MyForm", - "type": "form", - "metadata": [{ - "name": "ohos.extability.form", - "resource": "$profile:form_config" - }] - }] -} -``` - -#### Internal Structure of the shortcuts Attribute - -This attribute identifies the shortcut information of an application. The value is an array. A maximum of four shortcuts can be configured. It contains four sub-attributes: **shortcutId**, **label**, **icon**, and **wants**. - -Specify the **shortcut** information in **metadata**, where: - -- **name** indicates the name of the shortcut, for example, **ohos.ability.shortcuts**. - -- **resource** indicates where the resources of the shortcut are stored. - -Table 14 Internal structure of the shortcuts attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | -------------------------- | -| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty) | -| icon | Icon of the shortcut. The value is the index to the resource file. | String | Yes (initial value: left empty)| -| wants | Wants to which the shortcut points. The attribute consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut; string type.
**abilityName**: target component name of the shortcut; string type.| Object | Yes (initial value: left empty) | - -Define the **shortcut_config.json** file (this file name is customizable) in **resources/base/profile** of the development view. - -```json -{ - "shortcuts": [{ - "shortcutId": "id_test1", - "label": "$string:shortcut", - "icon": "$media:aa_icon", - "wants": [{ - "bundleName": "com.ohos.hello", - "abilityName": "MainAbility" - }] - }] -} -``` - -Define the **metadata** information under **module** in the **module.json5** file as follows: - -```json -{ - "module": { - "name": "MyAbilityStage", - "abilities": [{ - "name": "MyAbility", - "srcEntrance": "./abilities/MyAbility.ts", - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "metadata": [{ - "name": "ohos.ability.shortcuts", - "resource": "$profile:shortcuts_config" - }] - }] - } -} -``` - -#### Internal Structure of the commonEvents Attribute - -The **commonEvents** attribute identifies the registered static common event information. The value is an array. - -Specify the **commonEvent** information in the **metadata**, where: - -- **name** indicates the name of the common event, for example, **ohos.extability.staticSubscriber**. - -- **resource** indicates where the resources of the common event are stored. - -Table 15 Internal structure of the commonEvents attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | ---------- | -------------------------- | -| name | Ability name corresponding to the current static common event. The class must be marked in the ability.| String | No | -| permission | Permission required for implementing the static common event. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.| String | Yes (initial value: left empty) | -| types | Types of the current static common event. The value is an array of strings, each of which represents a type.| String array| Yes (initial value: left empty)| -| events | Events of the intents that can be accepted by the ability. The value can be customized or be the events predefined in the system.| String array| No | - -Define the **common_event_config.json** file in **resources/base/profile** in the development view. (The file name can be defined by developers.) - -```json -{ - "commonEvents": [{ - "name": "abilityName", - "permission": "string", - "types": [ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - }] -} -``` - -Define the **metadata** information under **extension** in the **module.json5** file as follows: - -```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:common_event_config", - }], - } -] -``` - -#### Internal Structure of the distroFilter Attribute - -Distribution rules of the application. - -This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when AppGallery distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. - -Table 16 Internal structure of the distroFilter attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | ------------------------------------------------------------ | -------- | -------------------------- | -| apiVersion | Supported API versions. For details, see Table 16. | Object array| Yes (initial value: left empty)| -| screenShape | Supported screen shapes. | Object array| Yes (initial value: left empty)| -| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)| -| screenDensity | Pixel density of the screen, in dots per inch (dpi). This attribute is optional. The value options are as follows:
**sdpi**: small-scale dots per inch. This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: medium-scale dots per inch. This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: large-scale dots per inch. This value is applicable for devices with a DPI in the (160, 240] range.
**xldpi**: extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (240, 320] range.
**xxldpi**: extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI in the (320, 480] range.
**xxxldpi**: extra-extra-extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (480, 640] range.| Object array| Yes (initial value: left empty)| -| countryCode | Code of the country or region to which the application is to be distributed. For details, see ISO-3166-1. Enumerated definitions of multiple countries and regions are supported. This attribute is optional. The substring of the value consists of two uppercase letters and indicates the supported countries or regions.| Object array| Yes (initial value: left empty)| - -Table 17 Internal structure of the apiVersion attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| - -Table 18 Internal structure of the screenShape attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | The value can be **circle** or **rect**. Example: Different HAP files can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| - -Table 19 Internal structure of the screenWindow attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Width and height of the screen. The value is in the "width * height" format, in pixels, for example, **454*454**.| Array | Yes (initial value: left empty)| - -Table 20 Internal structure of the screenDensity attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Pixel density of the screen, in dots per inch (dpi). | Array | Yes (initial value: left empty)| - -Table 21 Internal structure of the countryCode attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Code of the country or region to which the application is to be distributed. | Array | Yes (initial value: left empty)| - -Example of the **distroFilter** attribute structure: - -Define the **distroFilter_config.json** file in **resources/base/profile** of the development view. (The file name can be defined by developers.) - -```json -"distroFilter": [ - { - "apiVersion": { - "policy": "include", - "value": [4, 5] - }, - "screenShape": { - "policy": "include", - "value": ["circle", "rect"] - }, - "screenWindow": { - "policy": "include", - "value": ["454*454", "466*466"] - } - } -] -``` - -Define the **metadata** information under **extensionAbilities** in the **module.json5** file as follows: - -```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:distroFilter_config", - }], - } -] -``` - -#### Internal Structure of the testRunner Attribute - -Table 22 Internal structure of the testRunner attribute - -| Attribute| Description | Data Type| Initial Value Allowed| -| -------- | ---------------------- | -------- | ---------- | -| name | Name of the test runner object.| String | No| -| srcPath | Path of the test runner code.| String | No| - -``` -"testRunner": { - "name": "myTestRUnnerName", - "srcPath": "etc/test/TestRunner.ts" -} -``` +- Information about the permissions required during application running. diff --git a/en/application-dev/quick-start/start-overview.md b/en/application-dev/quick-start/start-overview.md index 5548032d25184e05086648501f67d52b6caf6c65..fd04d4b1e0e2551d2b2885f0314b39204692fc40 100644 --- a/en/application-dev/quick-start/start-overview.md +++ b/en/application-dev/quick-start/start-overview.md @@ -4,7 +4,7 @@ This document is intended for novices at developing OpenHarmony applications. It ![en-us_image_0000001364254729](figures/en-us_image_0000001364254729.png) -Before you begin, there are two basic concepts that will help you better understand OpenHarmony: UI framework and ability. +Before you begin, there are two basic concepts that will help you better understand OpenHarmony: UI framework and application model. ## Basic Concepts @@ -16,29 +16,25 @@ OpenHarmony provides a UI development framework, known as ArkUI. ArkUI provides ArkUI comes with two development paradigms: ArkTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). You can choose whichever development paradigm that aligns with your practice. -| **Development Paradigm**| **Programming Language**| **UI Update Mode**| **Applicable To**| **Intended Audience**| -| -------- | -------- | -------- | -------- | -------- | -| Declarative development paradigm| ArkTS| Data-driven| Applications involving technological sophistication and teamwork| Mobile application and system application developers| -| Web-like development paradigm| JavaScript| Data-driven| Applications and service widgets with simple UIs| Frontend web developers| +| **Development Paradigm**| **Programming Language**| **UI Update Mode**| **Applicable To** | **Intended Audience** | +| ---------------- | ------------ | -------------- | -------------------------------- | -------------------------------------- | +| Declarative development paradigm | ArkTS | Data-driven | Applications involving technological sophistication and teamwork| Mobile application and system application developers| +| Web-like development paradigm | JavaScript | Data-driven | Applications and service widgets with simple UIs | Frontend web developers | For more details, see [UI Development](../ui/arkui-overview.md). +### Application Model -### Ability +The application model is the abstraction of capabilities required by OpenHarmony applications. It provides necessary components and running mechanisms for applications. With application models, you can develop applications based on a unified set of models, making application development simpler and more efficient. For details, see [Elements of the Application Model](../application-models/application-model-composition.md). -An ability is the abstraction of a functionality that an application can provide. An application may provide various capabilities, and so it can have multiple abilities. These abilities can be deployed together or independently from each other. +Along its evolution, OpenHarmony has provided two application models: -The ability framework model has two forms: +- Feature Ability (FA) model. This model is supported by OpenHarmony API version 7 and 8. It is no longer recommended. For details about development based on the FA model, see [FA Model Development Overview](../application-models/fa-model-development-overview.md). +- Stage model. This model is supported since OpenHarmony API version 9. It is recommended and will evolve for a long time. In this model, classes such as **AbilityStage** and **WindowStage** are provided as the stage of application components and windows. That's why it is named stage model. For details about development based on the stage model, see [Stage Model Development Overview](../application-models/fa-model-development-overview.md). -- **FA model**: applies to application development using API version 8 and earlier versions. For details, see [FA Model Overview](../ability/fa-brief.md). +For details about the differences between the FA model and stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). -- **Stage model**: introduced since API version 9. For details, see [Stage Model Overview](../ability/stage-brief.md). - -The project directory structure of the FA model is different from that of the stage model. The stage model only works with the ArkTS programming language. - -For details about the differences between the FA model and stage model, see [Ability Framework Overview](../ability/ability-brief.md). - -This document provides an ability with two pages. For more information about ability development, see [Ability Development](../ability/ability-brief.md). +To help you better understand the preceding basic concepts and application development process, **Getting Started** provides a development example that contains two pages in different programming languages and application models. ## Tool Preparation diff --git a/en/application-dev/quick-start/start-with-ets-fa.md b/en/application-dev/quick-start/start-with-ets-fa.md index f1280c77658fd048619ec34bd5b6736713465ad0..66f2ead3d35e72950a81c5495db14254210c8c2b 100644 --- a/en/application-dev/quick-start/start-with-ets-fa.md +++ b/en/application-dev/quick-start/start-with-ets-fa.md @@ -40,7 +40,7 @@ - **src > main > ets > MainAbility > pages > index.ets**: the first page in the **pages** list, also referred to as the entry to the application. - **src > main > ets > MainAbility > app.ets**: ability lifecycle file. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories). - - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md). + - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md). - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation. @@ -129,7 +129,7 @@ > **NOTE** > > You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes. - - Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** The sample code is as follows: The sample code is as follows: + - Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** file. The sample code is as follows: ```json { @@ -223,7 +223,7 @@ You can implement page redirection through the [page router](../reference/apis/j .height('5%') // Bind the onClick event to the Next button so that clicking the button redirects the user to the second page. .onClick(() => { - router.push({ url: 'pages/second' }) + router.pushUrl({ url: 'pages/second' }) }) } .width('100%') diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index a37eb8d3da42490bfc4027ecadbf401f21982444..3bf9d124a666b0ad057310b21e1bf3b52cdf5505 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -38,7 +38,7 @@ - **src > main > ets > entryability**: entry to your application/service. - **src > main > ets > pages**: pages included in your application/service. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories). - - **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (Stage Model)](stage-structure.md). + - **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md). - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation. @@ -216,7 +216,7 @@ You can implement page redirection through the [page router](../reference/apis/j .height('5%') // Bind the onClick event to the Next button so that clicking the button redirects the user to the second page. .onClick(() => { - router.push({ url: 'pages/Second' }) + router.pushUrl({ url: 'pages/Second' }) }) } .width('100%') diff --git a/en/application-dev/quick-start/start-with-js-fa.md b/en/application-dev/quick-start/start-with-js-fa.md index e0b43711caa931013ca581c40f588fd6f6cfe070..ad648638defddada7565cc34b2172c67d3050765 100644 --- a/en/application-dev/quick-start/start-with-js-fa.md +++ b/en/application-dev/quick-start/start-with-js-fa.md @@ -39,7 +39,7 @@ - **src > main > js > MainAbility > app.js**: ability lifecycle file. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Limitations and Access](../ui/js-framework-resource-restriction.md). - - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md). + - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md). - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation. diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 80356f76fa74323530b24e2e503ea9dc09af1e81..85bb902ce576919aadc1422f1b8c35f7afd75718 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -1,6 +1,6 @@ # Development References - [SystemCapability](syscap.md) -- [SysCap List](syscap-list.md) +- [SystemCapability List](syscap-list.md) - [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) - [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md) - [JS Service Widget UI Component Reference](js-service-widget-ui/Readme-EN.md) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 13110f9784e44ab0d406917924394ef5b84fc470..7ec2ef1b9e52f9d3e4e53a0caa9bcfd5a9498c9f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -125,9 +125,14 @@ - [continuationResult](js-apis-continuation-continuationResult.md) - Common Event and Notification + - [@ohos.commonEventManager (Recommended)](js-apis-commonEventManager.md) - [@ohos.events.emitter](js-apis-emitter.md) + - [@ohos.notificationManager (Recommended)](js-apis-notificationManager.md) + - [@ohos.notificationSubscribe (Recommended)](js-apis-notificationSubscribe.md) + - [@ohos.commonEvent (To Be Deprecated Soon)](js-apis-commonEvent.md) - [@ohos.notification](js-apis-notification.md) - - application/[EventHub](js-apis-inner-application-eventHub.md) + - application + - [EventHub](js-apis-inner-application-eventHub.md) - Bundle Management - [@ohos.bundle.appControl](js-apis-appControl.md) - [@ohos.bundle.bundleManager](js-apis-bundleManager.md) @@ -154,6 +159,8 @@ - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - UI Page - [@ohos.animator](js-apis-animator.md) + - [@ohos.curves](js-apis-curve.md) + - [@ohos.matrix4](js-apis-matrix4.md) - [@ohos.mediaquery](js-apis-mediaquery.md) - [@ohos.promptAction](js-apis-promptAction.md) - [@ohos.router](js-apis-router.md) @@ -187,13 +194,13 @@ - [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - Security - - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - - [@ohos.privacyManager](js-apis-privacyManager.md) - - [@ohos.security.cryptoFramework](js-apis-cryptoFramework.md) - - [@ohos.security.huks ](js-apis-huks.md) - - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) - - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - - [@system.cipher](js-apis-system-cipher.md) + - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) + - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) + - [@ohos.security.cryptoFramework (Crypto Framework)](js-apis-cryptoFramework.md) + - [@ohos.security.huks (HUKS)](js-apis-huks.md) + - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) + - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) + - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - Data Management - [@ohos.data.dataAbility ](js-apis-data-ability.md) - [@ohos.data.dataShare](js-apis-data-dataShare.md) @@ -251,6 +258,8 @@ - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md) + - [@ohos.accessibility.GesturePat](js-apis-accessibility-GesturePath.md) + - [@ohos.accessibility.GesturePoint](js-apis-accessibility-GesturePoint.md) - [@ohos.application.AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md) - [@ohos.faultLogger](js-apis-faultLogger.md) - [@ohos.hichecker](js-apis-hichecker.md) @@ -260,10 +269,11 @@ - [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - [@ohos.hiviewdfx.hiAppEvent](js-apis-hiviewdfx-hiappevent.md) - - [@ohos.inputMethod](js-apis-inputmethod.md) - - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.inputmethod](js-apis-inputmethod.md) + - [@ohos.inputmethodengine](js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) + - [@ohos.inputmethodsubtype](js-apis-inputmethod-subtype.md) - [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) @@ -272,12 +282,15 @@ - [@ohos.web.webview](js-apis-webview.md) - [console](js-apis-logs.md) - [Timer](js-apis-timer.md) - - application/[AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) + - application + - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) - Device Management - [@ohos.batteryInfo ](js-apis-battery-info.md) + - [@ohos.batteryStatistics](js-apis-batteryStatistics.md) - [@ohos.brightness](js-apis-brightness.md) - [@ohos.deviceInfo](js-apis-device-info.md) - [@ohos.distributedHardware.deviceManager](js-apis-device-manager.md) + - [@ohos.geoLocationManager](js-apis-geoLocationManager.md) - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) - [@ohos.multimodalInput.inputDeviceCooperate](js-apis-cooperate.md) @@ -294,6 +307,7 @@ - [@ohos.sensor](js-apis-sensor.md) - [@ohos.settings](js-apis-settings.md) - [@ohos.stationary](js-apis-stationary.md) + - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md) - [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - [@ohos.thermal](js-apis-thermal.md) - [@ohos.update](js-apis-update.md) @@ -305,7 +319,11 @@ - [@ohos.account.osAccount](js-apis-osAccount.md) - Custom Management - [@ohos.configPolicy](js-apis-configPolicy.md) - - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.deviceInfo](js-apis-enterprise-deviceInfo.md) + - [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.adminManager](js-apis-enterprise-adminManager.md) + - [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md) + - Language Base Class Library - [@ohos.buffer](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) diff --git a/en/application-dev/reference/apis/development-intro.md b/en/application-dev/reference/apis/development-intro.md index aaeab2f2961f4254f4bbd8d634ee0f773f996ab4..281fa66969891561b062b7cfd7185d25f7c7f474 100644 --- a/en/application-dev/reference/apis/development-intro.md +++ b/en/application-dev/reference/apis/development-intro.md @@ -9,9 +9,9 @@ In API references, the earliest versions of APIs and components are specified in - For a new API or component, the version information is provided at the beginning of the reference document. Example: "The initial APIs of this module are supported since API version 7." - For a new feature of an existing API or component, a superscript is added following the feature. For example, "uid8+" indicates that the **uid** attribute is supported since API version 8. -## Ability Framework Model Description +## Application Model Description -Ability is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability framework models are classified into the FA model and stage model. For details, see [Ability Framework Overview](../../ability/ability-brief.md). +Along its evolution, OpenHarmony has provided two application models: FA model and stage model. For their differences, see [Interpretation of the Application Model](../../application-models/application-model-description.md). - If all the APIs of a module support only one model, the following description is provided at the beginning of the reference document: "The APIs of this module can be used only in the FA model." or "The APIs of this module can be used only in the stage model." - If certain APIs of a module support only one model, the following description is provided individually for these APIs: "This API can be used only in the FA model." or "This API can be used only in the stage model." @@ -19,18 +19,18 @@ Ability is the minimum unit for the system to schedule applications. An applicat ## Available APIs -Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by non-system applications. +Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by common applications. A description regarding system APIs will be provided in the document. - If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs." - If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API." -Non-system applications are applications whose Ability Privilege Level (APL) is **normal**. The default application level is **normal**. +A common application is an application whose application type is **hos_normal_app** in the HarmonyAppProvision configuration file. **hos_normal_app** is the default value for project creation. -For details about the APL and how to declare the APL of an application higher than **normal**, see [Access Control Overview - App APLs](../../security/accesstoken-overview.md#app-apls). - -The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use system APIs, switch to the full SDK. For details on the operation, see [Guide to Switching to Full SDK](../../quick-start/full-sdk-switch-guide.md). +The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use the system APIs, you must: +- Switch the public SDK to the full SDK by following the instructions provided in [Guide to Switching to Full SDK] (../../quick-start/full-sdk-switch-guide.md). +- Change the value of **app-feature** in the HarmonyAppProvision configuration file to **hos_system_app**. For details, see [HarmonyAppProvision Configuration File](../../security/app-provision-structure.md). ## Permission Description @@ -41,17 +41,19 @@ To call APIs to access these resources, you must apply for the corresponding per - If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx" - If an application can call an API without any permission, no special description is provided. -To determine whether an application can apply for a specific permission, see [Permission List](../../security/permission-list.md). +To determine whether an application can request a specific permission, see [Permission Application and Use](../../security/accesstoken-overview.md#permission-application-and-use). ## System Capability Description -System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SysCap](../../quick-start/syscap.md). +System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SystemCapability](../syscap.md). The following description is provided for each API in the reference document to describe the system capability of the API: "**System capability**: SystemCapability.xxx.xxx" +You can use the [SystemCapability List](../syscap-list.md) to query the devices supported by a specific capability set. + ## Sample Code Language Description OpenHarmony supports two development languages: JS and TS. -- When a code block is labeled with `js`, the sample code can be used in the JS and ArkTS projects. -- When a code block is labeled with `ts`, the sample code can be used only in the ArkTS project. +- When a code block is labeled with **js**, the sample code can be used in the JS and ArkTS projects. +- When a code block is labeled with **ts**, the sample code can be used only in the ArkTS project. diff --git a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md index 108345299ae8e55e185b6d33df259400afe2dada..7b041a216de98edff7ee662ff229c0e16b70470e 100644 --- a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md @@ -1,6 +1,6 @@ # @ohos.ability.dataUriUtils -The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module. +The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module. > **NOTE** > @@ -24,18 +24,18 @@ Obtains the ID attached to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object from which the ID is to be obtained.| +| uri | string | Yes | Target URI object.| **Return value** | Type | Description | | ------ | ------------------------ | -| number | ID obtained from the URI object.| +| number | ID obtained.| **Example** ```ts -dataUriUtils.getId("com.example.dataUriUtils/1221") +let id = dataUriUtils.getId("com.example.dataUriUtils/1221"); ``` @@ -52,7 +52,7 @@ Attaches an ID to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object to which an ID is to be attached.| +| uri | string | Yes | Target URI object.| | id | number | Yes | ID to be attached. | **Return value** @@ -64,10 +64,10 @@ Attaches an ID to the end of a given URI. **Example** ```ts -var idint = 1122; -dataUriUtils.attachId( +let id = 1122; +let uri = dataUriUtils.attachId( "com.example.dataUriUtils", - idint, + id, ) ``` @@ -96,9 +96,11 @@ Deletes the ID from the end of a given URI. **Example** ```ts -dataUriUtils.deleteId("com.example.dataUriUtils/1221") +let uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") ``` + + ## dataUriUtils.updateId updateId(uri: string, id: number): string @@ -111,7 +113,7 @@ Updates the ID in a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------- | -| uri | string | Yes | URI object to be updated.| +| uri | string | Yes | Target URI object.| | id | number | Yes | New ID. | **Return value** @@ -123,9 +125,9 @@ Updates the ID in a given URI. **Example** ```ts -var idint = 1122; -dataUriUtils.updateId( - "com.example.dataUriUtils", - idint +let id = 1122; +let uri = dataUriUtils.updateId( + "com.example.dataUriUtils/1221", + id ) ``` diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index d593cf5a61697773be5837287f0e63d33cff3ce8..ed59083949a8d151e7e007e9b2475d20e91446e6 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -1,4 +1,4 @@ -# Ability Access Control +# @ohos.abilityAccessCtrl (Ability Access Control) The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index 80c507b83ab0012aafbdc9745810730a54997293..6f512b4f9f32904106f9120ea2fcc1095ec732b8 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.appRecovery +# @ohos.app.ability.appRecovery (Application Recovery) -The **appRecovery** module provides APIs for recovering faulty applications. +The **appRecovery** module provides APIs for recovering failed applications. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md index a13e0f73daea27a21a57b6af321dcc9ee8afa038..c7a6f6021594569e01519814160894fff5096c2d 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md @@ -1,6 +1,6 @@ -# ohos.app.ability.dataUriUtils +# @ohos.app.ability.dataUriUtils -The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. +The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. > **NOTE** > @@ -24,13 +24,13 @@ Obtains the ID attached to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object from which the ID is to be obtained.| +| uri | string | Yes | Target URI object.| **Return value** | Type | Description | | ------ | ------------------------ | -| number | ID obtained from the URI object.| +| number | ID obtained.| **Example** @@ -49,7 +49,7 @@ try { attachId(uri: string, id: number): string -Attaches an ID to the end of a given URI. It can be used to generate a new URI. +Attaches an ID to the end of a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -57,7 +57,7 @@ Attaches an ID to the end of a given URI. It can be used to generate a new URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object to which an ID is to be attached.| +| uri | string | Yes | Target URI object.| | id | number | Yes | ID to be attached. | **Return value** @@ -69,11 +69,11 @@ Attaches an ID to the end of a given URI. It can be used to generate a new URI. **Example** ```ts -var idint = 1122; +var id = 1122; try { var uri = dataUriUtils.attachId( "com.example.dataUriUtils", - idint, + id, ) console.info('attachId the uri is: ' + uri) } catch (err) { @@ -130,7 +130,7 @@ Updates the ID in a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------- | -| uri | string | Yes | URI object to be updated.| +| uri | string | Yes | Target URI object.| | id | number | Yes | New ID. | **Return value** @@ -144,10 +144,10 @@ Updates the ID in a given URI. ```ts try { - var idint = 1122; + var id = 1122; var uri = dataUriUtils.updateId( - "com.example.dataUriUtils", - idint + "com.example.dataUriUtils/1221", + id ) } catch (err) { console.error('delete uri err, check the input uri' + err) diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md index 3fb88a2b8ad93d3dbb5adf627f105d117ca86fda..f7203ef5de08d0151d65e2c65cf19b6e3855c1ea 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.errorManager +# @ohos.app.ability.errorManager (Error Manager) -The **ErrorManager** module provides APIs for registering and deregistering error observers. +The **errorManager** module provides APIs for registering and deregistering error observers. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md index bfc8b4f99cf05e7dd20c420b3314b695c880f8d1..3a73d862541383d93b8944d5b57326656ca50b4c 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -1,6 +1,6 @@ # @ohos.app.ability.wantAgent -The **app.ability.WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future. +The **app.ability.WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future. > **NOTE** > @@ -24,7 +24,7 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ----------------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| **Error codes** @@ -43,7 +43,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -54,33 +54,30 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| - **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -92,15 +89,15 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(err)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -119,7 +116,7 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ------------- | ---- | ------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain.| **Return value** @@ -143,7 +140,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -157,28 +154,25 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -217,6 +211,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous | callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). | ID | Error Message | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -231,7 +226,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -245,28 +240,27 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -278,7 +272,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -297,9 +291,9 @@ function getWantAgentCallback(err, data) { console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -342,7 +336,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -356,29 +350,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -390,7 +382,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -405,9 +397,9 @@ function getWantAgentCallback(err, data) { console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -445,7 +437,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -461,26 +453,26 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -492,7 +484,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(err)); @@ -511,9 +503,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -556,7 +548,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -570,29 +562,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent; +// WantAgent object +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -604,7 +594,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -619,9 +609,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -642,11 +632,10 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------- | | agent | WantAgent | Yes | Target **WantAgent** object. | -| callback | AsyncCallback\ | Yes | Callback used to return the want.| +| callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.| **Error codes** For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - | ID | Error Message | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -661,7 +650,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -675,28 +664,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -708,7 +696,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -727,9 +715,9 @@ function getWantAgentCallback(err, data) { console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -774,7 +762,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -788,29 +776,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent; +// WantAgent object +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -822,7 +808,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -837,9 +823,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -877,7 +863,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -891,28 +877,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -924,7 +909,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -943,9 +928,9 @@ function getWantAgentCallback(err, data) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -988,7 +973,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1002,29 +987,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1036,7 +1019,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -1051,17 +1034,13 @@ function getWantAgentCallback(err, data) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` - -//TODO WantAgent.trigger Callback - - ## WantAgent.trigger trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\): void @@ -1075,8 +1054,8 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ----------- | ----------------------------- | ---- | ------------------------------- | | agent | WantAgent | Yes | Target **WantAgent** object. | -| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. | -| callback | AsyncCallback\ | No | Callback used to return the result.| +| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. | +| callback | AsyncCallback\<[CompleteData](#completedata)\> | No | Callback used to return the result.| **Error codes** For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). @@ -1094,7 +1073,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1108,32 +1087,31 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // triggerInfo -var triggerInfo = { - code: 0 +let triggerInfo = { + code: 0 // Custom result code. } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1145,7 +1123,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -1164,9 +1142,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1177,7 +1155,7 @@ try{ equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void -Checks whether two **WantAgent** objects are equal. This API uses an asynchronous callback to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1205,7 +1183,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1219,29 +1197,28 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1253,7 +1230,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent1 = data; wantAgent2 = data; } else { @@ -1273,9 +1250,9 @@ function getWantAgentCallback(err, data) { console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1286,7 +1263,7 @@ try{ equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -Checks whether two **WantAgent** objects are equal. This API uses a promise to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1319,7 +1296,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1333,30 +1310,28 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent1; -var wantAgent2; +// WantAgent object +let wantAgent1; +let wantAgent2; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1368,7 +1343,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent1 = data; wantAgent2 = data; } else { @@ -1384,9 +1359,9 @@ function getWantAgentCallback(err, data) { console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1422,7 +1397,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1436,28 +1411,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1469,7 +1443,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -1488,9 +1462,9 @@ function getWantAgentCallback(err, data) { console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1531,7 +1505,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1545,29 +1519,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent; +// WantAgent object +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1579,7 +1551,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -1594,9 +1566,9 @@ function getWantAgentCallback(err, data) { console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md index 9c374059dc89f8ebdc719597df0afb7c12247d66..1fbb65c4ae5cbe676db6d5ddad5bdacf305df5bb 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -3,6 +3,7 @@ The **Configuration** module defines environment change information. > **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead. @@ -16,7 +17,7 @@ import Configuration from '@ohos.application.Configuration' | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| language8+ | string | Yes| Yes| Language of the application.| +| language8+ | string | Yes| Yes| Language of the application, for example, **zh**.| | colorMode8+ | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| | direction9+ | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| | screenDensity9+ | [ScreenDensity](js-apis-application-configurationConstant.md#configurationconstantscreendensity9) | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| @@ -29,10 +30,10 @@ For details about the fields, see the **ohos.application.Configuration.d.ts** fi ```ts import hilog from '@ohos.hilog'; -import Ability from '@ohos.application.Ability' -import Window from '@ohos.window' +import UIAbility from '@ohos.app.ability.UIAbility'; +import Window from '@ohos.window'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { } diff --git a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md index 863848066791fd23c5811bcc2af027552d8e5991..316244503def8d44c09fb10c7bbe164730239eae 100644 --- a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -18,11 +18,11 @@ You can obtain the value of this constant by calling the **ConfigurationConstant **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| -| COLOR_MODE_DARK | 0 | Dark mode.| -| COLOR_MODE_LIGHT | 1 | Light mode.| +| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| +| COLOR_MODE_DARK | 0 | Dark mode.| +| COLOR_MODE_LIGHT | 1 | Light mode.| ## ConfigurationConstant.Direction9+ @@ -31,11 +31,11 @@ You can obtain the value of this constant by calling the **ConfigurationConstant **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| DIRECTION_NOT_SET | -1 | Unspecified direction.| -| DIRECTION_VERTICAL | 0 | Vertical direction.| -| DIRECTION_HORIZONTAL | 1 | Horizontal direction.| +| DIRECTION_NOT_SET | -1 | Unspecified direction.| +| DIRECTION_VERTICAL | 0 | Vertical direction.| +| DIRECTION_HORIZONTAL | 1 | Horizontal direction.| ## ConfigurationConstant.ScreenDensity9+ @@ -44,12 +44,12 @@ You can obtain the value of this constant by calling the **ConfigurationConstant **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| -| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| -| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| -| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| -| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| -| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| -| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| +| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| +| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| +| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| +| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| +| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| +| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| +| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| diff --git a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index c6192ce1235b2c75607e92788b68fd635dddaffd..9ecffc326e125b6e7dbe0ecd3cf03bfc3d2fa7dd 100644 --- a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -1,6 +1,6 @@ # @ohos.application.DataShareExtensionAbility -The **DataShareExtensionAbility** module provides extension abilities for data share services. +The **DataShareExtensionAbility** module provides data share services based on the Extension ability. >**NOTE** > @@ -17,13 +17,34 @@ The **DataShareExtensionAbility** module provides extension abilities for data s import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** + +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## Attributes **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| +| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| ## onCreate @@ -43,7 +64,7 @@ Called by the server to initialize service logic when the DataShare client conne **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -56,7 +77,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { onCreate(want, callback) { rdb.getRdbStore(this.context, { name: DB_NAME - }, 1, function (err, data) { + }, function (err, data) { console.log('getRdbStore done, data : ' + data); rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { @@ -89,7 +110,7 @@ Inserts data into the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -134,7 +155,7 @@ Updates data in the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -176,7 +197,7 @@ Deletes data from the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -219,7 +240,7 @@ Queries data from the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -264,7 +285,7 @@ Batch inserts data into the database. This API is called by the server and can b **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; diff --git a/en/application-dev/reference/apis/js-apis-application-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md index 5326b582120b6dcbf23a88bedb1ff4dcbe6192ae..b1a98049c70502462a6225a63efd642c164ca60c 100644 --- a/en/application-dev/reference/apis/js-apis-application-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md @@ -1,6 +1,6 @@ -# @ohos.application.errorManager +# @ohos.application.errorManager (Error Manager) -The **ErrorManager** module provides APIs for registering and deregistering error observers. +The **errorManager** module provides APIs for registering and deregistering error observers. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 48be07fbffdadd82f34eb41b6906f4a87a679e89..a992de969d6b6e673b89eff8f14f28f5328ce017 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -2356,10 +2356,6 @@ audioVolumeManager.on('volumeChange', (volumeEvent) => { Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - ### setVolume9+ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index 14e4656758b6ef17f98345767a07d7759a691eda..94ba3b3ca01982070588760ebdd757db7ee8d13b 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -1,14 +1,16 @@ -# AVSession Management +# @ohos.multimedia.avsession (AVSession Management) The **avSession** module provides APIs for media playback control so that applications can access the system's Media Controller. This module provides the following common features related to media sessions: -- [AVSession](#section652893): used to set session metadata, playback state information, and more. -- [AVSessionController](#section974602): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. +- [AVSession](#avsession): used to set session metadata, playback state information, and more. +- [AVSessionController](#avsessioncontroller): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> All the APIs provided by this module are system APIs. ## Modules to Import @@ -28,7 +30,7 @@ Creates a media session. This API uses a promise to return the result. An abilit | Name| Type | Mandatory| Description | | ------ | ------------------------------- | ---- | ------------------------------ | -| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information.| +| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information.| | tag | string | Yes | Custom session name. | | type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video.| @@ -45,7 +47,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -76,7 +78,7 @@ Creates a media session. This API uses an asynchronous callback to return the re | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information. | +| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information. | | tag | string | Yes | Custom session name. | | type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video. | | callback | AsyncCallback<[AVSession](#avsession)\> | Yes | Callback used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| @@ -87,7 +89,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -132,7 +134,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -173,7 +175,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 |Session service exception | +| 6600101 |Session service exception. | **Example** @@ -222,8 +224,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -275,8 +277,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -338,9 +340,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600104 | The remote session connection failed | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600104 | The remote session connection failed. | **Example** @@ -391,9 +393,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600104 | The remote session connection failed | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600104 | The remote session connection failed. | **Example** @@ -443,7 +445,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -492,7 +494,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -523,7 +525,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -554,7 +556,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -592,8 +594,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | **Example** @@ -635,8 +637,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | **Example** @@ -683,9 +685,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** @@ -738,9 +740,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** @@ -770,7 +772,7 @@ avSession.sendSystemControlCommand(avcommand, function (err) { }); ``` -## AVSession +## AVSession An **AVSession** object is created by calling [avSession.createAVSession](#avsessioncreateavsession). The object enables you to obtain the session ID and set the metadata and playback state. @@ -815,8 +817,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -865,8 +867,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -922,8 +924,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -964,8 +966,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -997,9 +999,9 @@ Sets a launcher ability. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | +| ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| **Return value** @@ -1013,8 +1015,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1068,10 +1070,10 @@ Sets a launcher ability. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID. | +| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -1079,8 +1081,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1146,8 +1148,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1181,8 +1183,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1218,8 +1220,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1251,8 +1253,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1286,8 +1288,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1319,8 +1321,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1354,8 +1356,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1389,8 +1391,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1424,8 +1426,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1458,8 +1460,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1494,8 +1496,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1544,8 +1546,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** The session does not exist @@ -1576,8 +1578,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1608,8 +1610,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1640,8 +1642,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1672,8 +1674,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1704,8 +1706,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1736,8 +1738,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1772,8 +1774,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1802,8 +1804,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1832,8 +1834,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1862,8 +1864,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1892,8 +1894,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1922,8 +1924,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1933,7 +1935,7 @@ session.off('outputDeviceChange'); -## AVSessionController +## AVSessionController An AV session controller is created by calling [avSession.createController](#avsessioncreatecontroller). Through the AV session controller, you can query the session ID, send commands and events to a session, and obtain session metadata and playback state information. @@ -1977,9 +1979,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2010,9 +2012,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2045,9 +2047,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2078,9 +2080,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2113,8 +2115,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2145,8 +2147,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2180,11 +2182,11 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | **Return value** @@ -2218,7 +2220,7 @@ Sends a key event to the session corresponding to this controller. This API uses | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------- | | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** @@ -2226,11 +2228,11 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | **Example** @@ -2257,9 +2259,9 @@ Obtains the **WantAgent** object saved by the application in the session. This A **Return value** -| Type | Description | -| ------------------------------------------- | ------------------------------------------------------------ | -| Promise<[WantAgent](js-apis-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| +| Type | Description | +| ------------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** @@ -2267,9 +2269,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2293,9 +2295,9 @@ Obtains the **WantAgent** object saved by the application in the session. This A **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[WantAgent](js-apis-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** @@ -2303,9 +2305,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2341,8 +2343,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2370,9 +2372,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2404,9 +2406,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2440,8 +2442,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2473,8 +2475,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2508,9 +2510,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2542,9 +2544,9 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2584,12 +2586,12 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | **Example** @@ -2633,12 +2635,12 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | **Example** @@ -2685,8 +2687,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2723,8 +2725,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2760,8 +2762,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2792,8 +2794,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ----------------------------- | -| 6600101 | Session service exception | -| 6600103 |The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 |The session controller does not exist. | **Example** @@ -2824,8 +2826,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2857,8 +2859,8 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ----------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2889,7 +2891,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2918,7 +2920,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2947,7 +2949,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2976,7 +2978,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3005,7 +3007,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID| Error Message | | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3034,7 +3036,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err | ID | Error Message | | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3132,7 +3134,7 @@ Describes the media metadata. | album | string | No | Album name. | | writer | string | No | Writer. | | composer | string | No | composer. | -| duration | string | No | Media duration, in ms. | +| duration | number | No | Media duration, in ms. | | mediaImage | image.PixelMap | string | No | Pixel map or image path (local path or network path) of the image. | | publishDate | Date | No | Release date. | | subtitle | string | No | Subtitle. | @@ -3217,10 +3219,10 @@ Enumerates the error codes used in the media session. | Name | Value | Description | | ------------------------------ | ------- | ------------------------------- | -| ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception | -| ERR_CODE_SESSION_NOT_EXIST | 6600102 | The session does not exist | -| ERR_CODE_CONTROLLER_NOT_EXIST | 6600103 | The session controller does not exist | -| ERR_CODE_REMOTE_CONNECTION_ERR | 6600104 | The remote session connection failed | -| ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command | -| ERR_CODE_SESSION_INACTIVE | 6600106 | The session not active | -| ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Command or event overload | +| ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception. | +| ERR_CODE_SESSION_NOT_EXIST | 6600102 | The session does not exist. | +| ERR_CODE_CONTROLLER_NOT_EXIST | 6600103 | The session controller does not exist. | +| ERR_CODE_REMOTE_CONNECTION_ERR | 6600104 | The remote session connection failed. | +| ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command. | +| ERR_CODE_SESSION_INACTIVE | 6600106 | The session is not activated. | +| ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Too many commands or events. | diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 197e25cfce48edc49798b438745adc13c35ab9d5..41d13ba5741ecf4324b1f4c859fb2a0a4bdf1d19 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,11 +1,10 @@ -# Battery Info +# @ohos.batteryInfo (Battery Information) -The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. +The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```js diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md index 917bc81d2f3eecef3f25d609db686b0d9dae44a2..2bb3159fc3912a6a1fe272451ce31aa812052432 100644 --- a/en/application-dev/reference/apis/js-apis-batteryStatistics.md +++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -1,6 +1,6 @@ -# Battery Statistics +# @ohos.batteryStatistics (Battery Statistics) -This module provides APIs for querying software and hardware power consumption statistics. +The **batteryStatistics** module provides APIs for querying software and hardware power consumption statistics. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index df783bbda132f5da29e152e146cc6cb56316f083..bd003733a485c1601ac251697461e78b863976a8 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -1,6 +1,6 @@ -# Screen Brightness +# @ohos.brightness (Screen Brightness) -The Brightness module provides an API for setting the screen brightness. +The **brightness** module provides an API for setting the screen brightness. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index 525f882052397b5d59e5d4a22c79dc013c847e6a..3dab120c4667c563047b5cc48da6ed378e4a29aa 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -3,16 +3,18 @@ The **bundleManager** module provides APIs for querying information about bundles, applications, abilities, Extension abilities, and more. > **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; ``` + ## Required Permissions -| Required Permissions | Permission Level | Description | +| Permission | Permission Level | Description | | ------------------------------------------ | ------------ | ------------------| | 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.| @@ -184,7 +186,7 @@ Enumerates the display orientations of the ability. This attribute applies only | AUTO_ROTATION_PORTRAIT_RESTRICTED |11|Switched-determined auto rotation in the vertical direction.| | LOCKED |12|Locked.| -## Methods +## APIs ### bundleManager.getBundleInfoForSelf @@ -209,16 +211,17 @@ Obtains the bundle information of this bundle based on the given bundle flags. T **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { - console.info('getBundleInfoForSelf successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfoForSelf failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfoForSelf failed:' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } ``` @@ -240,19 +243,20 @@ Obtains the bundle information of this bundle based on the given bundle flags. T **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfoForSelf(bundleFlags, (err, data) => { if (err) { - console.error('getBundleInfoForSelf failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } else { - console.info('getBundleInfoForSelf successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfoForSelf failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } ``` @@ -262,6 +266,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, userId: number, callback: Obtains the bundle information based on the given bundle name, bundle flags, and user ID. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -272,7 +278,7 @@ Obtains the bundle information based on the given bundle name, bundle flags, and | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| | userId | number | Yes | User ID. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the bundle information obtained. Otherwise, **err** is an error object.| @@ -291,7 +297,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the ability information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_ABILITY; let userId = 100; @@ -299,19 +306,20 @@ let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` ```ts // Obtain the bundle information with the metadata in the application information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA; let userId = 100; @@ -319,13 +327,13 @@ let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` @@ -335,6 +343,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\< Obtains the bundle information based on the given bundle name and bundle flags. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -345,7 +355,7 @@ Obtains the bundle information based on the given bundle name and bundle flags. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| | callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the bundle information obtained. Otherwise, **err** is an error object.| @@ -363,20 +373,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the Extension ability information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY; try { bundleManager.getBundleInfo(bundleName, bundleFlags, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` @@ -386,6 +397,8 @@ getBundleInfo(bundleName: string, bundleFlags: [number](#bundleflag), userId?: n Obtains the bundle information based on the given bundle name, bundle flags, and user ID. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -420,35 +433,37 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the application and signature information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO; let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId).then((data) => { - console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfo(bundleName, bundleFlags).then((data) => { - console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); } ``` @@ -459,6 +474,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), use Obtains the application information based on the given bundle name, application flags, and user ID. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -487,7 +504,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; @@ -495,13 +513,13 @@ let userId = 100; try { bundleManager.getApplicationInfo(bundleName, appFlags, userId, (err, data) => { if (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } else { - console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } ``` @@ -511,6 +529,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), cal Obtains the application information based on the given bundle name and application flags. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -538,20 +558,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; try { bundleManager.getApplicationInfo(bundleName, appFlags, (err, data) => { if (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } else { - console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } ``` @@ -561,6 +582,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), use Obtains the application information based on the given bundle name, application flags, and user ID. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -594,19 +617,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; let userId = 100; try { bundleManager.getApplicationInfo(bundleName, appFlags, userId).then((data) => { - console.info('getApplicationInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getApplicationInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getApplicationInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed. Cause: %{public}s', err.message); } ``` @@ -614,7 +638,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), userId: number, callback: AsyncCallback>): void; -Obtains an array of bundle information based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. +Obtains the information about all bundles based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -641,20 +665,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; let userId = 100; try { bundleManager.getAllBundleInfo(bundleFlags, userId, (err, data) => { if (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } else { - console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } ``` @@ -662,7 +687,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), callback: AsyncCallback>): void; -Obtains an array of bundle information based on the given bundle flags. This API uses an asynchronous callback to return the result. +Obtains the information about all bundles based on the given bundle flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -688,19 +713,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getAllBundleInfo(bundleFlags, (err, data) => { if (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } else { - console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } ``` @@ -708,7 +734,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), userId?: number): Promise>; -Obtains an array of bundle information based on the given bundle flags and user ID. This API uses a promise to return the result. +Obtains the information about all bundles based on the given bundle flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -740,17 +766,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getAllBundleInfo(bundleFlags).then((data) => { - console.info('getAllBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAllBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAllBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed. Cause: %{public}s', err.message); } ``` @@ -758,7 +785,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), userId: number, callback: AsyncCallback>): void; -Obtains an array of application information based on the given application flags and user ID. This API uses an asynchronous callback to return the result. +Obtains the information about all applications based on the given application flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -785,20 +812,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; try { bundleManager.getAllApplicationInfo(appFlags, userId, (err, data) => { if (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } else { - console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } ``` @@ -806,7 +834,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), callback: AsyncCallback>): void; -Obtains an array of application information based on the given application flags. This API uses an asynchronous callback to return the result. +Obtains the information about all applications based on the given application flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -832,19 +860,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { bundleManager.getAllApplicationInfo(appFlags, (err, data) => { if (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } else { - console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } ``` @@ -852,7 +881,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), userId?: number): Promise>; -Obtains an array of application information based on the given application flags and user ID. This API uses a promise to return the result. +Obtains the information about all applications based on the given application flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -884,17 +913,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { bundleManager.getAllApplicationInfo(appFlags).then((data) => { - console.info('getAllApplicationInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAllApplicationInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAllApplicationInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed. Cause: %{public}s', err.message); } ``` @@ -915,7 +945,7 @@ Obtains an array of ability information based on the given want, ability flags, | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ------------------------------------------------------- | -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain. | | userId | number | Yes | User ID. | | callback | AsyncCallback> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of ability information obtained. Otherwise, **err** is an error object.| @@ -935,24 +965,25 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId, (err, data) => { if (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } ``` @@ -972,7 +1003,7 @@ Obtains an array of ability information based on the given want and ability flag | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | -------------------------------------------------------| -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain. | | callback | AsyncCallback> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of ability information obtained. Otherwise, **err** is an error object.| @@ -991,23 +1022,24 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, (err, data) => { if (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } ``` @@ -1027,7 +1059,7 @@ Obtains the ability information based on the given want, ability flags, and user | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ------------------------------------------------------- | -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain.| | userId | number | No | User ID. | @@ -1052,41 +1084,43 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((data) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags).then((data) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }) -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1106,10 +1140,10 @@ Obtains the Extension ability information based on the given want, Extension abi | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want containing the bundle name to query. | -| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | -| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | -| userId | number | Yes | User ID. | +| want | Want | Yes | Want containing the bundle name to query. | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | +| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | +| userId | number | Yes | User ID. | | callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of Extension ability information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -1126,25 +1160,26 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId, (err, data) => { if (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } ``` @@ -1164,9 +1199,9 @@ Obtains the Extension ability information based on the given want, Extension abi | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want containing the bundle name to query. | -| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | -| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | +| want | Want | Yes | Want containing the bundle name to query. | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | +| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | | callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of Extension ability information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -1183,24 +1218,25 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, (err, data) => { if (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } ``` @@ -1218,8 +1254,8 @@ Obtains the Extension ability information based on the given want, Extension abi **Parameters** -| Name | Type | Mandatory| Description | -| --------------------- | --------------------------------------------- | ---- | ------------------------------------------------------- | +| Name | Type | Mandatory| Description | +| --------------------- | --------------------------------------------- | ---- | --------------------------------------------------------- | | want | Want | Yes | Want containing the bundle name to query. | | extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | | extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain.| @@ -1245,44 +1281,46 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId).then((data) => { - console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags).then((data) => { - console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); }) -} catch (error) { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1316,18 +1354,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let uid = 20010005; try { bundleManager.getBundleNameByUid(uid, (err, data) => { if (err) { - console.error('getBundleNameByUid failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed: %{public}s', err.message); } else { - console.info('getBundleNameByUid successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleNameByUid successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleNameByUid failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed: %{public}s', err.message); } ``` @@ -1366,16 +1405,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let uid = 20010005; try { bundleManager.getBundleNameByUid(uid).then((data) => { - console.info('getBundleNameByUid successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleNameByUid failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleNameByUid successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleNameByUid failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed. Cause: %{public}s', err.message); } ``` @@ -1410,20 +1450,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let hapFilePath = "/data/xxx/test.hap"; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { if (err) { - console.error('getBundleArchiveInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } else { - console.info('getBundleArchiveInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleArchiveInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleArchiveInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } ``` @@ -1463,18 +1504,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let hapFilePath = "/data/xxx/test.hap"; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags).then((data) => { - console.info('getBundleArchiveInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleArchiveInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleArchiveInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleArchiveInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } ``` @@ -1482,7 +1524,7 @@ try { cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\): void; -Clears cache files of a bundle. This API uses an asynchronous callback to return the result. +Clears the cache files based on the given bundle name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1509,19 +1551,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { bundleManager.cleanBundleCacheFiles(bundleName, err => { if (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } else { - console.info('cleanBundleCacheFiles successfully.'); + hilog.info(0x0000, 'testTag', 'cleanBundleCacheFiles successfully.'); } }); } catch (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } ``` @@ -1529,7 +1572,7 @@ try { cleanBundleCacheFiles(bundleName: string): Promise\; -Clears cache files of a bundle. This API uses a promise to return the result. +Clears the cache files based on the given bundle name. This API uses a promise to return the result. **System API**: This is a system API. @@ -1547,7 +1590,7 @@ Clears cache files of a bundle. This API uses a promise to return the result. | Type | Description | | -------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| +| Promise\ | Promise that returns no value. If clearing the cache files fails, an error object is thrown.| **Error codes** @@ -1561,17 +1604,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { - bundleManager.cleanBundleCacheFiles(bundleName).then(()=> { - console.info('cleanBundleCacheFiles successfully.'); - }).catch(err=> { - console.error('cleanBundleCacheFiles failed:' + err.message); + bundleManager.cleanBundleCacheFiles(bundleName).then(() => { + hilog.info(0x0000, 'testTag', 'cleanBundleCacheFiles successfully.'); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); }); } catch (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } ``` @@ -1606,19 +1650,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { bundleManager.setApplicationEnabled(bundleName, false, err => { if (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } else { - console.info('setApplicationEnabled successfully.'); + hilog.info(0x0000, 'testTag', 'setApplicationEnabled successfully.'); } }); } catch (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1658,17 +1703,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { - bundleManager.setApplicationEnabled(bundleName, false).then(()=> { - console.info('setApplicationEnabled successfully.'); - }).catch(err=> { - console.error('setApplicationEnabled failed:' + err.message); + bundleManager.setApplicationEnabled(bundleName, false).then(() => { + hilog.info(0x0000, "testTag", "setApplicationEnabled successfully."); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); }); } catch (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1689,7 +1735,7 @@ Enables or disables an ability. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means to disable the application.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -1704,32 +1750,33 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.setAbilityEnabled(info, false, err => { if (err) { - console.error('setAbilityEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setAbilityEnabled failed: %{public}s', err.message); } else { - console.info('setAbilityEnabled successfully.'); + hilog.info(0x0001, "testTag", "setAbilityEnabled successfully."); } }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1750,7 +1797,7 @@ Enables or disables an ability. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means to disable the application.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| **Return value** @@ -1770,30 +1817,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; - bundleManager.setAbilityEnabled(info, false).then(()=> { - console.info('setAbilityEnabled successfully.'); - }).catch(err=> { - console.error('setAbilityEnabled failed:' + err.message); + bundleManager.setAbilityEnabled(info, false).then(() => { + hilog.info(0x0000, "testTag", "setAbilityEnabled successfully."); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'setAbilityEnabled failed: %{public}s', err.message); }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1825,19 +1873,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.isApplicationEnabled(bundleName, (err, data) => { if (err) { - console.error('isApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed: %{public}s', err.message); } else { - console.info('isApplicationEnabled successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isApplicationEnabled successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('isApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1874,17 +1923,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.isApplicationEnabled(bundleName).then((data) => { - console.info('isApplicationEnabled successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('isApplicationEnabled failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'isApplicationEnabled successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('isApplicationEnabled failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed. Cause: %{public}s', err.message); } ``` @@ -1917,32 +1967,33 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.isAbilityEnabled(info, (err, data) => { if (err) { - console.error('isAbilityEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isAbilityEnabled failed: %{public}s', err.message); } else { - console.info('isAbilityEnabled successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isAbilityEnabled successfully: %{public}s', JSON.stringify(data)); } }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1980,30 +2031,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.isAbilityEnabled(info).then((data) => { - console.info('isAbilityEnabled successfully. Data: ' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isAbilityEnabled successfully. Data: %{public}s', JSON.stringify(data)); }).catch(err => { - console.error('isAbilityEnabled failed. Cause: ' + err.message); + hilog.error(0x0000, 'testTag', 'isAbilityEnabled failed. Cause: %{public}s', err.message); }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -2011,7 +2063,7 @@ try { getLaunchWantForBundle(bundleName: string, userId: number, callback: AsyncCallback\): void; -Obtains the want used to launch the bundle based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. +Obtains the Want used to launch the bundle based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2040,20 +2092,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let userId = 100; try { bundleManager.getLaunchWantForBundle(bundleName, userId, (err, data) => { if (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } else { - console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } ``` @@ -2061,7 +2114,7 @@ try { getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; -Obtains the want used to launch the bundle based on the given bundle name. This API uses an asynchronous callback to return the result. +Obtains the Want used to launch the bundle based on the given bundle name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2089,19 +2142,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.getLaunchWantForBundle(bundleName, (err, data) => { if (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } else { - console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } ``` @@ -2109,7 +2163,7 @@ try { getLaunchWantForBundle(bundleName: string, userId?: number): Promise\; -Obtains the want used to launch the bundle based on the given bundle name and user ID. This API uses a promise to return the result. +Obtains the Want used to launch the bundle based on the given bundle name and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -2143,18 +2197,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let userId = 100; try { bundleManager.getLaunchWantForBundle(bundleName, userId).then((data) => { - console.info('getLaunchWantForBundle successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getLaunchWantForBundle failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getLaunchWantForBundle failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed. Cause: %{public}s', err.message); } ``` @@ -2190,21 +2245,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByAbility(moduleName, abilityName, metadataName, (err, data) => { if (err) { - console.error('getProfileByAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } else { - console.info('getProfileByAbility successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getProfileByAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` @@ -2245,34 +2301,36 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getProfileByAbility(moduleName, abilityName).then((data) => { - console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByAbility(moduleName, abilityName, metadataName).then((data) => { - console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` @@ -2307,7 +2365,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; let extensionAbilityName = 'com.example.myapplication.extension'; let metadataName = 'com.example.myapplication.metadata'; @@ -2315,13 +2374,13 @@ let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName, (err, data) => { if (err) { - console.error('getProfileByExtensionAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed: %{public}s', err.message); } else { - console.info('getProfileByExtensionAbility successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getProfileByExtensionAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed: %{public}s', err.message); } ``` @@ -2361,29 +2420,30 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; let extensionAbilityName = 'com.example.myapplication.extension'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName).then((data) => { - console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); } try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName).then((data) => { - console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); } ``` @@ -2391,7 +2451,7 @@ try { getPermissionDef(permissionName: string, callback: AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>): void; -Obtains the details of a permission. This API uses an asynchronous callback to return the result. +Obtains the details of a permission in the form of a **PermissionDef** struct. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2417,18 +2477,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let permission = "ohos.permission.GET_BUNDLE_INFO"; try { bundleManager.getPermissionDef(permission, (err, data) => { if (err) { - console.error('getPermissionDef failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getPermissionDef failed: %{public}s', err.message); } else { - console.info('getPermissionDef successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getPermissionDef successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getPermissionDef failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getPermissionDef failed: %{public}s', err.message); } ``` @@ -2436,7 +2497,7 @@ try { getPermissionDef(permissionName: string): Promise\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>; -Obtains the details of a permission. This API uses a promise to return the result. +Obtains the details of a permission in the form of a **PermissionDef** struct. This API uses a promise to return the result. **System API**: This is a system API. @@ -2467,16 +2528,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let permissionName = "ohos.permission.GET_BUNDLE_INFO"; try { bundleManager.getPermissionDef(permissionName).then((data) => { - console.info('getPermissionDef successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getPermissionDef failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getPermissionDef successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getPermissionDef failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getPermissionDef failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getPermissionDef failed. Cause: %{public}s', err.message); } ``` @@ -2516,21 +2578,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityLabel(bundleName, moduleName, abilityName, (err, data) => { if (err) { - console.error('getAbilityLabel failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed: %{public}s', err.message); } else { - console.info('getAbilityLabel successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAbilityLabel successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAbilityLabel failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed: %{public}s', err.message); } ``` @@ -2575,19 +2638,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityLabel(bundleName, moduleName, abilityName).then((data) => { - console.info('getAbilityLabel successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAbilityLabel failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAbilityLabel successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAbilityLabel failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed. Cause: %{public}s', err.message); } ``` @@ -2627,21 +2691,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityIcon(bundleName, moduleName, abilityName, (err, data) => { if (err) { - console.error('getAbilityIcon failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); } else { - console.info('getAbilityIcon successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAbilityIcon failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); } ``` @@ -2686,19 +2751,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityIcon(bundleName, moduleName, abilityName).then((data) => { - console.info('getAbilityIcon successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAbilityIcon failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAbilityIcon failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); } ``` @@ -2720,7 +2786,7 @@ Synchronously obtains the application information based on the given bundle name | ----------- | ------ | ---- | ----------------------------------------------------------| | bundleName | string | Yes | Bundle name. | | applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain. | -| userId | number | Yes | User ID. | +| userId | number | No | User ID. | **Return value** @@ -2741,65 +2807,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; try { let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags, userId); - console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getApplicationInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfoSync failed: %{public}s', err.message); } ``` -### bundleManager.getApplicationInfoSync - -getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); - -Synchronously obtains the application information based on the given bundle name and application flags. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO - -**System capability**: SystemCapability.BundleManager.BundleFramework.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------------------------------------------| -| bundleName | string | Yes | Bundle name. | -| applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain. | - -**Return value** - -| Type | Description | -| --------------- | ------------------------- | -| [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Application information obtained.| - -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - -| ID| Error Message | -| -------- | -------------------------------------- | -| 17700001 | The specified bundleName is not found. | -| 17700026 | The specified bundle is disabled. | - -**Example** - ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags); - console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getApplicationInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfoSync failed: %{public}s', err.message); } ``` @@ -2821,7 +2853,7 @@ Synchronously obtains the bundle information based on the given bundle name, bun | ----------- | ------ | ---- | -------------------------------------------------------- | | bundleName | string | Yes | Bundle name. | | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| -| userId | number | Yes | User ID. | +| userId | number | No | User ID. | **Return value** @@ -2842,66 +2874,29 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; let userId = 100; try { let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags, userId); - console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getBundleInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` -### bundleManager.getBundleInfoSync - -getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); - -Synchronously obtains the bundle information based on the given bundle name and bundle flags. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO - -**System capability**: SystemCapability.BundleManager.BundleFramework.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| - -**Return value** - -| Type | Description | -| ---------- | -------------------- | -| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | Bundle information obtained.| - -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - -| ID| Error Message | -| -------- | ------------------------------------- | -| 17700001 | The specified bundleName is not found. | -| 17700004 | The specified user ID is not found. | -| 17700026 | The specified bundle is disabled. | - -**Example** - ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; try { let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags); - console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getBundleInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 544a4ba0d27e6c39794e063fc63282ba5455bf5e..89e14f7ad3e4fb3f525ccd9d5aab83b56e8c6521 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -1,4 +1,4 @@ -# Performance Tracing +# @ohos.bytrace (Performance Tracing) > **NOTE** > - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 7c5bd52bd9ccbc5ee7ad99b8a1e7311ce8c5f8d5..0ccd49a5dc2a8b8e3577b7614f8219573de7cf7d 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -1,6 +1,6 @@ -# Call +# @ohos.telephony.call (Call) -The call module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. +The **call** module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-observer.md#observeroncallstatechange). diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index baf10a887589617bee09f1a3220c70dd1b6d6cdb..cb1311397a52d39e41466c33135bdc93164a0807 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -1,4 +1,4 @@ -# Camera Management +# @ohos.multimedia.camera (Camera Management) > **NOTE** > @@ -22,7 +22,7 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ---------------------------- | -| context | [Context](../../ability/context-userguide.md) | Yes | Application context. | +| context | [Context](js-apis-inner-app-context.md) | Yes | Application context. | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | Yes | Callback used to return the **CameraManager** instance.| **Example** @@ -49,7 +49,7 @@ Obtains a **CameraManager** instance. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ------- | ---- | ------------ | -| context | [Context](../../ability/context-userguide.md) | Yes | Application context.| +| context | [Context](js-apis-inner-app-context.md) | Yes | Application context.| **Return value** @@ -757,7 +757,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | --------- | | type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status change event.| -| callback | AsyncCallback | Yes | Callback used to return the camera mute status. | +| callback | AsyncCallback\ | Yes | Callback used to return the camera mute status. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index a166781108683f6b6fb53673da4deacd99882b26..2778a143c65125eca650324e67a220ab60f64ead 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -1,4 +1,4 @@ -# Contacts +# @ohos.contact (Contacts) >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md index cfbfb83e3359a4b7d41cf6ab039d0c1f0552c9eb..89ddd643d07a9882e289b27ff9fd0cc6679fd187 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @@ -1,6 +1,6 @@ # ContinuationExtraParams -The **ContinuationExtraParams** module provides the extra parameters required by the device selection module in the continuation management entry. +The **ContinuationExtraParams** module provides the filter parameters required by the device selection module in the continuation management entry. These filter parameters can be used as an input parameter of [startContinuationDeviceManager](js-apis-continuation-continuationManager.md#continuationmanagerstartcontinuationdevicemanager9). > **NOTE** > @@ -15,7 +15,7 @@ Describes the extra parameters required by the device selection module in the co | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | deviceType | Array\ | Yes| Yes| Device type.| -| targetBundle | string | Yes| Yes| Target bundle name.| +| targetBundle | string | Yes| Yes| Name of the target bundle.| | description | string | Yes| Yes| Device filtering description.| | filter | any | Yes| Yes| Device filtering parameter.| | continuationMode | [ContinuationMode](js-apis-continuation-continuationManager.md#continuationmode) | Yes| Yes| Continuation mode.| diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md index 48bf6c24db78efa7b41219c879d994223a5d43ce..05f490c454f7e7133bfc5977d1bdc2d180462a7c 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -1,4 +1,4 @@ -# continuationManager +# @ohos.continuation.continuationManager (continuationManager) The **continuationManager** module provides the continuation management entry. You can use the APIs of this module to connect to and cancel the continuation management service, subscribe to and unsubscribe from device connection events, start the device selection module, and update the device connection state. diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md index bdebb727ff7b5c6b41868f37bf5ecdb0ea333d10..0e0bd18e5e4a5d2abafcdbdf82b17f88a23357cd 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md @@ -6,7 +6,7 @@ ## ContinuationResult -Describes the device information returned by the continuation management entry. +Describes the device information returned by the continuation management entry after [on](js-apis-continuation-continuationManager.md#continuationmanagerstartcontinuationdevicemanager9) is called. **System capability**: SystemCapability.Ability.DistributedAbilityManager diff --git a/en/application-dev/reference/apis/js-apis-cooperate.md b/en/application-dev/reference/apis/js-apis-cooperate.md index 3ed0e77078376df038d327d8edb53f3022ebe7d7..d63729a9dcf6a08133dd28f7cdabc6e63f0a4b6e 100644 --- a/en/application-dev/reference/apis/js-apis-cooperate.md +++ b/en/application-dev/reference/apis/js-apis-cooperate.md @@ -1,11 +1,11 @@ -# Screen Hopping +# @ohos.multimodalInput.inputDeviceCooperate (Screen Hopping) -The Screen Hopping module enables two or more networked devices to share the keyboard and mouse for collaborative operations. +The **inputDeviceCooperate** module enables two or more networked devices to share the keyboard and mouse for collaborative operations. > **NOTE** > > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs provided by this module are system APIs. +> - The APIs provided by this module are system APIs. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md index 11b95aa03d0135d811ee21f9e672ad1798d23b5c..2c90472a98a38d74e7211eb8dcef2061082f18c8 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -1,6 +1,6 @@ -# Interpolation Calculation +# @ohos.curves -The **Curves** module provides APIs for interpolation calculation to construct step, cubic Bezier, and spring curve objects. +The **Curves** module provides APIs for interpolation calculation to create step, cubic Bezier, and spring curves. > **NOTE** > @@ -19,7 +19,7 @@ import Curves from '@ohos.curves' initCurve(curve?: Curve): ICurve -Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. +Implements initialization for the interpolation curve, which is used to create an interpolation curve based on the input parameter. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -33,7 +33,7 @@ Implements initialization for the interpolation curve, which is used to create a | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| +| [ICurve](#icurve) | Interpolation curve.| **Example** @@ -49,7 +49,7 @@ Curves.initCurve(Curve.EaseIn) // Create a default ease-in curve, where the inte stepsCurve(count: number, end: boolean): ICurve -Constructs a step curve object. +Creates a step curve. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -64,7 +64,7 @@ Constructs a step curve object. | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| +| [ICurve](#icurve) | Interpolation curve.| **Example** @@ -80,7 +80,7 @@ Curves.stepsCurve(9, true) // Create a step curve. cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve -Constructs a cubic Bezier curve object. The curve values must be between 0 and 1. +Creates a cubic Bezier curve. The curve values must be between 0 and 1. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -96,7 +96,7 @@ Constructs a cubic Bezier curve object. The curve values must be between 0 and 1 | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| +| [ICurve](#icurve) | Interpolation curve.| **Example** @@ -112,7 +112,7 @@ Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve -Constructs a spring curve object. +Creates a spring curve. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -120,7 +120,7 @@ Constructs a spring curve object. | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ----- | | velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| -| mass | number | Yes | Mass. Force object of the elastic system, which will have inertia effect on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| +| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| | stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| | damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| @@ -129,7 +129,7 @@ Constructs a spring curve object. | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve object.| +| [ICurve](#icurve)| Interpolation curve.| **Example** @@ -140,6 +140,68 @@ Curves.springCurve(100, 1, 228, 30) // Create a spring curve. ``` +## Curves.springMotion9+ + +springMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve + +Creates a spring animation curve. If multiple spring animations are applied to the same attribute of an object, each animation replaces their predecessor and inherits the velocity. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| response | number | No | Duration of one complete oscillation, in seconds.
Default value: **0.55**| +| dampingFraction | number | No | Damping coefficient.
**0**: undamped. In this case, the spring oscillates forever.
> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.
**1**: critically damped.
> 1: overdamped. In this case, the spring approaches equilibrium gradually.
Default value: **0.825**| +| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.
Default value: **0**| + + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve)| Curve.
Note: The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.springMotion() // Create a spring animation curve with default settings. +Curves.springMotion(0.5) // Create a spring animation curve with the specified response value. +Curves.springMotion (0.5, 0.6) // Create a spring animation curve with the specified response and dampingFraction values. +Curves.springMotion(0.5, 0.6, 0) // Create a spring animation curve with the specified parameter values. +``` + + +## Curves.responsiveSpringMotion9+ + +responsiveSpringMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve + +Creates a responsive spring animation curve. It is a special case of [springMotion](#curvesspringmotion9), with the only difference in the default values. It can be used together with **springMotion**. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| response | number | No | See **response** in **springMotion**. Default value: **0.15**| +| dampingFraction | number | No | See **dampingFraction** in **springMotion**. Default value: **0.86**| +| overlapDuration | number | No | See **overlapDuration** in **springMotion**. Default value: **0.25**| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve)| Curve.
**NOTE**
1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.responsiveSpringMotion() // Create a responsive spring animation curve with default settings. +``` + + ## ICurve @@ -194,7 +256,7 @@ Implements initialization to create a curve. This API is deprecated since API ve steps(count: number, end: boolean): string -Constructs a step curve object. This API is deprecated since API version 9. You are advised to use [Curves.stepsCurve](#curvesstepscurve9) instead. +Creates a step curve. This API is deprecated since API version 9. You are advised to use [Curves.stepsCurve](#curvesstepscurve9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -211,7 +273,7 @@ Constructs a step curve object. This API is deprecated since API version 9. You cubicBezier(x1: number, y1: number, x2: number, y2: number): string -Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. This API is deprecated since API version 9. You are advised to use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. +Creates a cubic Bezier curve. The curve value must range from 0 to 1. This API is deprecated since API version 9. You are advised to use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -229,7 +291,7 @@ Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. spring(velocity: number, mass: number, stiffness: number, damping: number): string -Constructs a spring curve object. This API is deprecated since API version 9. You are advised to use [Curves.springCurve](#curvesspringcurve9) instead. +Creates a spring curve. This API is deprecated since API version 9. You are advised to use [Curves.springCurve](#curvesspringcurve9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -238,7 +300,7 @@ Constructs a spring curve object. This API is deprecated since API version 9. Yo | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ----- | | velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| -| mass | number | Yes | Mass. Force object of the elastic system, which will have inertia effect on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| +| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| | stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| | damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| @@ -247,6 +309,7 @@ Constructs a spring curve object. This API is deprecated since API version 9. Yo ```ts // xxx.ets import Curves from '@ohos.curves' + @Entry @Component struct ImageComponent { @@ -256,16 +319,16 @@ struct ImageComponent { build() { Column() { Text() - .margin({top:100}) + .margin({ top: 100 }) .width(this.widthSize) .height(this.heightSize) .backgroundColor(Color.Red) - .onClick(()=> { + .onClick(() => { let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0); this.widthSize = curve.interpolate(0.5) * this.widthSize; this.heightSize = curve.interpolate(0.5) * this.heightSize; }) - .animation({duration: 2000 , curve: Curves.stepsCurve(9, true)}) + .animation({ duration: 2000, curve: Curves.stepsCurve(9, true) }) }.width("100%").height("100%") } } diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 5fedece20aac3dc30e68020964be1fbca1cefdfa..ccc1f7b4e26c0cbc6556f2ea767c5601ac3a477e 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,4 +1,4 @@ -# Data Share Result Set +# @ohos.data.dataShareResultSet The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index a5f16c8c04d650608231c4757224c662c23bf387..2a476aaf33cc927b8c0ec5c392a083b6b42c8f80 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,4 +1,4 @@ -# Data Sharing +# @ohos.data.dataShare The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. @@ -17,6 +17,26 @@ The **DataShare** module allows an application to manage its own data and share import dataShare from '@ohos.data.dataShare' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## dataShare.createDataShareHelper @@ -24,6 +44,11 @@ createDataShareHelper(context: Context, uri: string, callback: AsyncCallback< Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -34,21 +59,33 @@ Creates a **DataShareHelper** instance. This API uses an asynchronous callback t | uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri, (err, data) => { - if (err != undefined) { - console.info("createDataShareHelper failed, error message : " + err); - } else { +try { + dataShare.createDataShareHelper(this.context, uri, (err, data) => { + if (err != undefined) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + return; + } console.info("createDataShareHelper succeed, data : " + data); dataShareHelper = data; - } -}); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## dataShare.createDataShareHelper @@ -57,6 +94,11 @@ createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper Creates a **DataShareHelper** instance. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -72,19 +114,31 @@ Creates a **DataShareHelper** instance. This API uses a promise to return the re | -------------------------------------------------- | -------------------------------------- | | Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri).then((data) => { - console.info("createDataShareHelper succeed, data : " + data); - dataShareHelper = data; -}).catch((err) => { - console.info("createDataShareHelper failed, error message : " + err); -}) +try { + dataShare.createDataShareHelper(this.context, uri).then((data) => { + console.info("createDataShareHelper succeed, data : " + data); + dataShareHelper = data; + }). catch((err) => { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## DataShareHelper @@ -101,16 +155,17 @@ Subscribes to changes of the specified data. After an observer is registered, th **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the data is changed, the value of **err** is **undefined**. Otherwise, this callback is not invoked or the value of **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is changed, the value of **err** is undefined. Otherwise, this callback is not invoked or the value of **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function onCallback() { console.info("**** Observer on callback ****"); } @@ -128,7 +183,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| @@ -137,7 +192,8 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function offCallback() { console.info("**** Observer off callback ****"); } @@ -155,29 +211,34 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the index of the inserted data record. Otherwise, **err** is an error object.
The data index is not returned if the APIs of the database in use, for example, the key-value database (KVDB), do not support the return of indexes.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose", "age": 22, "salary": 200.5, } -dataShareHelper.insert(uri, valueBucket, (err, data) => { - if (err != undefined) { - console.log("insert failed, error message : " + err); - }else{ - console.log("insert succeed, data : " + data); - } -}); +try { + dataShareHelper.insert(uri, valueBucket, (err, data) => { + if (err != undefined) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("insert succeed, data : " + data); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### insert @@ -193,7 +254,7 @@ Inserts a single data record into the database. This API uses a promise to retur | Name | Type | Mandatory| Description | | ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| **Return value** @@ -204,18 +265,23 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose1", "age": 221, "salary": 20.5, } -dataShareHelper.insert(uri, valueBucket).then((data) => { - console.log("insert succeed, data : " + data); -}).catch((err) => { - console.log("insert failed, error message : " + err); -}); +try { + dataShareHelper.insert(uri, valueBucket).then((data) => { + console.log("insert succeed, data : " + data); + }). catch((err) => { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -231,25 +297,29 @@ Deletes one or more data records from the database. This API uses an asynchronou | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.
The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da, (err, data) => { - if (err != undefined) { - console.log("delete failed, error message : " + err); - }else{ - console.log("delete succeed, data : " + data); - } -}); +try { + dataShareHelper.delete(uri, da, (err, data) => { + if (err != undefined) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("delete succeed, data : " + data); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -265,7 +335,7 @@ Deletes one or more data records from the database. This API uses a promise to r | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| **Return value** @@ -276,17 +346,21 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da).then((data) => { - console.log("delete succeed, data : " + data); -}).catch((err) => { - console.log("delete failed, error message : " + err); -}); +try { + dataShareHelper.delete(uri, da).then((data) => { + console.log("delete succeed, data : " + data); + }). catch((err) => { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -302,27 +376,31 @@ Queries data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | | callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the result set obtained. Otherwise, **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns, (err, data) => { - if (err != undefined) { - console.log("query failed, error message : " + err); - }else{ +try { + dataShareHelper.query(uri, da, columns, (err, data) => { + if (err != undefined) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("query succeed, rowCount : " + data.rowCount); - } -}); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -338,7 +416,7 @@ Queries data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | **Return value** @@ -350,18 +428,22 @@ Queries data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns).then((data) => { - console.log("query succeed, rowCount : " + data.rowCount); -}).catch((err) => { - console.log("query failed, error message : " + err); -}); +try { + dataShareHelper.query(uri, da, columns).then((data) => { + console.log("query succeed, rowCount : " + data.rowCount); + }). catch((err) => { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -377,15 +459,15 @@ Updates data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.
The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -396,13 +478,17 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va, (err, data) => { - if (err != undefined) { - console.log("update failed, error message : " + err); - }else{ +try { + dataShareHelper.update(uri, da, va, (err, data) => { + if (err != undefined) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("update succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -418,8 +504,8 @@ Updates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | **Return value** @@ -430,8 +516,8 @@ Updates data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -442,11 +528,15 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va).then((data) => { - console.log("update succeed, data : " + data); -}).catch((err) => { - console.log("update failed, error message : " + err); -}); +try { + dataShareHelper.update(uri, da, va).then((data) => { + console.log("update succeed, data : " + data); + }). catch((err) => { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -462,24 +552,29 @@ Batch inserts data into the database. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.
The number of inserted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs, (err, data) => { - if (err != undefined) { - console.log("batchInsert failed, error message : " + err); - }else{ +try { + dataShareHelper.batchInsert(uri, vbs, (err, data) => { + if (err != undefined) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("batchInsert succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -495,7 +590,7 @@ Batch inserts data into the database. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | uri | string | Yes | URI of the data to insert.| -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | **Return value** @@ -506,16 +601,21 @@ Batch inserts data into the database. This API uses a promise to return the resu **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs).then((data) => { - console.log("batchInsert succeed, data : " + data); -}).catch((err) => { - console.log("batchInsert failed, error message : " + err); -}); +try { + dataShareHelper.batchInsert(uri, vbs).then((data) => { + console.log("batchInsert succeed, data : " + data); + }). catch((err) => { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### normalizeUri @@ -536,7 +636,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { if (err != undefined) { @@ -570,7 +671,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri).then((data) => { console.log("normalizeUri = " + data); @@ -597,7 +699,8 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { if (err != undefined) { @@ -631,7 +734,8 @@ Denormalizes a URI. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri).then((data) => { console.log("denormalizeUri = " + data); @@ -650,7 +754,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | uri | string | Yes | URI of the data.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -658,7 +762,8 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.log("***** notifyChange *****"); @@ -688,7 +793,8 @@ Notifies the registered observer of data changes. This API uses a promise to ret **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 87c75a024fb144c72c0942e44b114a7d250a8008..89ebac58ef1f970c8c97c00bedb0fe5552491115 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,4 +1,4 @@ -# Relational Database +# @ohos.data.rdb The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. @@ -8,15 +8,17 @@ This module provides the following RDB-related functions: - [RdbStore](#rdbstore): provides APIs for managing an RDB store. > **NOTE**
-> +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore](js-apis-data-relationalStore.md). + ## Modules to Import ```js import data_rdb from '@ohos.data.rdb'; ``` - ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void @@ -27,12 +29,12 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| -| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | **Example** @@ -41,7 +43,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db"} @@ -58,9 +60,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -76,6 +79,7 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { console.log("Got RdbStore successfully.") }) ``` + ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> @@ -86,16 +90,16 @@ Obtains an RDB store. This API uses a promise to return the result. You can set **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes|Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------------------------ | ------------------------------- | | Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| **Example** @@ -105,7 +109,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db" } @@ -121,9 +125,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -149,11 +154,11 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -162,7 +167,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { @@ -178,9 +183,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -206,16 +212,16 @@ Deletes an RDB store. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -224,11 +230,11 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ +promise.then(() => { console.log("Deleted RdbStore successfully.") }).catch((err) => { console.info("Failed to delete RdbStore, err: " + err) @@ -239,9 +245,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -256,16 +263,70 @@ promise.then(()=>{ }) ``` +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| number | Number. | +| string | String. | +| boolean | Boolean.| + + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode8+ + +Defines the database synchronization mode. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | + +## SubscribeType8+ + +Defines the subscription type. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| + +## StoreConfig + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Database file name.| + ## RdbPredicates Defines predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. - ### constructor constructor(name: string) - A constructor used to create an **RdbPredicates** object. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -286,8 +347,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates - -Sets an **RdbPredicates** to specify the remote devices on the network to connect during distributed database synchronization. +Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -314,7 +374,6 @@ predicates.inDevices(['12345678abcde']) inAllDevices(): RdbPredicates - Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -336,7 +395,6 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -366,7 +424,6 @@ predicates.equalTo("NAME", "lisi") notEqualTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -396,7 +453,6 @@ predicates.notEqualTo("NAME", "lisi") beginWrap(): RdbPredicates - Adds a left parenthesis to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1098,7 +1154,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. -Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). +Before using the following APIs, use [executeSql](#executesql8) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). ### insert @@ -1172,7 +1228,7 @@ promise.then((rowId) => { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void @@ -1210,7 +1266,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { if (status) { console.log("Failed to batch insert data, status = " + status); @@ -1220,7 +1276,7 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> @@ -1263,7 +1319,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); @@ -1299,12 +1355,12 @@ const valueBucket = { } let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, ret) { +rdbStore.update(valueBucket, predicates, function (err, rows) { if (err) { console.info("Failed to update data, err: " + err) return } - console.log("Updated row count: " + ret) + console.log("Updated row count: " + rows) }) ``` @@ -1341,91 +1397,8 @@ const valueBucket = { let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.update(valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) -}).catch((err) => { - console.info("Failed to update data, err: " + err) -}) -``` - -### update9+ -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { - if (err) { - console.info("Failed to update data, err: " + err) - return - } - console.log("Updated row count: " + ret) -}) -``` - -### update9+ - -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) }).catch((err) => { console.info("Failed to update data, err: " + err) }) @@ -1493,76 +1466,6 @@ promise.then((rows) => { }) ``` -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { - if (err) { - console.info("Failed to delete data, err: " + err) - return - } - console.log("Deleted rows: " + rows) -}) -``` - -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) -promise.then((rows) => { - console.log("Deleted rows: " + rows) -}).catch((err) => { - console.info("Failed to delete data, err: " + err) -}) -``` - ### query query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void @@ -1629,151 +1532,6 @@ Queries data from the RDB store based on specified conditions. This API uses a p }) ``` -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void - -Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - if (err) { - console.info("Failed to query data, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) -}) -``` - -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> - -Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to query data, err: " + err) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void - -Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet){ - if (err) { - console.info("Failed to remoteQuery, err: " + err) - return - } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> - -Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | -------------------------------------------------------- | -| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) -}) -``` - ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void @@ -1836,7 +1594,7 @@ promise.then((resultSet) => { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void @@ -1865,7 +1623,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> @@ -1884,7 +1642,7 @@ Executes an SQL statement that contains specified arguments but returns no value | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -1910,7 +1668,7 @@ Starts the transaction before executing an SQL statement. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1937,7 +1695,7 @@ Commits the executed SQL statements. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1964,7 +1722,7 @@ Rolls back the SQL statements that have been executed. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { try { @@ -1984,122 +1742,6 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### backup9+ - -backup(destName:string, callback: AsyncCallback<void>):void - -Backs up an RDB store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Failed to back up data, err: ' + err) - return - } - console.info('Backed up data successfully.') -}) -``` - -### backup9+ - -backup(destName:string): Promise<void> - -Backs up an RDB store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseBackup = rdbStore.backup("dbBackup.db") -promiseBackup.then(()=>{ - console.info('Backed up data successfully.') -}).catch((err)=>{ - console.info('Failed to back up data, err: ' + err) -}) -``` - -### restore9+ - -restore(srcName:string, callback: AsyncCallback<void>):void - -Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Failed to restore data, err: ' + err) - return - } - console.info('Restored data successfully.') -}) -``` - -### restore9+ - -restore(srcName:string): Promise<void> - -Restores an RDB store from a backup file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseRestore = rdbStore.restore("dbBackup.db") -promiseRestore.then(()=>{ - console.info('Restored data successfully.') -}).catch((err)=>{ - console.info('Failed to restore data, err: ' + err) -}) -``` - ### setDistributedTables8+ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void @@ -2149,7 +1791,7 @@ Sets distributed tables. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -2306,8 +1948,6 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2315,7 +1955,7 @@ Registers an observer for this RDB store. When the data in the RDB store changes | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| The value is'dataChange', which indicates a data change event.| -| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to register.| | observer | Callback<Array<string>> | Yes| Observer that listens for the data changes in the RDB store.| **Example** @@ -2339,8 +1979,6 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri Unregisters the observer of the specified type from the RDB store. This API uses a callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2348,7 +1986,7 @@ Unregisters the observer of the specified type from the RDB store. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| The value is'dataChange', which indicates a data change event.| -| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to unregister.| | observer | Callback<Array<string>> | Yes| Data change observer registered.| **Example** @@ -2365,60 +2003,3 @@ try { console.log('Failed to unregister observer') } ``` - -## StoreConfig - -Defines the RDB store configuration. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Database file name.| -| encrypt9+ | boolean | No| Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store, and the value **false** means the opposite.| - -## ValueType - -Defines the data types allowed. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Type| Description| -| -------- | -------- | -| number | Number.| -| string | String.| -| boolean | Boolean.| - - -## ValuesBucket - -Defines the types of the key and value in a KV pair. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Key Type| Value Type| -| -------- | -------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | - -## SyncMode8+ - -Defines the database synchronization mode. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |----- | -| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| -| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device.| - -## SubscribeType8+ - -Defines the subscription type. - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |---- | -| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md new file mode 100644 index 0000000000000000000000000000000000000000..e6b33f3544ead35cb0584365c1c806f02b30ad1f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -0,0 +1,3202 @@ +# @ohos.data.relationalStore + +The relational database (RDB) store manages data based on relational models. With the underlying SQLite database, the RDB store provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. + +The **relationalStore** module provides the following functions: + +- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbStore](#rdbstore): provides APIs for managing data in an RDB store. +- [Resultset](#resultset): provides APIs for accessing the result set obtained from the RDB store. + +> **NOTE**
+> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import data_rdb from '@ohos.data.relationalStore'; +``` + +## data_rdb.getRdbStore + +getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void + +Obtains an RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call getRdbStore. +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + if (err) { + console.info("Failed to get RdbStore, err: " + err) + return + } + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call getRdbStore. +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + if (err) { + console.info("Failed to get RdbStore, err: " + err) + return + } + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}) +``` + +## data_rdb.getRdbStore + +getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> + +Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | + +**Return value** + +| Type | Description | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call getRdbStore. +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +promise.then(async (rdbStore) => { + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}).catch((err) => { + console.log("Failed to get RdbStore, err: " + err) +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call getRdbStore. +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +promise.then(async (rdbStore) => { + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}).catch((err) => { + console.log("Failed to get RdbStore, err: " + err) +}) +``` + +## data_rdb.deleteRdbStore + +deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void + +Deletes an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call deleteRdbStore. +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call deleteRdbStore. +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") +}) +``` + +## data_rdb.deleteRdbStore + +deleteRdbStore(context: Context, name: string): Promise<void> + +Deletes an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call deleteRdbStore. +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Deleted RdbStore successfully.") +}).catch((err) => { + console.info("Failed to delete RdbStore, err: " + err) +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call deleteRdbStore. +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Deleted RdbStore successfully.") +}).catch((err) => { + console.info("Failed to delete RdbStore, err: " + err) +}) +``` + +## StoreConfig + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | Yes | Database file name. | +| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. | +| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store;
the value **false** means the opposite.| + +## SecurityLevel + +Enumerates the RDB store security levels. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Value | Description | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | The RDB store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, an RDB store that contains system data such as wallpapers.| +| S2 | 2 | The RDB store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, an RDB store that contains information created by users or call records, such as audio or video clips.| +| S3 | 3 | The RDB store security level is high. If data leakage occurs, major impact will be caused on the database. For example, an RDB store that contains information such as user fitness, health, and location data.| +| S4 | 4 | The RDB store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, an RDB store that contains information such as authentication credentials and financial data.| + +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| number | Number. | +| string | String. | +| boolean | Boolean.| + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode + +Defines the database synchronization mode. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | + +## SubscribeType + +Defines the subscription type. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| + +## ConflictResolution10+ + +Defines the resolution to use when **insert()** and **update()** conflict. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------------- | ---- | ------------------------------------------------------------ | +| ON_CONFLICT_NONE | 0 | No operation is performed.| +| ON_CONFLICT_ROLLBACK | 1 | Abort the SQL statement and roll back the current transaction. | +| ON_CONFLICT_ABORT | 2 | Abort the current SQL statement and revert any changes made by the current SQL statement. However, the changes made by the previous SQL statement in the same transaction are retained and the transaction remains active.| +| ON_CONFLICT_FAIL | 3 | Abort the current SQL statement. The **FAIL** resolution does not revert previous changes made by the failed SQL statement or end the transaction.| +| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| +| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| + +## OpenStatus10+ + +Enumerates the RDB store status. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------- | ---- | --------------------------------------------------- | +| ON_CREATE | 0 | The RDB store is created for the first time. | +| ON_OPEN | 1 | The RDB store is already created. | + +## RdbPredicates + +Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. + +### constructor + +constructor(name: string) + +A constructor used to create an **RdbPredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| name | string | Yes | Database table name.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +``` + +### inDevices + +inDevices(devices: Array<string>): RdbPredicates + + +Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | -------------------------- | +| devices | Array<string> | Yes | IDs of the remote devices in the same network.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inDevices(['12345678abcde']) +``` + +### inAllDevices + +inAllDevices(): RdbPredicates + + +Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inAllDevices() +``` + +### equalTo + +equalTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") +``` + + +### notEqualTo + +notEqualTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notEqualTo("NAME", "lisi") +``` + + +### beginWrap + +beginWrap(): RdbPredicates + + +Adds a left parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### endWrap + +endWrap(): RdbPredicates + +Adds a right parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### or + +or(): RdbPredicates + +Adds the OR condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and + +and(): RdbPredicates + +Adds the AND condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) +``` + +### contains + +contains(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string containing the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.contains("NAME", "os") +``` + +### beginsWith + +beginsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that starts with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.beginsWith("NAME", "os") +``` + +### endsWith + +endsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that ends with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.endsWith("NAME", "se") +``` + +### isNull + +isNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNull("NAME") +``` + +### isNotNull + +isNotNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is not null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNotNull("NAME") +``` + +### like + +like(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that is similar to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.like("NAME", "%os%") +``` + +### glob + +glob(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match the specified string. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.glob("NAME", "?h*g") +``` + +### between + +between(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.between("AGE", 10, 50) +``` + +### notBetween + +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notBetween("AGE", 10, 50) +``` + +### greaterThan + +greaterThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThan("AGE", 18) +``` + +### lessThan + +lessThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThan("AGE", 20) +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThanOrEqualTo("AGE", 18) +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThanOrEqualTo("AGE", 20) +``` + +### orderByAsc + +orderByAsc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByAsc("NAME") +``` + +### orderByDesc + +orderByDesc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in descending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByDesc("AGE") +``` + +### distinct + +distinct(): RdbPredicates + +Sets an **RdbPredicates** to filter out duplicate records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").distinct() +``` + +### limitAs + +limitAs(value: number): RdbPredicates + +Sets an **RdbPredicates** to specify the maximum number of records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| value | number | Yes | Maximum number of records.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").limitAs(3) +``` + +### offsetAs + +offsetAs(rowOffset: number): RdbPredicates + +Sets an **RdbPredicates** to specify the start position of the returned result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------------------------- | +| rowOffset | number | Yes | Number of rows to offset from the beginning. The value is a positive integer.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").offsetAs(3) +``` + +### groupBy + +groupBy(fields: Array<string>): RdbPredicates + +Sets an **RdbPredicates** to group rows that have the same value into summary rows. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| fields | Array<string> | Yes | Names of columns to group.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ---------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.groupBy(["AGE", "NAME"]) +``` + +### indexedBy + +indexedBy(field: string): RdbPredicates + +Sets an **RdbPredicates** object to specify the index column. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| field | string | Yes | Name of the index column.| + +**Return value** + + +| Type | Description | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.indexedBy("SALARY_INDEX") +``` + +### in + +in(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | --------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.in("AGE", [18, 20]) +``` + +### notIn + +notIn(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notIn("NAME", ["Lisa", "Rose"]) +``` + +## RdbStore + +Provides methods to manage an RDB store. + +Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). + +### Attributes10+ + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ----------- | ---- | -------------------------------- | +| openStatus10+ | number | Yes | RDB store status. The value **0** indicates the **ON_CREATE** state, which means the RDB store is created for the first time. The value **1** indicates the **ON_OPEN** state, which means the RDB store is already created. | + +### insert + +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { + if (status) { + console.log("Failed to insert data"); + return; + } + console.log("Inserted data successfully, rowId = " + rowId); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (status, rowId) { + if (status) { + console.log("Failed to insert data"); + return; + } + console.log("Inserted data successfully, rowId = " + rowId); +}) +``` + +### insert + +insert(table: string, values: ValuesBucket):Promise<number> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket) +promise.then((rowId) => { + console.log("Inserted data successfully, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promise<number> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) +promise.then((rowId) => { + console.log("Inserted data successfully, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +Batch inserts data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { + if (status) { + console.log("batchInsert is failed, status = " + status); + return; + } + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +Batch inserts data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +promise.then((insertNum) => { + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}).catch((status) => { + console.log("batchInsert is failed, status = " + status); +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, function (err, rows) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution):Promise<number> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +Updates data based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Update conditions specified by the **DataSharePredicates** object. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +Updates data based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Update conditions specified by the **DataSharePredicates** object. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### delete + +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.delete(predicates, function (err, rows) { + if (err) { + console.info("Failed to delete data, err: " + err) + return + } + console.log("Deleted rows: " + rows) +}) +``` + +### delete + +delete(predicates: RdbPredicates):Promise<number> + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete(predicates) +promise.then((rows) => { + console.log("Deleted rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { + if (err) { + console.info("Failed to delete data, err: " + err) + return + } + console.log("Deleted rows: " + rows) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete("EMPLOYEE", predicates) +promise.then((rows) => { + console.log("Deleted rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` + +### query + +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Failed to query data, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query + +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + + ```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) + ``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Failed to query data, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void + +Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| device | string | Yes | Network ID of the remote device. | +| table | string | Yes | Name of the target table. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.greaterThan("id", 0) +rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], + function(err, resultSet){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> + +Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| device | string | Yes | Network ID of the remote device. | +| table | string | Yes | Name of the target table. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.greaterThan("id", 0) +let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + +### querySql + +querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void + +Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { + if (err) { + console.info("Failed to query data, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### querySql + +querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> + +Queries data using the specified SQL statement. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | Yes | SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void + +Executes an SQL statement that contains specified arguments but returns no value. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ---------------------- | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.info("Failed to execute SQL, err: " + err) + return + } + console.info('Create table done.') +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> + +Executes an SQL statement that contains specified arguments but returns no value. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | Yes | SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +let promise = rdbStore.executeSql(SQL_CREATE_TABLE) +promise.then(() => { + console.info('Create table done.') +}).catch((err) => { + console.info("Failed to execute SQL, err: " + err) +}) +``` + +### beginTransaction + +beginTransaction():void + +Starts the transaction before executing an SQL statement. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) +``` + +### commit + +commit():void + +Commits the executed SQL statements. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) +``` + +### rollBack + +rollBack():void + +Rolls back the SQL statements that have been executed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + try { + rdbStore.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() + } catch (e) { + rdbStore.rollBack() + } +}) +``` + +### backup + +backup(destName:string, callback: AsyncCallback<void>):void + +Backs up an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +rdbStore.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup + +backup(destName:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promiseBackup = rdbStore.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore + +restore(srcName:string, callback: AsyncCallback<void>):void + +Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +rdbStore.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore + +restore(srcName:string): Promise<void> + +Restores an RDB store from a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promiseRestore = rdbStore.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` + +### setDistributedTables + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void + +Sets distributed tables. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| tables | Array<string> | Yes | Names of the distributed tables to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { + if (err) { + console.info('Failed to set distributed tables, err: ' + err) + return + } + console.info('Set distributed tables successfully.') +}) +``` + +### setDistributedTables + + setDistributedTables(tables: Array<string>): Promise<void> + +Sets distributed tables. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ------------------------ | +| tables | Array<string> | Yes | Names of the distributed tables to set.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) +promise.then(() => { + console.info("Set distributed tables successfully.") +}).catch((err) => { + console.info("Failed to set distributed tables, err: " + err) +}) +``` + +### obtainDistributedTableName + +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void + +Obtains the distributed table name for a remote device based on the local table name. This API uses an asynchronous callback to return the result. The distributed table name is required when the RDB store of a remote device is queried. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| device | string | Yes | Remote device. | +| table | string | Yes | Local table name. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** + +```js +rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { + if (err) { + console.info('Failed to obtain DistributedTableName, err: ' + err) + return + } + console.info('Obtained distributed table name successfully, tableName=.' + tableName) +}) +``` + +### obtainDistributedTableName + + obtainDistributedTableName(device: string, table: string): Promise<string> + +Obtains the distributed table name for a remote device based on the local table name. This API uses a promise to return the result. The distributed table name is required when the RDB store of a remote device is queried. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| device | string | Yes | Remote device.| +| table | string | Yes | Local table name.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------- | +| Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** + +```js +let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +promise.then((tableName) => { + console.info('Obtained distributed table name successfully, tableName= ' + tableName) +}).catch((err) => { + console.info('Failed to obtain DistributedTableName, err: ' + err) +}) +``` + +### sync + +sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void + +Synchronizes data between devices. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| mode | [SyncMode](#syncmode) | Yes | Data synchronization mode. The value can be **push** or **pull**. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.inDevices(['12345678abcde']) +rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { + if (err) { + console.log('Sync failed, err: ' + err) + return + } + console.log('Sync done.') + for (let i = 0; i < result.length; i++) { + console.log('device=' + result[i][0] + ' status=' + result[i][1]) + } +}) +``` + +### sync + + sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> + +Synchronizes data between devices. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------ | +| mode | [SyncMode](#syncmode) | Yes | Data synchronization mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | + +**Return value** + +| Type | Description | +| -------------------------------------------- | ------------------------------------------------------------ | +| Promise<Array<[string, number]>> | Promise used to send the synchronization result.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.inDevices(['12345678abcde']) +let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates) +promise.then((resultSet) =>{ + console.log('Sync done.') + for (let i = 0; i < resultSet.length; i++) { + console.log('device=' + resultSet[i][0] + ' status=' + resultSet[i][1]) + } +}).catch((err) => { + console.log('Sync failed') +}) +``` + +### on('dataChange') + +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------- | +| event | string | Yes | The value is'dataChange', which indicates a data change event. | +| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register.| +| observer | Callback<Array<string>> | Yes | Observer that listens for the data changes in the RDB store. | + +**Example** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Failed to register observer') +} +``` + +### off('dataChange') + +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------ | +| event | string | Yes | The value is'dataChange', which indicates a data change event. | +| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register. | +| observer | Callback<Array<string>> | Yes | Data change observer registered. | + +**Example** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Failed to unregister observer') +} +``` + +## ResultSet + +Provides APIs to access the result set obtained by querying the RDB store. A result set is a set of results returned after **query()** is called. + +### Usage + +Obtain the **resultSet** object by [RdbStore.query()](#query). + +```js +import dataRdb from '@ohos.data.rdb'; +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +predicates.equalTo("AGE", 18); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); +}); +``` + +### Attributes + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ------------------- | ---- | -------------------------------- | +| columnNames | Array<string> | Yes | Names of all columns in the result set. | +| columnCount | number | Yes | Number of columns in the result set. | +| rowCount | number | Yes | Number of rows in the result set. | +| rowIndex | number | Yes | Index of the current row in the result set. | +| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | +| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | +| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| +| isStarted | boolean | Yes | Whether the cursor has been moved. | +| isClosed | boolean | Yes | Whether the result set is closed. | + +### getColumnIndex + +getColumnIndex(columnName: string): number + +Obtains the column index based on the column name. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------------- | +| columnName | string | Yes | Column name.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Column index obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +resultSet.goToFirstRow(); +const id = resultSet.getLong(resultSet.getColumnIndex("ID")); +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### getColumnName + +getColumnName(columnIndex: number): string + +Obtains the column name based on the specified column index. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------------------------- | +| columnIndex | number | Yes | Column index.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Column name obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +const id = resultSet.getColumnName(0); +const name = resultSet.getColumnName(1); +const age = resultSet.getColumnName(2); + ``` + +### goTo + +goTo(offset:number): boolean + +Moves the cursor to the row based on the specified offset. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| offset | number | Yes | Offset relative to the current position.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise= rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goTo(1); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToRow + +goToRow(position: number): boolean + +Moves to the specified row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| position | number | Yes | Destination position to move to.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.(5); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToFirstRow + +goToFirstRow(): boolean + + +Moves to the first row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToFirstRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToLastRow + +goToLastRow(): boolean + +Moves to the last row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToLastRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToNextRow + +goToNextRow(): boolean + +Moves to the next row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToNextRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToPreviousRow + +goToPreviousRow(): boolean + +Moves to the previous row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToPreviousRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### getBlob + +getBlob(columnIndex: number): Uint8Array + +Obtains the value in the form of a byte array based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ---------- | -------------------------------- | +| Uint8Array | Value obtained.| + +**Example** + + ```js +const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); + ``` + +### getString + +getString(columnIndex: number): string + +Obtains the value in the form of a string based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | String obtained.| + +**Example** + + ```js +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); + ``` + +### getLong + +getLong(columnIndex: number): number + +Obtains the value of the Long type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Value obtained.| + +**Example** + + ```js +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); + ``` + +### getDouble + +getDouble(columnIndex: number): number + +Obtains the value of the double type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| number | Value obtained.| + +**Example** + + ```js +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### isColumnNull + +isColumnNull(columnIndex: number): boolean + +Checks whether the value in the specified column is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------------------- | +| boolean | Returns **true** if the value is null; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); + ``` + +### close + +close(): void + +Closes this result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + + ```js +let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); +let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promiseClose.then((resultSet) => { + resultSet.close(); +}).catch((err) => { + console.log('resultset close failed'); +}); + ``` + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md index 798ac7bba0926f47e1bc16eb6b672403bc082fa7..8cdecd1134a270075b3d4dd86a7e4e7a07fc7390 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,549 +1,17 @@ -# Result Set +# resultSet A result set is a set of results returned after the relational database (RDB) query APIs are called. You can use the **resultset** APIs to obtain required data. -> **NOTE** +> **NOTE**
> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore#ResultSet](js-apis-data-relationalStore.md#resultset). -## ResultSetV99+ - -Provides methods to access the result set, which is obtained by querying the RDB store. - -### Usage - -You need to obtain the **resultSetV9** instance by using [RdbStoreV9.query()](js-apis-data-rdb.md#query). - -```js -import dataRdb from '@ohos.data.rdb'; -let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -predicatesV9.equalTo("AGE", 18); -let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSetV9) => { - console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount); -}); -``` - -### Attributes9+ - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Type | Mandatory| Description | -| ------------ | ------------------- | ---- | -------------------------------- | -| columnNames | Array<string> | Yes | Names of all columns in the result set. | -| columnCount | number | Yes | Number of columns in the result set. | -| rowCount | number | Yes | Number of rows in the result set. | -| rowIndex | number | Yes | Index of the current row in the result set. | -| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | -| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | -| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| -| isStarted | boolean | Yes | Whether the cursor has been moved. | -| isClosed | boolean | Yes | Whether the result set is closed. | - -### getColumnIndex9+ - -getColumnIndex(columnName: string): number - -Obtains the column index based on the column name. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------------------------- | -| columnName | string | Yes | Column name specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| number | Index of the column obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -resultSetV9.goToFirstRow(); -const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID")); -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### getColumnName9+ - -getColumnName(columnIndex: number): string - -Obtains the column name based on the column index. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------- | -| columnIndex | number | Yes | Column index specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| string | Column name obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const id = resultSetV9.getColumnName(0); -const name = resultSetV9.getColumnName(1); -const age = resultSetV9.getColumnName(2); - ``` - -### goTo9+ - -goTo(offset:number): boolean - -Moves the cursor to the row based on the specified offset. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------- | -| offset | number | Yes | Offset relative to the current position.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoto.then((resultSetV9) => { - resultSetV9.goTo(1); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToRow9+ - -goToRow(position: number): boolean - -Moves the cursor to the specified row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------ | -| position | number | Yes | Position to which the cursor is to be moved.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygotorow.then((resultSetV9) => { - resultSetV9.goToRow(5); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToFirstRow9+ - -goToFirstRow(): boolean - - -Moves the cursor to the first row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoFirst.then((resultSetV9) => { - resultSetV9.goToFirstRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToLastRow9+ - -goToLastRow(): boolean - -Moves the cursor to the last row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoLast.then((resultSetV9) => { - resultSetV9.goToLastRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToNextRow9+ - -goToNextRow(): boolean - -Moves the cursor to the next row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoNext.then((resultSetV9) => { - resultSetV9.goToNextRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToPreviousRow9+ - -goToPreviousRow(): boolean - -Moves the cursor to the previous row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoPrev.then((resultSetV9) => { - resultSetV9.goToPreviousRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### getBlob9+ - -getBlob(columnIndex: number): Uint8Array - -Obtains the value in the specified column in the current row as a byte array. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ---------- | -------------------------------- | -| Uint8Array | Value in the specified column as a byte array.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES")); - ``` - -### getString9+ - -getString(columnIndex: number): string - -Obtains the value in the specified column in the current row as a string. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| string | Value in the specified column as a string.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); - ``` - -### getLong9+ - -getLong(columnIndex: number): number - -Obtains the value in the specified column in the current row as a Long. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | -------------------------- | -| number | Value in the specified column as a Long.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); - ``` - -### getDouble9+ - -getDouble(columnIndex: number): number - -Obtains the value in the specified column in the current row as a double. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| number | Value in the specified column as a double.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### isColumnNull9+ - -isColumnNull(columnIndex: number): boolean - -Checks whether the value in the specified column of the current row is null. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------------------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES")); - ``` - -### close9+ - -close(): void - -Closes this result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Example** - - ```js -let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSetV9) => { - resultSetV9.close(); -}).catch((err) => { - console.log('Failed to close the resultset'); -}); - ``` - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -## ResultSet(deprecated) +## ResultSet Provides methods to access the result set, which is obtained by querying the RDB store. -> **NOTE** -> -> This object is supported since API version 7 and deprecated since API version 9. You are advised to use [ResultSetV9](#resultsetv99). - ### Usage You need to obtain a **resultSet** object by using [RdbStore.query()](js-apis-data-rdb.md#query). @@ -559,11 +27,7 @@ promise.then((resultSet) => { }); ``` -### Attributes(deprecated) - -> **NOTE** -> -> This parameter is supported since API version 7 and is deprecated since API version 9. You are advised to use [Attributes](#attributes9). +### Attributes **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -579,29 +43,25 @@ promise.then((resultSet) => { | isStarted | boolean | Yes| Whether the cursor has been moved.| | isClosed | boolean | Yes| Whether the result set is closed.| -### getColumnIndex(deprecated) +### getColumnIndex getColumnIndex(columnName: string): number Obtains the column index based on the column name. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnIndex](#getcolumnindex9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnName | string | Yes| Column name specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnName | string | Yes| Column name specified.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Index of the column obtained.| + | Type| Description| + | -------- | -------- | + | number | Index of the column obtained.| **Example** @@ -613,29 +73,25 @@ Obtains the column index based on the column name. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### getColumnName(deprecated) +### getColumnName getColumnName(columnIndex: number): string Obtains the column name based on the column index. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnName](#getcolumnname9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Column index specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Column index specified.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Column name obtained.| + | Type| Description| + | -------- | -------- | + | string | Column name obtained.| **Example** @@ -645,29 +101,25 @@ Obtains the column name based on the column index. const age = resultSet.getColumnName(2); ``` -### goTo(deprecated) +### goTo goTo(offset:number): boolean Moves the cursor to the row based on the specified offset. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goTo](#goto9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| offset | number | Yes| Offset relative to the current position.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | offset | number | Yes| Offset relative to the current position.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -682,29 +134,25 @@ Moves the cursor to the row based on the specified offset. }); ``` -### goToRow(deprecated) +### goToRow goToRow(position: number): boolean Moves the cursor to the specified row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToRow](#gotorow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| position | number | Yes| Position to which the cursor is to be moved.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | position | number | Yes| Position to which the cursor is to be moved.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -719,23 +167,19 @@ Moves the cursor to the specified row in the result set. }); ``` -### goToFirstRow(deprecated) +### goToFirstRow goToFirstRow(): boolean Moves the cursor to the first row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToFirstRow](#gotofirstrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -750,23 +194,19 @@ Moves the cursor to the first row of the result set. }); ``` -### goToLastRow(deprecated) +### goToLastRow goToLastRow(): boolean Moves the cursor to the last row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToLastRow](#gotolastrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -781,23 +221,19 @@ Moves the cursor to the last row of the result set. }); ``` -### goToNextRow(deprecated) +### goToNextRow goToNextRow(): boolean Moves the cursor to the next row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToNextRow](#gotonextrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -812,23 +248,19 @@ Moves the cursor to the next row in the result set. }); ``` -### goToPreviousRow(deprecated) +### goToPreviousRow goToPreviousRow(): boolean Moves the cursor to the previous row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToPreviousRow](#gotopreviousrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -843,29 +275,25 @@ Moves the cursor to the previous row in the result set. }); ``` -### getBlob(deprecated) +### getBlob getBlob(columnIndex: number): Uint8Array Obtains the value in the specified column in the current row as a byte array. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getBlob](#getblob9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| Uint8Array | Value in the specified column as a byte array.| + | Type| Description| + | -------- | -------- | + | Uint8Array | Value in the specified column as a byte array.| **Example** @@ -873,29 +301,25 @@ Obtains the value in the specified column in the current row as a byte array. const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` -### getString(deprecated) +### getString getString(columnIndex: number): string Obtains the value in the specified column in the current row as a string. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getString](#getstring9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Value in the specified column as a string.| + | Type| Description| + | -------- | -------- | + | string | Value in the specified column as a string.| **Example** @@ -903,29 +327,25 @@ Obtains the value in the specified column in the current row as a string. const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` -### getLong(deprecated) +### getLong getLong(columnIndex: number): number Obtains the value in the specified column in the current row as a Long. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getLong](#getlong9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a Long.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a Long.| **Example** @@ -933,29 +353,25 @@ Obtains the value in the specified column in the current row as a Long. const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` -### getDouble(deprecated) +### getDouble getDouble(columnIndex: number): number Obtains the value in the specified column in the current row as a double. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDouble](#getdouble9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a double.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a double.| **Example** @@ -963,29 +379,25 @@ Obtains the value in the specified column in the current row as a double. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### isColumnNull(deprecated) +### isColumnNull isColumnNull(columnIndex: number): boolean Checks whether the value in the specified column of the current row is null. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isColumnNull](#iscolumnnull9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the value is null; returns **false** otherwise.| **Example** @@ -993,16 +405,12 @@ Checks whether the value in the specified column of the current row is null. const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` -### close(deprecated) +### close close(): void Closes this result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [close](#close9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md index 46a110814dc474f66393135a91313ab5df03b98e..d413556b36e7e8ebaacbe053ffbe0f0c97b98019 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -1,9 +1,8 @@ -# Device Information +# @ohos.deviceInfo The **deviceInfo** module provides product information. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 09af96344c7bb7a86a28906d06730e2894296e2b..e8363f6203436eec807f436ca3c63c00cfc3bc74 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,6 +1,6 @@ # @ohos.distributedHardware.deviceManager (Device Management) -The **DeviceManager** module provides APIs for distributed device management. +The **deviceManager** module provides APIs for distributed device management. System applications can call the APIs to do the following: diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 2bc06da295e4bf610281929f32b7a797e46db204..21f8d30deacbcacd95e5da17012a3ba3c184c834 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,4 +1,5 @@ -# Display +# @ohos.display + The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. > **NOTE** @@ -188,7 +189,7 @@ Checks whether there is a visible privacy window on a display. The privacy windo | Type | Description | | -------------------------------- |-----------------------------------------------------------------------| -|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| +|boolean | Whether there is a visible privacy window on the display. The value **true** means that there is a visible privacy window on the display, and **false** means the opposite. | **Error codes** @@ -264,7 +265,7 @@ Unsubscribes from display changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event indicating that a display is disconnected.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event that a display is disconnected.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| | callback | Callback<number> | No| Callback used to return the ID of the display.| **Example** @@ -404,6 +405,8 @@ Implements a **Display** instance, with properties and APIs defined. Before calling any API in **Display**, you must use [getAllDisplays()](#displaygetalldisplays9) or [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) to obtain a **Display** instance. +### Attributes + **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name| Type| Readable| Writable| Description| @@ -416,9 +419,9 @@ Before calling any API in **Display**, you must use [getAllDisplays()](#displayg | rotation | number | Yes| No| Screen rotation angle of the display.
The value **0** indicates that the screen of the display rotates by 0°.
The value **1** indicates that the screen of the display rotates by 90°.
The value **2** indicates that the screen of the display rotates by 180°.
The value **3** indicates that the screen of the display rotates by 270°.| | width | number | Yes| No| Width of the display, in pixels.| | height | number | Yes| No| Height of the display, in pixels.| -| densityDPI | number | Yes| No| Screen density of the display, in DPI.| -| densityPixels | number | Yes| No| Screen density of the display, in pixels.| -| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.| +| densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. Generally, the value is **160** or **480**.| +| densityPixels | number | Yes| No| Logical density of the display, which is a scaling coefficient independent of the pixel unit. Generally, the value is **1** or **3**.| +| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display. Generally, the value is the same as that of **densityPixels**.| | xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| | yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md index aa49db0f38c911850ec73e2fdb00fa98399ff1fc..770689ba93a6a375f7d48a46d49cbe2334bd9bc3 100644 --- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -1,4 +1,4 @@ -# Distributed Mission Management +# @ohos.distributedMissionManager (Distributed Mission Management) The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device. @@ -372,6 +372,19 @@ Continues a mission on a remote device. This API uses an asynchronous callback t | options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 16300501 | The system ability work abnormally. | +| 16300502 | Failed to get the missionInfo of the specified missionId. | +| 16300503 | The application is not installed on the remote end and installation-free is not supported. | +| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. | +| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. | +| 16300506 | The local continuation task is already in progress. | + **Example** ```ts @@ -381,11 +394,11 @@ Continues a mission on a remote device. This API uses an asynchronous callback t missionId: 1, wantParam: {"key": "value"} }; - function OnContinueDone(resultCode) { - console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + function onContinueDone(resultCode) { + console.log('onContinueDone resultCode: ' + JSON.stringify(resultCode)); }; var options = { - OnContinueDone: OnContinueDone + onContinueDone: onContinueDone }; try { distributedMissionManager.continueMission(parameter, options, (error) => { @@ -422,6 +435,19 @@ Continues a mission on a remote device. This API uses a promise to return the re | ------------------- | ---------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 16300501 | The system ability work abnormally. | +| 16300502 | Failed to get the missionInfo of the specified missionId. | +| 16300503 | The application is not installed on the remote end and installation-free is not supported. | +| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. | +| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. | +| 16300506 | The local continuation task is already in progress. | + **Example** ```ts @@ -431,11 +457,11 @@ Continues a mission on a remote device. This API uses a promise to return the re missionId: 1, wantParam: {"key": "value"} }; - function OnContinueDone(resultCode) { - console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + function onContinueDone(resultCode) { + console.log('onContinueDone resultCode: ' + JSON.stringify(resultCode)); }; var options = { - OnContinueDone: OnContinueDone + onContinueDone: onContinueDone }; try { distributedMissionManager.continueMission(parameter, options) diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index ac903232328a4da80fe021b39266fd0025ca9fcb..2a6c9e6c8670b70ce80b59b6eea5cf5defa98234 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -1,4 +1,6 @@ -# Fault Logger +# @ohos.faultLogger (Fault Logger) + +The **faultLogger** module implements fault logging functions. > **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-fileAccess.md b/en/application-dev/reference/apis/js-apis-fileAccess.md index 743e17c77f8dd2c4baa48f90de3ff9ac47fedfc0..bea477cc5357a7026ca0fd3b4b11bb3f6049d53e 100644 --- a/en/application-dev/reference/apis/js-apis-fileAccess.md +++ b/en/application-dev/reference/apis/js-apis-fileAccess.md @@ -1,11 +1,11 @@ -# User File Access and Management +# @ohos.data.fileAccess -The **fileAccess** module is a framework for accessing and operating user files based on the extension mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of unified file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. +The **fileAccess** module is a framework for accessing and operating user files based on the Extension ability mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. >**NOTE** > >- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by FilePicker and the file manager app. +>- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **FilePicker** and **Files**. ## Modules to Import @@ -21,17 +21,13 @@ Obtains information about all wants with **extension** set to **fileAcesss** in **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER - -**Parameters** - -None +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Return value** -| Type| Description| -| --- | -- | -| Promise<Array<Want>> | Promise used to return the want information obtained.| + | Type| Description| + | --- | -- | + | Promise<Array<Want>> | Promise used to return the **want** information obtained.| **Example** @@ -55,27 +51,27 @@ Synchronously creates a **Helper** object to connect to the specified wants. The **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| context | Context | Yes| Context of the ability.| -| wants | Array<Want> | Yes| Wants to connect.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | context | Context | Yes| Context of the ability.| + | wants | Array<Want> | Yes| Wants to connect.| **Return value** -| Type| Description| -| --- | -- | -| FileAccessHelper | **Helper** object created.| + | Type| Description| + | --- | -- | + | FileAccessHelper | **Helper** object created.| **Example** ```js createFileAccessHelper() { - let fileAccesssHelper = null; - // Obtain want information by using getFileAccessAbilityInfo(). + let fileAccessHelper = null; + / / Obtain wantInfos by using getFileAccessAbilityInfo(). // Create a Helper object to interact with the media library service only. let wantInfos = [ { @@ -84,8 +80,9 @@ Synchronously creates a **Helper** object to connect to the specified wants. The }, ] try { - fileAccesssHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); - if (!fileAccesssHelper) + // This.context is passed by MainAbility. + fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); + if (!fileAccessHelper) console.error("createFileAccessHelper interface returns an undefined object"); } catch (error) { console.error("createFileAccessHelper failed, error " + error); @@ -97,23 +94,23 @@ Synchronously creates a **Helper** object to connect to the specified wants. The createFileAccessHelper(context: Context) : FileAccessHelper -Synchronously creates a **Helper** object that connects to all file management services in the current system. +Synchronously creates a **Helper** object to connect to all file management services in the system. **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| context | Context | Yes| Context of the ability.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | context | Context | Yes| Context of the ability.| **Return value** -| Type| Description| -| --- | -- | -| FileAccessHelper | **Helper** object created.| + | Type| Description| + | --- | -- | + | FileAccessHelper | **Helper** object created.| **Example** @@ -122,6 +119,7 @@ Synchronously creates a **Helper** object that connects to all file management s let fileAccesssHelperAllServer = null; // Create a Helper object to interact with all file management services configured with fileAccess in the system. try { + // This.context is passed by MainAbility. fileAccesssHelperAllServer = fileAccess.createFileAccessHelper(this.context); if (!fileAccesssHelperAllServer) console.error("createFileAccessHelper interface returns an undefined object"); @@ -135,22 +133,18 @@ Synchronously creates a **Helper** object that connects to all file management s getRoots( ) : Promise<RootIterator> -Obtains information about the root nodes for the devices of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which +Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** -| Type| Description| -| --- | -- | -| Promise<RootIterator> | **RootIterator** object obtained.| + | Type| Description| + | --- | -- | + | Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.| **Example** @@ -160,7 +154,8 @@ None let rootinfos = []; let isDone = false; try { - rootIterator = await fileAccesssHelper.getRoots(); + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + rootIterator = await fileAccessHelper.getRoots(); if (!rootIterator) { console.error("getRoots interface returns an undefined object"); return; @@ -182,7 +177,7 @@ None listFile(filter?: Filter) : FileIterator -Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the root node of a device. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). +Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the device root node. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -190,28 +185,28 @@ Synchronously obtains the **FileIterator** object of the first-level files (file **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** ```js - / / Obtain root information by using getRoots(). + / / Obtain rootInfos by using getRoots(). // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; let rootInfo = rootinfos[0]; let fileInfos = []; let isDone = false; try { let fileIterator = rootInfo.listFile(); - // ListFile that contains the filter implementation. + // listFile contains the filter implementation. // let fileIterator = rootInfo.listFile(filter); if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -233,7 +228,7 @@ Synchronously obtains the **FileIterator** object of the first-level files (file scanFile(filter?: Filter) : FileIterator -Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the root node of a device synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using the [next()](#fileiteratornext). +Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the device root node synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -241,39 +236,39 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** ```js - / / Obtain root information by using getRoots(). + // Obtain rootInfos by using getRoots(). // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; - let rootInfo = rootinfos[0]; + let rootInfo = rootInfos[0]; let fileInfos = []; let isDone = false; try { - let fileIterator = rootInfo.scanFile(); - // ScanFile that contains the filter implementation - // let fileIterator = rootInfo.scanFile(filter); - if (!fileIterator) { - console.error("scanFile interface returns undefined object"); - return; - } - while (!isDone) { - let result = fileIterator.next(); - console.log("next result = " + JSON.stringify(result)); - isDone = result.done; - if (!isDone) - fileInfos.push(result.value); - } + let fileIterator = rootInfo.scanFile(); + // scanFile contains the filter implementation. + // let fileIterator = rootInfo.scanFile(filter); + if (!fileIterator) { + console.error("scanFile interface returns undefined object"); + return; + } + while (!isDone) { + let result = fileIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + fileInfos.push(result.value); + } } catch (error) { console.error("scanFile failed, error " + error); } @@ -291,15 +286,15 @@ Synchronously obtains the **FileIterator** object of the next-level files (file **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -311,7 +306,7 @@ Synchronously obtains the **FileIterator** object of the next-level files (file let isDone = false; try { let fileIterator = fileInfoDir.listFile(); - // ListFile that contains the filter implementation. + // listFile contains the filter implementation. // let fileIterator = rootInfo.listFile(filter); if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -341,16 +336,16 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -362,7 +357,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit let isDone = false; try { let fileIterator = fileInfoDir.scanFile(); - // ScanFile that contains the filter implementation + // scanFile contains the filter implementation. // let fileIterator = rootInfo.scanFile(filter); if (!fileIterator) { console.error("scanFile interface returns an undefined object"); @@ -370,7 +365,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit } while (!isDone) { let result = fileIterator.next(); - console.error("next result = " + JSON.stringify(result)); + console.log("next result = " + JSON.stringify(result)); isDone = result.done; if (!isDone) subfileInfos.push(result.value); @@ -392,25 +387,28 @@ Creates a file in a directory. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the parent directory for the file to create.| -| displayName | string | Yes| Name of the file to create. A file name extension must be added for a local file. It is not required for a file stored in a shared disk.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the parent directory for the file to create.| + | displayName | string | Yes| Name of the file to create. A file name extension must be added for a local file. It is not required for a file stored in a shared disk.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the file created.| +| Promise<string> | Promise used to return the URI of the file created.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; let displayName = "file1" let fileUri = null; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. fileUri = await fileAccessHelper.createFile(sourceUri, displayName) if (!fileUri) { console.error("createFile return undefined object"); @@ -434,25 +432,28 @@ Creates a folder in a directory. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| parentUri | string | Yes| URI of the parent directory for the folder to create.| -| displayName | string | Yes| Name of the folder to create.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | parentUri | string | Yes| URI of the parent directory for the folder to create.| + | displayName | string | Yes| Name of the folder to create.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the folder created.| +| Promise<string> | Promise used to return the URI of the folder created.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; let dirName = "dirTest" let dirUri = null; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. dirUri = await fileAccessHelper.mkDir(sourceUri, dirName) if (!dirUri) { console.error("mkDir return undefined object"); @@ -466,7 +467,7 @@ Creates a folder in a directory. This API uses a promise to return the result. ## FileAccessHelper.openFile -openFile(uri: string, flags: [OPENFLAGS](#openflags)) : Promise<number> +openFile(uri: string, flags: OPENFLAGS) : Promise<number> Opens a file. This API uses a promise to return the result. @@ -476,25 +477,28 @@ Opens a file. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file to open.| -| flags | OPENFLAGS | |File open mode.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file to open.| + | flags | [OPENFLAGS](#openflags) | Yes| File open mode.| **Return value** | Type| Description| | --- | -- | -| Promise<number> | Handle of the file opened.| +| Promise<number> | Promise used to return the handle to the file opened.| **Example** ```js - // The URI of a shared disk is used as an example. - let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + // The media library URI is used as an example. + //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let targetUri = "datashare:///media/file/100"; try { - let fd = await fileAccessHelper.openFile(targetUri, OPENFLAGS.READ); - } cache (error) { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ); + } catch (error) { console.error("openFile failed, error " + error); }; ``` @@ -511,9 +515,9 @@ Deletes a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to delete.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or folder to delete.| **Return value** @@ -524,13 +528,16 @@ Deletes a file or folder. This API uses a promise to return the result. **Example** ```js - // The URI of a shared disk is used as an example. - let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + // The media library URI is used as an example. + //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let targetUri = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let code = await fileAccessHelper.delete(targetUri); if (code != 0) console.error("delete failed, code " + code); - } cache (error) { + } catch (error) { console.error("delete failed, error " + error); }; ``` @@ -547,27 +554,30 @@ Moves a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFile | string | Yes| URI of the file or folder to move.| -| destFile | string | Yes| URI of the folder to which the file or folder is moved.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFile | string | Yes| URI of the file or folder to move.| + | destFile | string | Yes| URI of the folder to which the file or folder will be moved.| **Return value** | Type| Description| | ----- | ------ | -| Promise<string> | URI of the file or folder in the destination directory.| +| Promise<string> | Promise used to return the URI of the file or folder in the destination directory.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; - let destFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + //In the sample code, sourceFile destFile indicates the file or folder in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceFile = "datashare:///media/file/102"; + let destFile = "datashare:///media/file/101"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let fileUri = await fileAccessHelper.move(sourceFile, destFile); console.log("Operation successful. fileUri: " + JSON.stringify(fileUri)); - } cache (error) { + } catch (error) { console.error("move failed, error " + error); }; ``` @@ -584,26 +594,29 @@ Renames a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to rename.| -| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or folder to rename.| + | displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the renamed file or folder.| +| Promise<string> | Promise used to return the URI of the renamed file or folder.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceDir = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let DestDir = await fileAccessHelper.rename(sourceDir, "testDir"); console.log("Operation successful. DestDir: " + JSON.stringify(DestDir)); - } cache (error) { + } catch (error) { console.error("rename failed, error " + error); }; ``` @@ -620,9 +633,9 @@ Checks whether a file or folder exists. This API uses a promise to return the re **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFileUri | string | Yes| URI of the file or folder.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFileUri | string | Yes| URI of the file or folder.| **Return value** @@ -633,15 +646,18 @@ Checks whether a file or folder exists. This API uses a promise to return the re **Example** ```js - // The URI of a shared disk is used as an example. - let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceDir = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let existJudgment = await fileAccessHelper.access(sourceDir); if (existJudgment) console.log("sourceDir exists"); else console.log("sourceDir does not exist"); - } cache (error) { + } catch (error) { console.error("rename failed, error " + error); }; ``` @@ -656,10 +672,6 @@ Obtains the next-level device root directory. **RootIterator** is an iterator ob **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** | Type| Description| @@ -676,10 +688,6 @@ Obtains the information about the next-level file or folder. **FileIterator** is **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** | Type| Description| @@ -720,7 +728,7 @@ Represents the file or folder attribute information and interface capabilities. | mode | number | Yes| No| Permissions on the file or folder.| | size | number | Yes| No| Size of the file or folder.| | mtime | number | Yes| No| Time when the file or folder was last modified.| -| mimeType | string | Yes| No| Media resource type of the file or folder.| +| mimeType | string | Yes| No| MIME type of the file or folder.| ## OPENFLAGS diff --git a/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md index fce0a93c72553be6306910412404e2fe09bc2290..43ccea2e0fadb8875acd0bbd18225d57a3ee62a8 100644 --- a/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md +++ b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md @@ -1,4 +1,4 @@ -# User File Extension Info +# @ohos.fileExtensionInfo The **fileExtensionInfo** module defines attributes in **RootInfo** and **FileInfo** of the user file access and management module. @@ -37,10 +37,10 @@ Defines the values of **deviceFlags** used in **RootInfo**. **deviceFlags** is u ### Attributes - | Name| Type | Value| Readable| Writable| Description | - | ------ | ------ | ---- | ---- | ---- | -------- | - | SUPPORTS_READ | number | 0b1 | Yes | No | Read support.| - | SUPPORTS_WRITE | number | 0b10 | Yes | No | Write support.| + | Name| Type | Readable| Writable| Description | + | ------ | ------ | ---- | ---- | -------- | + | SUPPORTS_READ | number | Yes | No | The device supports read.| + | SUPPORTS_WRITE | number | Yes | No | This device supports write.| ## fileExtensionInfo.DocumentFlag @@ -50,9 +50,9 @@ Defines the values of **mode** used in **FileInfo**. ### Attributes - | Name| Type | Value| Readable| Writable| Description | - | ------ | ------ | ---- | ---- | ---- | -------- | - | REPRESENTS_FILE | number | 0b1 | Yes | No | File.| - | REPRESENTS_DIR | number | 0b10 | Yes | No | Directory.| - | SUPPORTS_READ | number | 0b100 | Yes | No | Read support.| - | SUPPORTS_WRITE | number | 0b1000 | Yes | No | Write support.| + | Name| Type | Readable| Writable| Description | + | ------ | ------ | ---- | ---- | -------- | + | REPRESENTS_FILE | number | Yes | No | File.| + | REPRESENTS_DIR | number | Yes | No | Directory.| + | SUPPORTS_READ | number | Yes | No | This file is readable.| + | SUPPORTS_WRITE | number | Yes | No | This file is writable.| diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md index 5d22ce86255fa5bb680d4cf66c530a98fe4f215a..e102353bf8b19431fab51151c9c634916fa39ff4 100644 --- a/en/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -1,9 +1,8 @@ -# Geolocation Manager +# @ohos.geoLocationManager (Geolocation Manager) -The Geolocation Manager module provides location service management functions. +The **geoLocationManager** module provides location service management functions. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Applying for Permissions diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index a5c7034c0333cb640dbe1a51b7f5f6e6f63743ca..86b62bd76ff14cdd0aaa46d60f532b2b52220e4d 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,10 +1,11 @@ -# Geolocation +# @ohos.geolocation (Geolocation) -The Geolocation module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. +The **geolocation** module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. > **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. +> +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. ## Applying for Permissions diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index 24125f48cde82856302fc0b981b707c53387d54b..260c8c541809f723cee63a3cf7f7ce9374ff886d 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -1,4 +1,4 @@ -# HiAppEvent +# @ohos.hiAppEvent (Application Event Logging) The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 16c1d7b2ea9ca7327060d599da5fd0b6e89235ef..3a5687e9ee0b31e29450d72ad7f618a128b30050 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -1,6 +1,6 @@ -# HiChecker +# @ohos.hichecker (HiChecker) -HiChecker is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. +The **hichecker** module is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. > **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 7c9393e17557cc927cc880b2529c9e25966124af..189d855e894451790976eee2c3816cf17ae950b9 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,10 +1,10 @@ -# HiDebug +# @ohos.hidebug (HiDebug) -> **NOTE** -> +The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. + +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -The HiDebug module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index 66c180ce7fd431a39674276f2b1f20e406cfddb7..54355b12b723cf9cad06f5a4064568d5d772bea5 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,6 +1,6 @@ -# HiLog +# @ohos.hilog (HiLog) -The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. +The **hilog** module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index 50243525c010d6cbfcb3dd9ba9454f8ebb9dac65..b61207a81a9be58f9b8b405535e118757218529e 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -1,6 +1,6 @@ -# HiSysEvent +# @ohos.hiSysEvent (System Event Logging) -This module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file. +The **hiSysEvent** module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file. > **NOTE** > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md index aaf38a1962e65293b97f4fe18b4e93d68ef9d92a..b72b026ce908bbde85e385f46212d32e4a7fd61b 100644 --- a/en/application-dev/reference/apis/js-apis-hitracechain.md +++ b/en/application-dev/reference/apis/js-apis-hitracechain.md @@ -1,8 +1,8 @@ -# Distributed Call Chain Tracing +# @ohos.hiTraceChain (Distributed Call Chain Tracing) -This module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points. +The **hiTraceChain** module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index 04a9db2a0e7bc00cb9ff8a017eb6e39c47d97f30..af19e063a728abd4feb7d7238051d94ca49c2459 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -1,9 +1,8 @@ -# Performance Tracing +# @ohos.hiTraceMeter (Performance Tracing) -The Performance Tracing module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. +The **hiTraceMeter** module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md index 742c83b9c3fdedd2b8e3d8ef59df0535598478c0..86e09db17bda0e6efa68bbeeb973a26f4a4ff467 100644 --- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -1,8 +1,8 @@ -# Application Event Logging +# @ohos.hiviewdfx.hiAppEvent (Application Event Logging) -This module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. +The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 36faaa094260d0d86f065040f3a99de323fa3d00..3735792dd3f5ce66569fbebf3a1036019e7457ed 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -1,11 +1,9 @@ -# Data Request +# @ohos.net.http (Data Request) -This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. +The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. ->**NOTE** -> ->The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> **NOTE**
+> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 08bf0cfe66b40f46262765048463081b9c1a66a6..2a75e1015411c92c75f58d32dc236283fd24f266 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,10 +1,10 @@ -# Internationalization – I18N +# @ohos.i18n (Internationalization) -The I18N module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. -The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. +The **i18n** module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. +The [intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. -> **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -1054,7 +1054,7 @@ Creates a **PhoneNumberFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------- | | country | string | Yes | Country or region to which the phone number to be formatted belongs.| -| options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. | +| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | **Example** ```js @@ -1144,7 +1144,7 @@ Obtains the home location of a phone number. ``` -## PhoneNumberFormatOptions9+ +## PhoneNumberFormatOptions8+ Defines the options for this PhoneNumberFormat object. diff --git a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md index 90c03ba3418d2769a695f1bde26d1b2051279115..c281c62ff040c74bdc84def40b9db824ce95492a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md @@ -1,27 +1,35 @@ # AppStateData -The **AppStateData** module defines the application state data. +The **AppStateData** module defines the application state data, which can be obtained through [getForegroundApplications](js-apis-app-ability-appManager.md#appmanagergetforegroundapplications). **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This module is marked as @systemapi and not visible to third-party applications. -| Name | Type | Mandatory| Description | -| ----------- | -------- | ---- | ------------------------------------------------------------ | -| bundleName8+ | string | No | Bundle name of the application. | -| uid8+ | number | No | User ID.| -| state8+ | number | No | Application state.| +| Name | Type | Mandatory | Description | +| ------------------------- | ------ | ---- | --------- | +| bundleName8+ | string | No | Bundle name.| +| uid8+ | number | No | UID of the application. | +| state8+ | number | No | Application state.
**0**: The application is being initialized.
**1**: The application has been initialized and is ready.
**2**: The application is running in the foreground.
**3**: The application is having the focus. (This state is reserved.)
**4**: The application is running in the background.
**5**: The application has exited.| **Example** + ```ts -import appManager from "@ohos.application.appManager" +import appManager from "@ohos.app.ability.appManager" -appManager.getForegroundApplications((error, data) => { - for(let i=0; i { + if (error && error.code) { + console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + for (let i = 0; i < data.length; i++) { + let appStateData = data[i]; + console.log('appStateData.bundleName: ' + appStateData.bundleName); + console.log('appStateData.uid: ' + appStateData.uid); + console.log('appStateData.state: ' + appStateData.state); + } + }); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md index 1070334b0107b3e3e84101a287b7966f7e16dcff..a9f9e6cf9540c02ada58ea7e89f76b9c9c297efb 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -1,6 +1,6 @@ # MissionListener -The **MissionListener** module defines the listeners used to observe the mission status. +The **MissionListener** module defines the listeners used to observe the mission status. The listeners can be registered by using [on](js-apis-app-ability-missionManager.md#missionmanageron). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -16,7 +16,7 @@ The **MissionListener** module defines the listeners used to observe the mission **Example** ```ts -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.app.ability.missionManager' let listener = { onMissionCreated: function (mission) { @@ -38,5 +38,10 @@ let listener = { console.log("onMissionClosed mission: " + JSON.stringify(mission)); } }; -let listenerid = missionManager.registerMissionListener(listener); + +try { + let listenerId = missionManager.on("mission", listener); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md index e659a4d80e43f59f06bfe7a8357ab6675886fad6..5ca299f0ad5f9df4f5b460b30e9e34c7dad82d5d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -1,66 +1,12 @@ # TriggerInfo -The **TriggerInfo** module defines the information required for triggering the WantAgent. +The **TriggerInfo** module defines the information required for triggering the WantAgent. The information is used as an input parameter of [trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger). **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Mandatory| Description | | ---------- | --- |-------------------- | ----------- | -| code | number | Yes | Result code.| +| code | number | Yes | Custom result code provided for the target WantAgent.| | want | Want | No | Want. | | permission | string | No | Permission. | | extraInfo | {[key: string]: any} | No | Extra information. | - -**Example** -```ts -import wantAgent from '@ohos.wantAgent'; - -let wantAgentInfo = { - wants: [ - { - deviceId: "", - bundleName: "com.example.apicoverhaptest", - abilityName: "com.example.apicoverhaptest.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true.true,false}", - parameters: { - myKey0: 2222 - } - } - ], - operationType: wantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], - extraInfo:{ - "key": "value" - } -} - -let triggerInfo = { - code: 0, - want: { - deviceId: "", - bundleName: "com.example.apicoverhaptest", - abilityName: "com.example.apicoverhaptest.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true.true,false}", - parameters: { - myKey0: 2222 - } - }, - permission: "" - extraInfo:{ - "key": "value" - } -} - -wantAgent.trigger(wantAgentInfo, triggerInfo).then((data) =>{ - console.info("trigger data: " + JSON.stringify(data)); -}).catch((err) => { - console.error("trigger err: " + JSON.stringify(err)); -}) -``` diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index ef60fdc7decd8dc786ec79ad7bbbc32693509e2a..4de59dd1322f1cc83203ad38bc63746c81d56e8a 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,11 +1,9 @@ -# Input Consumer +# @ohos.multimodalInput.inputConsumer (Input Consumer) -The Input Consumer module implements listening for combination key events. +The **inputConsumer** module implements listening for combination key events. > **NOTE** -> > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> > - The APIs provided by this module are system APIs. diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index 29a9d739a1cd77bfd030beee38380dc870440444..c131d9bbd3e50790624d4eca0ea41c94d7022dd2 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -1,17 +1,12 @@ -# Input Device +# @ohos.multimodalInput.inputDevice (Input Device) +The **inputDevice** module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse. -The Input Device module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse. - - -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import - ```js import inputDevice from '@ohos.multimodalInput.inputDevice'; ``` diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md index 862c39c608ba76b56c23b675c9ef1da19c43331f..d2d55fa57ee6bd71288d03aa3f42e24bebb80bea 100644 --- a/en/application-dev/reference/apis/js-apis-inputevent.md +++ b/en/application-dev/reference/apis/js-apis-inputevent.md @@ -1,6 +1,6 @@ -# Input Event +# @ohos.multimodalInput.inputEvent (Input Event) -The Input Event module describes basic events reported by an input device. +The **inputEvent** module describes basic events reported by an input device. > **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index f4372d664aafbe2d55d4a35cc30d715b6d3be774..354f10e3802d163343b658bef56ab4e03689d2c3 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,11 +1,9 @@ -# Key Injection +# @ohos.multimodalInput.inputEventClient (Key Event Injection) -The Key Injection module implements injection of key events. +The **inputEventClient** module implements injection of key events. > **NOTE** -> > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> > - The APIs provided by this module are system APIs. diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 7bd41f5d0be2922df090f71651b1c4a15aafecb1..304fa76946de0e4279be5095bd1dae46f79c7ca6 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,11 +1,10 @@ -# Input Monitor +# @ohos.multimodalInput.inputMonitor (Input Monitor) -The Input Monitor module implements listening for events of input devices (namely, touchscreen and mouse). +The **inputMonitor** module implements listening for events of input devices (namely, touchscreen and mouse). > **NOTE** > > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> > - The APIs provided by this module are system APIs. diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index e3cb7bbfd684ae315d6d54363183401442f5167a..2034cae2ba7d64c6f593f937a4c944e39e5ac04c 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,12 +1,12 @@ -# Internationalization – Intl +# @ohos.intl (Internationalization) -The Intl module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. +The **intl** module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. -The [I18N](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. +The [i18n](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. -> **NOTE** -> -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -64,7 +64,7 @@ Creates a Locale object. | Name | Type | Mandatory | Description | | ------- | ------------- | ---- | ---------------------------- | | locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | +| options9+ | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | **Example** ``` @@ -135,7 +135,7 @@ Minimizes information of the **Locale** object. If the script and locale informa ``` -## LocaleOptions9+ +## LocaleOptions6+ Represents the locale options. @@ -181,7 +181,7 @@ Creates a **DateTimeOptions** object for the specified locale. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | +| options9+ | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | **Example** ``` @@ -265,7 +265,7 @@ Obtains the formatting options for **DateTimeFormat** object. | Type | Description | | ----------------------------------- | ----------------------------- | -| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| +| [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| **Example** ``` @@ -274,7 +274,7 @@ Obtains the formatting options for **DateTimeFormat** object. ``` -## DateTimeOptions9+ +## DateTimeOptions6+ Provides the options for the **DateTimeFormat** object. @@ -332,7 +332,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | +| options9+ | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | **Example** ``` @@ -380,7 +380,7 @@ Obtains the options of the **NumberFormat** object. | Type | Description | | ------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| +| [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| **Example** @@ -390,7 +390,7 @@ Obtains the options of the **NumberFormat** object. ``` -## NumberOptions9+ +## NumberOptions6+ Provides the device capability. @@ -449,7 +449,7 @@ Creates a Collator object. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | +| options9+ | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | **Example** ``` @@ -497,7 +497,7 @@ Returns properties reflecting the locale and collation options of a **Collator** | Type | Description | | ----------------------------------- | ----------------- | -| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| +| [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| **Example** @@ -507,7 +507,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ``` -## CollatorOptions9+ +## CollatorOptions8+ Represents the properties of a **Collator** object. @@ -553,7 +553,7 @@ Parameters | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | +| options9+ | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | **Example** ``` @@ -588,7 +588,7 @@ Obtains a string that represents the singular-plural type of the specified numbe ``` -## PluralRulesOptions9+ +## PluralRulesOptions8+ Represents the properties of a **PluralRules** object. @@ -635,7 +635,7 @@ Creates a **RelativeTimeFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------- | | locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | **Example** ``` @@ -720,7 +720,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects. ``` -## RelativeTimeFormatInputOptions9+ +## RelativeTimeFormatInputOptions8+ Represents the properties of a **RelativeTimeFormat** object. diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index 018046356b3df502c499726928b8b437e98fc81d..e69775942629948eab964f4f91795ddfe7dfeda7 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -1,6 +1,6 @@ -# Keycode +# @ohos.multimodalInput.keyCode (Key Code) -The Keycode module provides keycodes for a key device. +The **keyCode** module provides keycodes for a key device. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index 3cfb2440033aa8043801e986ade5b0bd28c475d3..32c18a558572b8f971b8faf6277c3300e86f9649 100644 --- a/en/application-dev/reference/apis/js-apis-keyevent.md +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -1,9 +1,8 @@ -# Key Event +# @ohos.multimodalInput.keyEvent (Key Event) -The Key Event module provides key events reported by an input device. +The **keyEvent** module provides key events reported by an input device. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-logs.md b/en/application-dev/reference/apis/js-apis-logs.md index e2d0aff5a5eec1f468b0511a08f1f593a9af3548..48cc7954e1b4315f0e12d9571395decf9592b90d 100644 --- a/en/application-dev/reference/apis/js-apis-logs.md +++ b/en/application-dev/reference/apis/js-apis-logs.md @@ -1,6 +1,6 @@ -# Log +# console (Log) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE**
> The APIs of this module are no longer maintained since API version 7. You are advised to use ['@ohos.hilog](js-apis-hilog.md)' instead. ## console.debug diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md index 97dd9e3f982d9f36d5feb6f17d59a40bb57e1a20..f5b9b27f55ed9d363939bef6f55582423afe4a28 100644 --- a/en/application-dev/reference/apis/js-apis-matrix4.md +++ b/en/application-dev/reference/apis/js-apis-matrix4.md @@ -145,11 +145,12 @@ Copies this matrix object. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().translate({x:100}) - private matrix2 = this.matrix1.copy().scale({x:2}) + private matrix1 = matrix4.identity().translate({ x: 100 }) + private matrix2 = this.matrix1.copy().scale({ x: 2 }) build() { Column() { @@ -160,7 +161,7 @@ struct Test { Image($r("app.media.bg2")) .width("40%") .height(100) - .margin({top:50}) + .margin({ top: 50 }) .transform(this.matrix2) } } @@ -199,11 +200,12 @@ Combines the effects of two matrices to generate a new matrix object. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().translate({x:200}).copy() - private matrix2 = matrix4.identity().scale({x:2}).copy() + private matrix1 = matrix4.identity().translate({ x: 200 }).copy() + private matrix2 = matrix4.identity().scale({ x: 2 }).copy() build() { Column() { @@ -211,13 +213,13 @@ struct Test { Image($r("app.media.icon")) .width("40%") .height(100) - .margin({top:50}) + .margin({ top: 50 }) // Translate the x-axis by 200px, and then scale it twice to obtain the resultant matrix. Image($r("app.media.icon")) .transform(this.matrix1.combine(this.matrix2)) .width("40%") - .height(100) - .margin({top:50}) + .height(100) + .margin({ top: 50 }) } } } @@ -245,8 +247,9 @@ Inverts this matrix object. ```ts import matrix4 from '@ohos.matrix4' // The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x). -let matrix1 = matrix4.identity().scale({x:2}) +let matrix1 = matrix4.identity().scale({ x: 2 }) let matrix2 = matrix1.invert() + @Entry @Component struct Tests { @@ -295,10 +298,11 @@ Translates this matrix object along the x, y, and z axes. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().translate({x:100, y:200, z:30}) + private matrix1 = matrix4.identity().translate({ x: 100, y: 200, z: 30 }) build() { Column() { @@ -346,7 +350,7 @@ import matrix4 from '@ohos.matrix4' @Entry @Component struct Test { - private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50}) + private matrix1 = matrix4.identity().scale({ x:2, y:3, z:4, centerX:50, centerY:50 }) build() { Column() { @@ -392,17 +396,18 @@ Rotates this matrix object along the x, y, and z axes. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30}) + private matrix1 = matrix4.identity().rotate({ x: 1, y: 1, z: 2, angle: 30 }) build() { Column() { Image($r("app.media.bg1")).transform(this.matrix1) .width("40%") .height(100) - }.width("100%").margin({top:50}) + }.width("100%").margin({ top: 50 }) } } ``` diff --git a/en/application-dev/reference/apis/js-apis-mouseevent.md b/en/application-dev/reference/apis/js-apis-mouseevent.md index d3d9e4c05e44c68bc7bc58caa5267ddb851cd9bb..92935d6f31e788eb0b71ec6529fbc94264e3d8d1 100644 --- a/en/application-dev/reference/apis/js-apis-mouseevent.md +++ b/en/application-dev/reference/apis/js-apis-mouseevent.md @@ -1,14 +1,14 @@ -# Mouse Event +# @ohos.multimodalInput.mouseEvent (Mouse Event) -Represents mouse events reported by an input device. +The **mouseEvent** module provides mouse events reported by an input device. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```js -import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mouseEvent'; +import { Action, Button, Axis, AxisValue, MouseEvent } from '@ohos.multimodalInput.mouseEvent'; ``` ## Action diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index bff6eb26654f551ab744bfdd7d988cb3b7a8f4f4..d5a5f1585a5ae153694833b611861cc49325c4e7 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -1,9 +1,8 @@ -# Network Connection Management +# @ohos.net.connection (Network Connection Management) -The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. +The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index 457fa931fd6550a7461d9a5c1f7bb40a41f7fe8b..d41845ec1859507bb96a071dff2a57e16f4cf12b 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -1,9 +1,8 @@ -# Ethernet Connection Management +# @ohos.net.ethernet (Ethernet Connection Management) -The Ethernet Connection Management module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. +The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index 9b0ceaead8faa59011bd2ec931e8fb5bd1477cbf..144ffa9c6e2d405c83e7cf14fdb7278c616759d3 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,9 +1,8 @@ -# Network Sharing Management +# @ohos.net.sharing (Network Sharing) -The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, and Bluetooth sharing. It also allows you to query the network sharing state and shared mobile data volume. +The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index ad7d19b4ab7a3cfa6593c81f2c70b52f403aa4d1..ae5b7999bd7e579179920a73fcaea6116890ff70 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -1,6 +1,6 @@ -# Observer +# @ohos.telephony.observer (Observer) -The observer module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. +The **observer** module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index ed71da2336509844e7baa5eea49f8a026e969eba..2435d0a39731803e7c8ba730f6547a125cfc8438 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -1,9 +1,8 @@ -# Mouse Pointer +# @ohos.multimodalInput.pointer (Mouse Pointer) -The mouse pointer module provides APIs related to pointer attribute management. +The **pointer** module provides APIs related to pointer attribute management. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -276,7 +275,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -319,7 +318,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -358,7 +357,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -396,7 +395,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index 1c78452681d08db91a4aa3ee4cf2aea785072191..4dc07d44197a78f01cb3e9018293cc1da88bea38 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -1,8 +1,8 @@ -# Power Manager +# @ohos.power (System Power Management) -The Power Manager module provides APIs for rebooting and shutting down the system, as well as querying the screen status. +The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -87,7 +87,7 @@ try { isActive(): boolean -Checks whether the current device is active. +Checks whether the current device is active. In the active state, the screen is on if the device has a screen and the device is not in sleep state if the device does not have a screen. **System capability:** SystemCapability.PowerManager.PowerManager.Core diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index cf518ed93a2aea668985ae96031b12d48e284811..4d7ffb05e886f6b908a771b091f83983452bcfed 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -1,4 +1,4 @@ -# Privacy Management +# @ohos.privacyManager (Privacy Management) The **privacyManager** module provides APIs for privacy management, such as management of permission usage records. diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 91c6be9cd7d076dbb72a502e64363d729668972f..dfb1dd75061b1bb272170b5dbd7c202d320ce304 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1,6 +1,6 @@ -# Radio +# @ohos.telephony.radio (Network Search) -The radio module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. +The **radio** module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 81717b6ebd1ed56470b9992e1f2fc69b546c035a..a861858ce8f2fd6979fe21860b62443ad3d2ee15 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,8 +1,8 @@ -# reminderAgent +# @ohos.reminderAgent The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. -You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. > **NOTE** > @@ -13,14 +13,16 @@ You can set your application to use the reminder agent APIs to create scheduled ## Modules to Import -```js +```ts import reminderAgent from'@ohos.reminderAgent'; ``` ## reminderAgent.publishReminder -publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void +```ts +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void +``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -33,14 +35,15 @@ 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<number> | Yes| Asynchronous callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Example** -```js +```ts let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + reminderAgent.publishReminder(timer, (err, reminderId) => { console.log("callback, reminderId = " + reminderId); }); @@ -49,7 +52,9 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ## reminderAgent.publishReminder -publishReminder(reminderReq: ReminderRequest): Promise<number> +```ts +publishReminder(reminderReq: ReminderRequest): Promise +``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -65,14 +70,15 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Example** -```js +```ts let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + reminderAgent.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); }); @@ -81,7 +87,9 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu ## reminderAgent.cancelReminder -cancelReminder(reminderId: number, callback: AsyncCallback<void>): void +```ts +cancelReminder(reminderId: number, callback: AsyncCallback): void +``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -92,11 +100,11 @@ 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<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts reminderAgent.cancelReminder(1, (err, data) => { console.log("cancelReminder callback"); }); @@ -105,7 +113,9 @@ reminderAgent.cancelReminder(1, (err, data) => { ## reminderAgent.cancelReminder -cancelReminder(reminderId: number): Promise<void> +```ts +cancelReminder(reminderId: number): Promise +``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -121,20 +131,21 @@ 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\ | Promise used to return the result.| **Example** -```js +```ts reminderAgent.cancelReminder(1).then(() => { console.log("cancelReminder promise"); }); ``` - ## reminderAgent.getValidReminders -getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void +```ts +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. @@ -144,11 +155,11 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| **Example** -```js +```ts reminderAgent.getValidReminders((err, reminders) => { console.log("callback, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -178,7 +189,9 @@ reminderAgent.getValidReminders((err, reminders) => { ## reminderAgent.getValidReminders -getValidReminders(): Promise<Array<ReminderRequest>> +```ts +getValidReminders(): Promise> +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -188,11 +201,11 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| **Example** -```js +```ts reminderAgent.getValidReminders().then((reminders) => { console.log("promise, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -222,7 +235,9 @@ reminderAgent.getValidReminders().then((reminders) => { ## reminderAgent.cancelAllReminders -cancelAllReminders(callback: AsyncCallback<void>): void +```ts +cancelAllReminders(callback: AsyncCallback): void +``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -232,11 +247,11 @@ 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\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts reminderAgent.cancelAllReminders((err, data) =>{ console.log("cancelAllReminders callback") }) @@ -245,7 +260,9 @@ reminderAgent.cancelAllReminders((err, data) =>{ ## reminderAgent.cancelAllReminders -cancelAllReminders(): Promise<void> +```ts +cancelAllReminders(): Promise +``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -255,20 +272,21 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts reminderAgent.cancelAllReminders().then(() => { console.log("cancelAllReminders promise") }) ``` - ## reminderAgent.addNotificationSlot -addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void +```ts +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void +``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -279,11 +297,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<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -297,7 +315,9 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ## reminderAgent.addNotificationSlot -addNotificationSlot(slot: NotificationSlot): Promise<void> +```ts +addNotificationSlot(slot: NotificationSlot): Promise +``` Adds a notification slot. This API uses a promise to return the result. @@ -313,11 +333,11 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -331,7 +351,9 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ## reminderAgent.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void +```ts +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void +``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -341,12 +363,12 @@ 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.| +| 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.| **Example** -```js +```ts import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { @@ -357,7 +379,9 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ## reminderAgent.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType): Promise<void> +```ts +removeNotificationSlot(slotType: notification.SlotType): Promise +``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -367,17 +391,17 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { @@ -392,7 +416,7 @@ Enumerates button types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | ACTION_BUTTON_TYPE_CLOSE | 0 | Button for closing the reminder.| | ACTION_BUTTON_TYPE_SNOOZE | 1 | Button for snoozing the reminder.| @@ -404,7 +428,7 @@ Enumerates reminder types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | REMINDER_TYPE_TIMER | 0 | Countdown reminder.| | REMINDER_TYPE_CALENDAR | 1 | Calendar reminder.| @@ -431,7 +455,7 @@ Sets the package and ability that are redirected to when the reminder notificati | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| +| 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.| @@ -443,7 +467,7 @@ Provides the information about the target package and ability to start automatic | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the HAP 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.| @@ -459,9 +483,9 @@ Defines the reminder to publish. | 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.| | 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.| -| snoozeTimes | number | No| Number of reminder snooze times.| -| timeInterval | number | No| Reminder snooze interval.| +| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| +| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| +| timeInterval | number | No| Reminder snooze interval, in seconds. The default value is **0**.| | title | string | No| Reminder title.| | content | string | No| Reminder content.| | expiredContent | string | No| Content to be displayed after the reminder expires.| @@ -481,8 +505,8 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array<number> | No| Month in which the reminder repeats.| -| repeatDays | Array<number> | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm @@ -497,7 +521,7 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats.| +| 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.| ## ReminderRequestTimer diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 7886c278e8870986e83535886e680cd1d631d302..7b8db156f8b609f2bc62d751a71623abc990c65f 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,8 +1,8 @@ -# reminderAgentManager +# @ohos.reminderAgentManager The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. -You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. > **NOTE** > @@ -11,14 +11,16 @@ You can set your application to use the reminder agent APIs to create scheduled ## Modules to Import -``` +```ts import reminderAgentManager from'@ohos.reminderAgentManager'; ``` ## reminderAgentManager.publishReminder -publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void +```ts +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void +``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -31,7 +33,7 @@ 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<number> | Yes| Asynchronous callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Error codes** @@ -43,11 +45,12 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | 1700002 | The number of reminders exceeds the limit. | **Example** -```js +```ts let timer = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + try { reminderAgentManager.publishReminder(timer, (err, reminderId) => { if (err) { @@ -64,7 +67,9 @@ try { ## reminderAgentManager.publishReminder -publishReminder(reminderReq: ReminderRequest): Promise<number> +```ts +publishReminder(reminderReq: ReminderRequest): Promise +``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -80,7 +85,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Error codes** @@ -92,11 +97,12 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | 1700002 | The number of reminders exceeds the limit. | **Example** -```js +```ts let timer = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + try { reminderAgentManager.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); @@ -111,7 +117,9 @@ try { ## reminderAgentManager.cancelReminder -cancelReminder(reminderId: number, callback: AsyncCallback<void>): void +```ts +cancelReminder(reminderId: number, callback: AsyncCallback): void +``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -122,7 +130,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\ | Yes| Asynchronous callback used to return the result.| **Error codes** @@ -135,7 +143,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelReminder(1, (err, data) => { if (err) { @@ -152,7 +160,9 @@ try { ## reminderAgentManager.cancelReminder -cancelReminder(reminderId: number): Promise<void> +```ts +cancelReminder(reminderId: number): Promise +``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -168,7 +178,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\ | Promise used to return the result.| **Error codes** @@ -181,7 +191,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelReminder(1).then(() => { console.log("cancelReminder promise"); @@ -193,10 +203,12 @@ try { }; ``` - ## reminderAgentManager.getValidReminders -getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void +```ts +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. @@ -206,7 +218,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| **Error codes** @@ -218,7 +230,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.getValidReminders((err, reminders) => { if (err) { @@ -253,10 +265,11 @@ try { }; ``` - ## reminderAgentManager.getValidReminders -getValidReminders(): Promise<Array<ReminderRequest>> +```ts +getValidReminders(): Promise> +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -266,7 +279,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| **Error codes** @@ -278,7 +291,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.getValidReminders().then((reminders) => { console.log("promise, getValidReminders length = " + reminders.length); @@ -314,7 +327,9 @@ try { ## reminderAgentManager.cancelAllReminders -cancelAllReminders(callback: AsyncCallback<void>): void +```ts +cancelAllReminders(callback: AsyncCallback): void +``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -324,7 +339,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\ | Yes| Asynchronous callback used to return the result.| **Error codes** @@ -336,7 +351,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelAllReminders((err, data) =>{ if (err) { @@ -353,7 +368,9 @@ try { ## reminderAgentManager.cancelAllReminders -cancelAllReminders(): Promise<void> +```ts +cancelAllReminders(): Promise +``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -363,7 +380,7 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Error codes** @@ -375,7 +392,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelAllReminders().then(() => { console.log("cancelAllReminders promise") @@ -390,7 +407,9 @@ try { ## reminderAgentManager.addNotificationSlot -addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void +```ts +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void +``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -401,11 +420,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<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -427,7 +446,9 @@ try { ## reminderAgentManager.addNotificationSlot -addNotificationSlot(slot: NotificationSlot): Promise<void> +```ts +addNotificationSlot(slot: NotificationSlot): Promise +``` Adds a notification slot. This API uses a promise to return the result. @@ -443,11 +464,11 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -467,7 +488,9 @@ try { ## reminderAgentManager.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void +```ts +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void +``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -478,11 +501,11 @@ 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\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' try { @@ -501,7 +524,9 @@ try { ## reminderAgentManager.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType): Promise<void> +```ts +removeNotificationSlot(slotType: notification.SlotType): Promise +``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -517,11 +542,11 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' try { @@ -580,7 +605,7 @@ Sets the package and ability that are redirected to when the reminder notificati | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| +| 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.| @@ -592,7 +617,7 @@ Provides the information about the target package and ability to start automatic | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the HAP 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.| @@ -608,9 +633,9 @@ Defines the reminder to publish. | 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.| | 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.| -| snoozeTimes | number | No| Number of reminder snooze times.| -| timeInterval | number | No| Reminder snooze interval, in seconds.| +| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| +| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| +| timeInterval | number | No| Reminder snooze interval, in seconds. The default value is **0**.| | title | string | No| Reminder title.| | content | string | No| Reminder content.| | expiredContent | string | No| Content to be displayed after the reminder expires.| @@ -630,8 +655,8 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array<number> | No| Month in which the reminder repeats.| -| repeatDays | Array<number> | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm @@ -646,7 +671,7 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| 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.| +| 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.| ## ReminderRequestTimer diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 5cf97609d706bcf49319962f204635c04ca23663..d3a0eeb30ea75a3109b6917d50b7b1d24cdd2fb4 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -1,9 +1,8 @@ -# @ohos.request +# @ohos.request (Upload and Download) The **request** module provides applications with basic upload, download, and background transmission agent capabilities. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 865f1104386664ce5b4cafede20ec54ffab711a6..7dc343709c19421175b4f99e6308c1c0ad90e5dd 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,4 +1,4 @@ -# Resource Manager +# @ohos.resourceManager (Resource Manager) The Resource Manager module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density. @@ -15,10 +15,8 @@ import resourceManager from '@ohos.resourceManager'; ## Instruction -Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object. - -For details about how to reference **context** in the stage model, see Context in the Stage Model. - +Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. +For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). ```ts import Ability from '@ohos.application.Ability'; diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 75d75ddb09e5c9e7d5d7028b02295cf24e8cf57e..11bb575b307023f70b92935d98f94cab013998ad 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -804,7 +804,7 @@ router.replace({ }); ``` - ## router.replace(deprecated) +## router.replace(deprecated) replace(options: RouterOptions, mode: RouterMode): void diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 94757432a9c16fa471fb98629b63387594542e65..8fc776d5508dccfd04155a3952936743de8e711c 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,6 +1,6 @@ -# @ohos.rpc +# @ohos.rpc (RPC) -The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. +The **rpc** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index e3718c5878ccae3e63f8bdfae8b37061599fffda..ee70e09ca874602bf8e41f3d4001b61caa5a0344 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,8 +1,8 @@ -# RunningLock +# @ohos.runningLock (Runninglock) -The RunningLock module provides APIs for creating, querying, holding, and releasing running locks. +The **runningLock** module provides APIs for creating, querying, holding, and releasing running locks. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index 9dcef8737df6eec61080fdbc7569ed7d4eb4a238..c726ec7c8fdd4cd6f16d71f5a6892bc565b66cf6 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,4 +1,4 @@ -# @ohos.screenLock +# @ohos.screenLock (Screenlock) The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set. diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 0f5d909e9b038c65bcd353afae633495a9bd2c4b..e9022ac7d23c3f213487da532d92a369c17a5c48 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -1,6 +1,6 @@ -# Screen +# @ohos.screen (Screen) -The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. +The **screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 81c05044174b46f17b6d5224f923167256290e4f..eb88ca8c05459fca0ba2ecd4dfcab60d49677aae 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -1,6 +1,6 @@ -# SIM Management +# @ohos.telephony.sim (SIM Management) -The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. +The **sim** module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index c26311312c5cc2360ddf4f3784f66bba05b0f5b1..901e3b258b7aa73530935baa81a6366f7aa50e65 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -1,6 +1,6 @@ -# SMS +# @ohos.telephony.sms (SMS) -The SMS module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. +The **sms** module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 32c4d78bfbd2fbace12d6294d03488f06aed27ba..bd14137464ce195f5c61b9d6a53ce6ef79cd3f10 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,7 +1,8 @@ -# Socket Connection +# @ohos.net.socket (Socket Connection) -> **NOTE** -> +The **socket** module implements socket connection management and operation. + +> **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 86675315d63423d728d2db90afd6b049614ee80a..c54d9d4b01fec93df43f92f47eab8aaae951fb4e 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -1,4 +1,4 @@ -# App Storage Statistics +# @ohos.storageStatistics (App Storage Statistics) The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md index e0cf8d10a1e79872dc6d59a908281610fd01ba23..fafd6ee8d27ded9366e6fec85b21274316f63f8b 100644 --- a/en/application-dev/reference/apis/js-apis-system-app.md +++ b/en/application-dev/reference/apis/js-apis-system-app.md @@ -1,6 +1,6 @@ -# Application Context +# @system.app -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** > - The APIs of this module are no longer maintained since API version 7. You are advised to use the new APIs. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -9,8 +9,8 @@ ## Modules to Import -``` -import app from '@system.app'; +```ts +import app from '@system.app' ``` @@ -20,7 +20,9 @@ getInfo(): AppResponse Obtains the declared information in the **config.json** file of an application. -> **Note: ** [`@ohos.bundle`](js-apis-Bundle.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.bundle](js-apis-Bundle.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Lite @@ -32,13 +34,13 @@ Obtains the declared information in the **config.json** file of an application. **Example** - ``` - export default { - getInfo(){ - var info = app.getInfo(); - console.log(JSON.stringify(info)); - } + ```ts +export default { + getInfo() { + let info = app.getInfo() + console.log(JSON.stringify(info)) } +} ``` ## app.terminate @@ -47,17 +49,20 @@ terminate(): void Terminates the current ability. -> **Note: ** [`@ohos.ability.featureAbility`](js-apis-featureAbility.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.ability.featureAbility](js-apis-ability-featureAbility.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Lite **Example** - ``` - export default { - terminate(){ - app.terminate(); - }} + ```ts +export default { + terminate() { + app.terminate() + } +} ``` ## app.requestFullWindow @@ -67,7 +72,9 @@ Requests the application to run in full window. You can call this API when the F This is a system API and cannot be called by third-party applications. -> **Note: ** [`@ohos.window`](js-apis-window.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.window](js-apis-window.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -78,13 +85,14 @@ This is a system API and cannot be called by third-party applications. **Example** - ``` - export default { - requestFullWindow(){ - app.requestFullWindow({ - duration: 200}); - } + ```ts +export default { + requestFullWindow() { + app.requestFullWindow({ + duration: 200 + }) } +} ``` ## app.setImageCacheCount7+ @@ -102,19 +110,19 @@ Sets the maximum number of decoded images that can be cached in the memory to sp **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## app.setImageRawDataCacheSize7+ @@ -132,20 +140,20 @@ Sets the maximum size (in bytes) of the image data cached in the memory before d **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageRawDataCacheSize(104857600) - // Set the upper limit of the memory for caching image data before decoding to 100 MB. (100 x 1024 x 1024 B =104857600 B = 100 MB). - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageRawDataCacheSize(104857600) + // Set the upper limit of the memory for caching image data before decoding to 100 MB. (100 x 1024 x 1024 B =104857600 B = 100 MB). + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## app.setImageFileCacheSize7+ @@ -163,20 +171,20 @@ Sets the maximum size of the image file cache (in bytes) to speed up the loading **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageFileCacheSize(209715200) - // Set the upper limit of the image file cache to 200 MB. (200 x 1024 x 1024 B= 209715200 B = 200 MB). - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageFileCacheSize(209715200) + // Set the upper limit of the image file cache to 200 MB. (200 x 1024 x 1024 B= 209715200 B = 200 MB). + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## AppResponse @@ -213,4 +221,4 @@ Defines the options of the **RequestFullWindow** API. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| duration | number | Yes| Number of animation options.| +| duration | number | Yes| Duration of an animation, in milliseconds.| diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md index 31959da80f23b90f54ea10883417eec202152d1a..d673a500027654075ff330c916cd22add25abaf6 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -1,6 +1,6 @@ -# Battery Info +# @system.battery (Battery Information) -This module allows you to query the charging status and remaining power of a device. +The **battery** module allows you to query the charging status and remaining power of a device. > **NOTE** > - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md index 2773c74397046c44784b65cc458be75eef8c21ea..939e7d7021bc8f93ad7359004de58f525feeee05 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,6 +1,6 @@ -# Screen Brightness +# @system.brightness (Screen Brightness) -This module provides APIs for querying and adjusting the screen brightness and mode. +The **brightness** module provides APIs for querying and adjusting the screen brightness and mode. > **NOTE** > - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-system-capability.md b/en/application-dev/reference/apis/js-apis-system-capability.md new file mode 100644 index 0000000000000000000000000000000000000000..7949bae9880af5a8e428e62440595a4a6e990da7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-capability.md @@ -0,0 +1,79 @@ +# @ohos.systemCapability (SystemCapability) + +System capability (SysCap) refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. This module provides APIs for querying the set of system capabilities. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. + + +## Modules to Import + +```ts +import systemcapability from '@ohos.systemCapability' +``` + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(callback: AsyncCallback): void; + +Queries system capabilities. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Developtools.Syscap + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback | Yes| Callback invoked to return the result.| + + +**Example** + +```ts +try { + systemcapability.querySystemCapabilities(function (err, data) { + if (err == undefined) { + console.log("get system capabilities:" + data) + } else { + console.log(" get system capabilities err:" + err.code) + }}); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(): Promise<string> + +Queries system capabilities. This API uses a promise to return the result. + +**System capability**: SystemCapability.Startup.SystemInfo + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the result.| + +**Example** + +```ts +try { + var p = systemcapability.querySystemCapabilities(); + p.then(function (value) { + console.log("get system capabilities: " + value); + }).catch(function (err) { + console.log("get system capabilities error: " + err.code); + }); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +> **NOTE** +> - The system capabilities returned by the preceding APIs are in the form of an encoded numeric string. diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index 6812d87828d55851d375eadba9dab6b2de55560a..dddb6a685f00a8a5a1829e489d43af4a198bdffa 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,6 +1,6 @@ -# Encryption Algorithm +# @system.cipher (Cipher Algorithm) -> **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -31,7 +31,7 @@ Defines the input parameters of **cipher.rsa()**. | Name | Type | Mandatory| Description | | -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.| -| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.| +| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length.
For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding. | | key | string | Yes | RSA key. It is a public key in encryption and a private key in decryption. | | transformation | string | No | RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| | success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. | diff --git a/en/application-dev/reference/apis/js-apis-system-date-time.md b/en/application-dev/reference/apis/js-apis-system-date-time.md new file mode 100644 index 0000000000000000000000000000000000000000..90c915b32ee35f9d09f6fe0453c962b985f914f1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-date-time.md @@ -0,0 +1,665 @@ +# @ohos.systemDateTime + +The **systemDateTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import systemDateTime from '@ohos.systemDateTime'; +``` + +## systemDateTime.setTime + +setTime(time : number, callback : AsyncCallback<void>) : void + +Sets the system time. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ---------------- | +| time | number | Yes | Timestamp to set, in milliseconds. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +// Set the system time to 2021-01-20 02:36:25. +let time = 1611081385000; +try { + systemDateTime.setTime(time, (error) => { + if (error) { + console.info(`Failed to set time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting time`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setTime + +setTime(time : number) : Promise<void> + +Sets the system time. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| time | number | Yes | Timestamp to set, in milliseconds.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +// Set the system time to 2021-01-20 02:36:25. +let time = 1611081385000; +try { + systemDateTime.setTime(time).then(() => { + console.info(`Succeeded in setting time.`); + }).catch((error) => { + console.info(`Failed to set time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void + +Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ------------------ | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | + +**Example** + +```js +try { + systemDateTime.getCurrentTime(true, (error, time) => { + if (error) { + console.info(`Failed to get currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ---------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | + +**Example** + +```js +try { + systemDateTime.getCurrentTime((error, time) => { + if (error) { + console.info(`Failed to get currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(isNano?: boolean): Promise<number> + +Obtains the time elapsed since the Unix epoch. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------- | +| Promise<number> | Promise used to return the time elapsed since the Unix epoch.| + +**Example** + +```js +try { + systemDateTime.getCurrentTime().then((time) => { + console.info(`Succeeded in getting currentTime : ${time}`); + }).catch((error) => { + console.info(`Failed to get currentTime. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------- | ---- | -------------------------- | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime(true, (error, time) => { + if (error) { + console.info(`Failed to get real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +getRealActiveTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | --------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime((error, time) => { + if (error) { + console.info(`Failed to get real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +getRealActiveTime(isNano?: boolean): Promise<number> + +Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| -------------- | -------------------------------- | +| Promise<number> | Promise used to return the time elapsed since system startup, excluding the deep sleep time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime().then((time) => { + console.info(`Succeeded in getting real active time : ${time}`); + }).catch((error) => { + console.info(`Failed to get real active time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealTime + +getRealTime(isNano: boolean, callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, including the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | ------------------------------- | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + +```js +try { + systemDateTime.getRealTime(true, (error, time) => { + if (error) { + console.info(`Failed to get real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealTime + +getRealTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, including the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------- | ---- | --------------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + +```js +try { + systemDateTime.getRealTime((error, time) => { + if (error) { + console.info(`Failed to get real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealTime + +getRealTime(isNano?: boolean): Promise<number> + +Obtains the time elapsed since system startup, including the deep sleep time. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the time elapsed since system startup, including the deep sleep time.| + +**Example** + +```js +try { + systemDateTime.getRealTime().then((time) => { + console.info(`Succeeded in getting real time : ${time}`); + }).catch((error) => { + console.info(`Failed to get real time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setDate + +setDate(date: Date, callback: AsyncCallback<void>): void + +Sets the system date. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | --------------------- | +| date | Date | Yes | Target date to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +let date = new Date(); +try { + systemDateTime.setDate(date, (error) => { + if (error) { + console.info(`Failed to set date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting date.`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setDate + +setDate(date: Date): Promise<void> + +Sets the system date. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------- | +| date | Date | Yes | Target date to set.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let date = new Date(); +try { + systemDateTime.setDate(date).then(() => { + console.info(`Succeeded in setting date.`); + }).catch((error) => { + console.info(`Failed to set date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getDate + +getDate(callback: AsyncCallback<Date>): void + +Obtains the current system date. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | --------------------- | +| callback | AsyncCallback<Date> | Yes | Callback used to return the current system date.| + +**Example** + +```js +try { + systemDateTime.getDate((error, date) => { + if (error) { + console.info(`Failed to get date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting date : ${date}`);; + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getDate + +getDate(): Promise<Date> + +Obtains the current system date. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------------------- | +| Promise<Date> | Promise used to return the current system date.| + +**Example** + +```js +try { + systemDateTime.getDate().then((date) => { + console.info(`Succeeded in getting date : ${date}`); + }).catch((error) => { + console.info(`Failed to get date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setTimezone + +setTimezone(timezone: string, callback: AsyncCallback<void>): void + +Sets the system time zone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | -------------------------- | +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones). | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + systemDateTime.setTimezone('Asia/Shanghai', (error) => { + if (error) { + console.info(`Failed to set timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting timezone.`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setTimezone + +setTimezone(timezone: string): Promise<void> + +Sets the system time zone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +try { + systemDateTime.setTimezone('Asia/Shanghai').then(() => { + console.info(`Succeeded in setting timezone.`); + }).catch((error) => { + console.info(`Failed to set timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getTimezone + +getTimezone(callback: AsyncCallback<string>): void + +Obtains the system time zone. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------- | ---- | ------------------------ | +| callback | AsyncCallback<string> | Yes | Callback used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Example** + +```js +try { + systemDateTime.getTimezone((error, data) => { + if (error) { + console.info(`Failed to get timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in get timezone : ${data}`);; + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getTimezone + +getTimezone(): Promise<string> + +Obtains the system time zone. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------- | +| Promise<string> | Promise used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Example** + +```js +try { + systemDateTime.getTimezone().then((data) => { + console.info(`Succeeded in getting timezone: ${data}`); + }).catch((error) => { + console.info(`Failed to get timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} +``` + +## Supported System Time Zones + +The following table lists the supported system time zones and the respective offset (unit: h) between each time zone and time zone 0. + +| Time Zone | Offset | +| ------------------------------ | --------------------- | +| Antarctica/McMurdo | 12 | +| America/Argentina/Buenos_Aires | -3 | +| Australia/Sydney | 10 | +| America/Noronha | -2 | +| America/St_Johns | -3 | +| Africa/Kinshasa | 1 | +| America/Santiago | -3 | +| Asia/Shanghai | 8 | +| Asia/Nicosia | 3 | +| Europe/Berlin | 2 | +| America/Guayaquil | -5 | +| Europe/Madrid | 2 | +| Pacific/Pohnpei | 11 | +| America/Godthab | -2 | +| Asia/Jakarta | 7 | +| Pacific/Tarawa | 12 | +| Asia/Almaty | 6 | +| Pacific/Majuro | 12 | +| Asia/Ulaanbaatar | 8 | +| America/Mexico_City | -5 | +| Asia/Kuala_Lumpur | 8 | +| Pacific/Auckland | 12 | +| Pacific/Tahiti | -10 | +| Pacific/Port_Moresby | 10 | +| Asia/Gaza | 3 | +| Europe/Lisbon | 1 | +| Europe/Moscow | 3 | +| Europe/Kiev | 3 | +| Pacific/Wake | 12 | +| America/New_York | -4 | +| Asia/Tashkent | 5 | diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index 60e999026e58bb6510a24540609f9c6bc44aa55d..1d47c8883ae8d3cc4be49d19845ce1b3e3d5bb2a 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -1,4 +1,4 @@ -# Page Routing +# @system.router The **Router** module provides APIs to access pages through URIs. @@ -43,8 +43,8 @@ export default { data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } }); } } @@ -67,7 +67,8 @@ export default { } ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The page routing stack supports a maximum of 32 pages. @@ -94,8 +95,8 @@ export default { router.replace({ uri: 'pages/detail/detail', params: { - data1: 'message', - }, + data1: 'message' + } }); } } @@ -135,7 +136,7 @@ Returns to the previous page or a specified page. export default { indexPushPage() { router.push({ - uri: 'pages/detail/detail', + uri: 'pages/detail/detail' }); } } @@ -147,7 +148,7 @@ export default { export default { detailPushPage() { router.push({ - uri: 'pages/mall/mall', + uri: 'pages/mall/mall' }); } } @@ -183,7 +184,8 @@ export default { } ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. ## router.getParams @@ -237,7 +239,7 @@ Obtains the number of pages in the current stack. ```js export default { getLength() { - var size = router.getLength(); + let size = router.getLength(); console.log('pages stack size = ' + size); } } @@ -262,7 +264,7 @@ Obtains state information about the current page. ```js export default { getState() { - var page = router.getState(); + let page = router.getState(); console.log('current index = ' + page.index); console.log('current name = ' + page.name); console.log('current path = ' + page.path); @@ -296,7 +298,7 @@ export default { }, cancel: function() { console.log('cancel'); - }, + } }); } } @@ -327,7 +329,7 @@ export default { }, cancel: function() { console.log('cancel'); - }, + } }); } } @@ -339,10 +341,10 @@ Defines the page routing parameters. **System capability**: SystemCapability.ArkUI.ArkUI.Lite -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| uri | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| -| params | Object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| +| Name | Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| uri | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| +| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| ## BackRouterOptions @@ -351,10 +353,10 @@ Defines the parameters for routing back. **System capability**: The items in the table below require different system capabilities. For details, see the table. -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| -| params | Object | No | Data that needs to be passed to the target page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| +| Name | Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| +| params | object | No | Data that needs to be passed to the target page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| ## RouterState diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index 4ce32e28d400e7fb0c954c1a99fed88e5f625dd2..a1876af97b532bf208eb405ee9c7c22edda6919f 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,4 +1,4 @@ -# System Time and Time Zone +# @ohos.systemTime The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. @@ -12,7 +12,7 @@ The **systemTime** module provides system time and time zone features. You can u import systemTime from '@ohos.systemTime'; ``` -## systemTime.setTime +## systemTime.setTime(deprecated) setTime(time : number, callback : AsyncCallback<void>) : void @@ -34,16 +34,20 @@ Sets the system time. This API uses an asynchronous callback to return the resul ```js // Set the system time to 2021-01-20 02:36:25. let time = 1611081385000; -systemTime.setTime(time, (error, data) => { - if (error) { - console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); -}); +try { + systemTime.setTime(time, (error) => { + if (error) { + console.info(`Failed to setting time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting time`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setTime +## systemTime.setTime(deprecated) setTime(time : number) : Promise<void> @@ -70,19 +74,27 @@ Sets the system time. This API uses a promise to return the result. ```js // Set the system time to 2021-01-20 02:36:25. let time = 1611081385000; -systemTime.setTime(time).then((data) => { - console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.setTime(time).then(() => { + console.info(`Succeeded in setting time.`); + }).catch((error) => { + console.info(`Failed to setting time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. 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 [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -95,21 +107,29 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal **Example** ```js -systemTime.getCurrentTime(true, (error, data) => { - if (error) { - console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getCurrentTime(true, (error, time) => { + if (error) { + console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) getCurrentTime(callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. 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 [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime-1). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -121,21 +141,29 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal **Example** ```js -systemTime.getCurrentTime((error, data) => { - if (error) { - console.error(`Succeeded in getting systemTime. Data:` + JSON.stringify(error)); - return; - } - console.log(`Failed to get systemTime. Cause:` + JSON.stringify(data)); -}); +try { + systemTime.getCurrentTime((error, time) => { + if (error) { + console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) getCurrentTime(isNano?: boolean): Promise<number> Obtains the time elapsed since the Unix epoch. 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 [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime-2). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -153,19 +181,27 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return **Example** ```js -systemTime.getCurrentTime().then((data) => { - console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getCurrentTime().then((time) => { + console.info(`Succeeded in getting currentTime : ${time}`); + }).catch((error) => { + console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, excluding the deep sleep time. 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 [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -178,21 +214,29 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th **Example** ```js -systemTime.getRealActiveTime(true, (error, data) => { - if (error) { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealActiveTime(true, (error, time) => { + if (error) { + console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) getRealActiveTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, excluding the deep sleep time. 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 [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime-1). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -204,21 +248,29 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th **Example** ```js -systemTime.getRealActiveTime((error, data) => { - if (error) { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealActiveTime((error, time) => { + if (error) { + console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) getRealActiveTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system startup, excluding the deep sleep time. 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 [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime-2). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -236,19 +288,27 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th **Example** ```js -systemTime.getRealActiveTime().then((data) => { - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getRealActiveTime().then((time) => { + console.info(`Succeeded in getting real active time : ${time}`); + }).catch((error) => { + console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) getRealTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, including the deep sleep time. 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 [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -261,21 +321,29 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th **Example** ```js -systemTime.getRealTime(true, (error, data) => { - if (error) { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealTime(true, (error, time) => { + if (error) { + console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) getRealTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, including the deep sleep time. 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 [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime-1). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -287,28 +355,36 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th **Example** ```js -systemTime.getRealTime((error, data) => { - if (error) { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealTime((error, time) => { + if (error) { + console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system startup, including the deep sleep time. 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 [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime-2). + **System capability**: SystemCapability.MiscServices.Time **Parameters** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.<
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| **Return value** @@ -319,14 +395,18 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th **Example** ```js -systemTime.getRealTime().then((data) => { - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getRealTime().then((time) => { + console.info(`Succeeded in getting real time : ${time}`); + }).catch((error) => { + console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setDate +## systemTime.setDate(deprecated) setDate(date: Date, callback: AsyncCallback<void>): void @@ -346,17 +426,21 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Example** ```js -let data = new Date(); -systemTime.setDate(data,(error, data) => { - if (error) { - console.error('Failed to set system date. Cause:' + JSON.stringify(error)); - return; -} - console.info('Succeeded in setting system date. Data:' + JSON.stringify(data)); -}); +let date = new Date(); +try { + systemTime.setDate(date, (error) => { + if (error) { + console.info(`Failed to setting date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting date.`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setDate +## systemTime.setDate(deprecated) setDate(date: Date): Promise<void> @@ -381,20 +465,28 @@ Sets the system date. This API uses a promise to return the result. **Example** ```js -let data = new Date(); -systemTime.setDate(data).then((value) => { - console.log(`Succeeded in setting system date. Data:` + JSON.stringify(value)); -}).catch((error) => { - console.error(`Failed to set system date. Cause:` + JSON.stringify(error)); -}); +let date = new Date(); +try { + systemTime.setDate(date).then(() => { + console.info(`Succeeded in setting date.`); + }).catch((error) => { + console.info(`Failed to setting date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getDate8+ +## systemTime.getDate(deprecated) getDate(callback: AsyncCallback<Date>): void Obtains the current system date. 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 [systemDateTime.getDate](./js-apis-system-date-time.md#systemdatetimegetdate). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -406,21 +498,29 @@ Obtains the current system date. This API uses an asynchronous callback to retur **Example** ```js -systemTime.getDate((error, data) => { - if (error) { - console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getDate((error, date) => { + if (error) { + console.info(`Failed to get date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in get date : ${date}`);; + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getDate8+ +## systemTime.getDate(deprecated) getDate(): Promise<Date> Obtains the current system date. 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 [systemDateTime.getDate](./js-apis-system-date-time.md#systemdatetimegetdate-1). + **System capability**: SystemCapability.MiscServices.Time **Return value** @@ -432,14 +532,18 @@ Obtains the current system date. This API uses a promise to return the result. **Example** ```js -systemTime.getDate().then((data) => { - console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getDate().then((date) => { + console.info(`Succeeded in getting date : ${date}`); + }).catch((error) => { + console.info(`Failed to getting date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setTimezone +## systemTime.setTimezone(deprecated) setTimezone(timezone: string, callback: AsyncCallback<void>): void @@ -459,16 +563,20 @@ Sets the system time zone. This API uses an asynchronous callback to return the **Example** ```js -systemTime.setTimezone('Asia/Shanghai', (error, data) => { - if (error) { - console.error('Failed to set system time zone. Cause:' + JSON.stringify(error)); - return; - } - console.info('Succeeded in setting system time zone. Data:' + JSON.stringify(data)); -}); +try { + systemTime.setTimezone('Asia/Shanghai', (error) => { + if (error) { + console.info(`Failed to setting timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting timezone.`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setTimezone +## systemTime.setTimezone(deprecated) setTimezone(timezone: string): Promise<void> @@ -493,19 +601,27 @@ Sets the system time zone. This API uses a promise to return the result. **Example** ```js -systemTime.setTimezone('Asia/Shanghai').then((data) => { - console.log(`Succeeded in setting system time zone. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to set system time zone. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.setTimezone('Asia/Shanghai').then(() => { + console.info(`Succeeded in setting timezone.`); + }).catch((error) => { + console.info(`Failed to setting timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getTimezone8+ +## systemTime.getTimezone(deprecated) getTimezone(callback: AsyncCallback<string>): void Obtains the system time zone. 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 [systemDateTime.getTimezone](./js-apis-system-date-time.md#systemdatetimegettimezone). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -517,21 +633,29 @@ Obtains the system time zone. This API uses an asynchronous callback to return t **Example** ```js -systemTime.getTimezone((error, data) => { - if (error) { - console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getTimezone((error, data) => { + if (error) { + console.info(`Failed to get timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in get timezone : ${data}`);; + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getTimezone8+ +## systemTime.getTimezone(deprecated) getTimezone(): Promise<string> Obtains the system time zone. 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 [systemDateTime.getTimezone](./js-apis-system-date-time.md#systemdatetimegettimezone-1). + **System capability**: SystemCapability.MiscServices.Time **Return value** @@ -543,11 +667,15 @@ Obtains the system time zone. This API uses a promise to return the result. **Example** ```js -systemTime.getTimezone().then((data) => { - console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getTimezone().then((data) => { + console.info(`Succeeded in getting timezone: ${data}`); + }).catch((error) => { + console.info(`Failed to getting timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} ``` ## Supported System Time Zones diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md index b83ed0e104931c657ff9117719f28bea0d50856a..fb1f95ce2d8c5003377120d9d28f29f4415d3117 100644 --- a/en/application-dev/reference/apis/js-apis-system-timer.md +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -1,4 +1,4 @@ -# System Timer +# @ohos.systemTimer The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services. @@ -33,13 +33,13 @@ Defines the initialization options for **createTimer**. **System capability**: SystemCapability.MiscServices.Time -| Name | Type | Mandatory| Description | -| --------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| type | number | Yes | Timer type.
**1**: CPU time type. The start time of the timer cannot be later than the current system time.
**2**: wakeup type.
**4**: exact type.
**5**: idle type (not supported currently).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| -| wantAgent | [WantAgent](js-apis-wantAgent.md) | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)| -| callback | number | Yes | Callback used to return the timer ID. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | number | Yes | Timer type.
**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)
**2**: wakeup type.
**4**: exact type.
**8**: idle type (not supported currently).| +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)| +| callback | number | Yes | Callback used to return the timer ID. | ## systemTimer.createTimer @@ -48,6 +48,8 @@ createTimer(options: TimerOptions, callback: AsyncCallback<number>): void Creates a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -66,13 +68,17 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat: false }; - systemTimer.createTimer(options, (error, data) => { - if (error) { - console.error(`Failed to create timer. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in creating timer. Data:` + JSON.stringify(data)); - }); + try { + systemTimer.createTimer(options, (error) => { + if (error) { + console.info(`Failed to create timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in creating timer.`); + }); + } catch(e) { + console.info(`Failed to create timer. message:${e.message}, code:${e.code}`); + } } } ``` @@ -83,6 +89,8 @@ createTimer(options: TimerOptions): Promise<number> Creates a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -105,12 +113,16 @@ export default { let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false - }; - systemTimer.createTimer(options).then((data) => { - console.log(`Succeeded in creating timer. Data:` + JSON.stringify(data)); - }).catch((error) => { - console.error(`Failed to create timer. Cause:` + JSON.stringify(error)); - }); + }; + try { + systemTimer.createTimer(options).then(() => { + console.info(`Succeeded in creating timer.`); + }).catch((error) => { + console.info(`Failed to create timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to create timer. message:${e.message}, code:${e.code}`); + } } } ``` @@ -121,6 +133,8 @@ startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void&g Starts a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -143,12 +157,17 @@ export default { let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime, (error) => { - if (error) { - console.error(`Failed to start timer. Cause:` + JSON.stringify(error)); - return; - } - }); + try { + systemTimer.startTimer(timerId, triggerTime, (error) => { + if (error) { + console.info(`Failed to start timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in starting timer.`); + }); + } catch(e) { + console.info(`Failed to start timer. message:${e.message}, code:${e.code}`); + } } } ``` @@ -159,6 +178,8 @@ startTimer(timer: number, triggerTime: number): Promise<void> Starts a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -186,11 +207,15 @@ export default { let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime).then((data) => { - console.log(`Succeeded in startting timer. Data:` + JSON.stringify(data)); - }).catch((error) => { - console.error(`Failed to start timer. Cause:` + JSON.stringify(error)); - }); + try { + systemTimer.startTimer(timerId, triggerTime).then(() => { + console.info(`Succeeded in starting timer.`); + }).catch((error) => { + console.info(`Failed to start timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to start timer. message:${e.message}, code:${e.code}`); + } } } ``` @@ -201,6 +226,8 @@ stopTimer(timer: number, callback: AsyncCallback<void>): void Stops a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -214,22 +241,27 @@ Stops a timer. This API uses an asynchronous callback to return the result. ```js export default { - async systemTimer () { - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime) - systemTimer.stopTimer(timerId, (error) => { - if (error) { - console.error(`Failed to stop timer. Cause:` + JSON.stringify(error)); - return; - } - }); - } + async systemTimer () { + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) + try { + systemTimer.stopTimer(timerId, (error) => { + if (error) { + console.info(`Failed to stop timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in stopping timer.`); + }); + } catch(e) { + console.info(`Failed to stop timer. message:${e.message}, code:${e.code}`); + } + } } ``` @@ -239,6 +271,8 @@ stopTimer(timer: number): Promise<void> Stops a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -257,21 +291,25 @@ Stops a timer. This API uses a promise to return the result. ```js export default { - async systemTimer (){ - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime) - systemTimer.stopTimer(timerId).then((data) => { - console.log(`Succeeded in stopping timer. Data:` + JSON.stringify(data)); - }).catch((error) => { - console.error(`Failed to stop timer. Cause:` + JSON.stringify(error)); - }); - } + async systemTimer (){ + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) + try { + systemTimer.stopTimer(timerId).then(() => { + console.info(`Succeeded in stopping timer.`); + }).catch((error) => { + console.info(`Failed to stop timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to stop timer. message:${e.message}, code:${e.code}`); + } + } } ``` @@ -281,6 +319,8 @@ destroyTimer(timer: number, callback: AsyncCallback<void>): void Destroys a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -304,12 +344,17 @@ export default { triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) - systemTimer.destroyTimer(timerId, (error) => { - if (error) { - console.error(`Failed to destroy timer. Cause:` + JSON.stringify(error)); - return; - } - }); + try { + systemTimer.destroyTimer(timerId, (error) => { + if (error) { + console.info(`Failed to destroy timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in destroying timer.`); + }); + } catch(e) { + console.info(`Failed to destroying timer. message:${e.message}, code:${e.code}`); + } } } ``` @@ -320,6 +365,8 @@ destroyTimer(timer: number): Promise<void> Destroys a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -348,11 +395,15 @@ export default { triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) - systemTimer.destroyTimer(timerId).then((data) => { - console.log(`Succeeded in destroying timer. Data:` + JSON.stringify(data)); - }).catch((error) => { - console.error(`Failed to destroy timer. Cause:` + JSON.stringify(error)); - }); + try { + systemTimer.destroyTimer(timerId).then(() => { + console.info(`Succeeded in destroying timer.`); + }).catch((error) => { + console.info(`Failed to destroy timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to destroying timer. message:${e.message}, code:${e.code}`); + } } } ``` diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index e9b54c774d2bc1e43de0dd7edb55e47bcf9c3b57..f1c9ad362175bd709d27bc4c7aec0059b413221e 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -1,6 +1,6 @@ -# Cellular Data +# @ohos.telephony.data (Cellular Data) -The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. +The **data** module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index e0d809d06ab24702e5eaf67eb6b1b841a7944ffc..514e7062cd649d8bf5b92261bceeb7cbed870166 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -1,8 +1,8 @@ -# Thermal Manager +# @ohos.thermal (Thermal Management) -This module provides thermal level-related callback and query APIs to obtain the information required for thermal control. +The **thermal** module provides thermal level-related callback and query APIs to obtain the information required for thermal control. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md index 0b52b8721ba891eacb099b86907458d72064dd9a..ae49b428e00c4c22ed126ecc539290a692b69696 100644 --- a/en/application-dev/reference/apis/js-apis-touchevent.md +++ b/en/application-dev/reference/apis/js-apis-touchevent.md @@ -1,6 +1,6 @@ -# Touch Event +# @ohos.multimodalInput.touchEvent (Touch Event) -Represents touch events reported by an input device. +The **touchEvent** module provides touch events reported by an input device. > **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 2a6fa561c6e21b85bfb07ee7b82223c42deff765..ffb07ba4f21cc5f154bcf25062f86845c97577dc 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -1,6 +1,6 @@ -# Update +# @ohos.update (Update) -The Update module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. +The **update** module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. There are two types of updates: SD card update and over the air (OTA) update. @@ -8,10 +8,8 @@ There are two types of updates: SD card update and over the air (OTA) update. - The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer. > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs provided by this module are system APIs. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md index b3be9875df2554c6df5b8c358c9243d734d87874..68a127a08bdfd1df0ca558866dc3cde577e2b25a 100644 --- a/en/application-dev/reference/apis/js-apis-usb-deprecated.md +++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -1,8 +1,8 @@ -# USB +# @ohos.usb (USB Management) -The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. +The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. -> **NOTE** +> **NOTE** > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 3e1c5b919c881ef5c0d0619a5b35e791c48c46cb..9035d2d040209f44a019fb69b3da6edc49b481b3 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,9 +1,8 @@ -# USB +# @ohos.usbV9 (USB Management) -The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. +The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -87,7 +86,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); connectDevice(device: USBDevice): Readonly<USBDevicePipe> -Connects to a USB device. +Connects to a USB device based on the device list obtained by using **getDevices()**. Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission. @@ -134,6 +133,8 @@ hasRight(deviceName: string): boolean Checks whether the application has the permission to access the device. +The value **true** is returned if the device access permission is available; the value **false** is returned otherwise. + **System capability**: SystemCapability.USB.USBManager **Parameters** @@ -187,7 +188,7 @@ usb.requestRight(devicesName).then((ret) => { ## usb.removeRight -removeRight(deviceName: string): boolean; +removeRight(deviceName: string): boolean Removes the permission for the application to access a USB device. @@ -216,7 +217,7 @@ if (usb.removeRight(devicesName) { ## usb.addRight -addRight(bundleName: string, deviceName: string): boolean; +addRight(bundleName: string, deviceName: string): boolean Adds the permission for the application to access a USB device. diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md index 9a45d1fe8f9644f0072fdfdb44c31f66c19e3d59..81fac3a36bb2dd34577e10596236cf8135a5fde1 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -1,4 +1,4 @@ -# Facial Authentication +# @ohos.userIAM.faceAuth (Facial Authentication) The **userIAM.faceAuth** module provides APIs for face enrollment. diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index ce73ba0bcd0ed53bb75bcb873cf35dd8f6910f6d..64e92b13dadd306eab3ee030611a5e2d6ce0bd40 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -1,4 +1,4 @@ -# User Authentication +# @ohos.userIAM.userAuth (User Authentication) The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login. diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 8897b51f07b4e00feae752e792820e6b9b32370f..09e3c245326f4bc9008e20535edfa4f0a2c3d2d0 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -1,6 +1,6 @@ -# @ohos.util +# @ohos.util (Utilities) -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. +The **util** module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 252dc45b802251e8cf0eb7493ce51ef917a5fa99..b0bad9b58fd5a74501fe45c9e2995a26236a8f30 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,6 +1,6 @@ # @ohos.wantAgent -The **WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. +The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. > **NOTE** > @@ -8,7 +8,7 @@ The **WantAgent** module provides APIs for triggering, canceling, and comparing ## Modules to Import -```js +```ts import WantAgent from '@ohos.wantAgent'; ``` @@ -24,37 +24,41 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ----------------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + if (err.code) { + console.info('getWantAgent Callback err:' + JSON.stringify(err)) + } else { + console.info('getWantAgent Callback success') + } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -64,11 +68,9 @@ var wantAgentInfo = { wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); ``` - - ## WantAgent.getWantAgent getWantAgent(info: WantAgentInfo): Promise\ @@ -81,7 +83,7 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ------------- | ---- | ------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain.| **Return value** @@ -91,29 +93,29 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -124,12 +126,10 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); }); ``` - - ## WantAgent.getBundleName getBundleName(agent: WantAgent, callback: AsyncCallback\): void @@ -147,16 +147,16 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -164,24 +164,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -195,9 +195,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // getBundleName callback function getBundleNameCallback(err, data) { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); } -WantAgent.getBundleName(wantAgent, getBundleNameCallback) +WantAgent.getBundleName(wantAgent, getBundleNameCallback); ``` @@ -218,38 +218,37 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ----------------- | ------------------------------------------------ | | Promise\ | Promise used to return the bundle name.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -260,12 +259,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getBundleName(wantAgent).then((data) => { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); }); ``` @@ -288,16 +287,16 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -305,24 +304,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -336,9 +335,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // getUid callback function getUidCallback(err, data) { - console.info("==========================>getUidCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); } -WantAgent.getUid(wantAgent, getUidCallback) +WantAgent.getUid(wantAgent, getUidCallback); ``` @@ -365,32 +364,32 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -401,162 +400,16 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getUid(wantAgent).then((data) => { - console.info("==========================>getUidCallback=======================>"); -}); -``` - - - -## WantAgent.getWant - -getWant(agent: WantAgent, callback: AsyncCallback\): void - -Obtains the want in a **WantAgent** object. This API uses an asynchronous callback to return the result. - -**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 | -| -------- | --------------------- | ---- | ------------------------------- | -| agent | WantAgent | Yes | Target **WantAgent** object. | -| callback | AsyncCallback\ | Yes | Callback used to return the want.| - -**Example** - -```js -import WantAgent from '@ohos.wantAgent'; - - -// WantAgent object -var wantAgent; - -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// getWant callback -function getWantCallback(err, data) { - console.info("==========================>getWantCallback=======================>"); -} -WantAgent.getWant(wantAgent, getWantCallback) -``` - - - -## WantAgent.getWant - -getWant(agent: WantAgent): Promise\ - -Obtains the want in a **WantAgent** object. This API uses a promise to return the result. - -**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 | -| ----- | --------- | ---- | ------------- | -| agent | WantAgent | Yes | Target **WantAgent** object.| - -**Return value** - -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the want.| - -**Example** - -```js -import WantAgent from '@ohos.wantAgent'; - - -// WantAgent object -var wantAgent; - -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); - -WantAgent.getWant(wantAgent).then((data) => { - console.info("==========================>getWantCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); }); ``` - ## WantAgent.cancel cancel(agent: WantAgent, callback: AsyncCallback\): void @@ -574,16 +427,16 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -591,24 +444,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -622,9 +475,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // cancel callback function cancelCallback(err, data) { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); } -WantAgent.cancel(wantAgent, cancelCallback) +WantAgent.cancel(wantAgent, cancelCallback); ``` @@ -651,32 +504,32 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -687,12 +540,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.cancel(wantAgent).then((data) => { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); }); ``` @@ -711,21 +564,21 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ----------- | ----------------------------- | ---- | ------------------------------- | | agent | WantAgent | Yes | Target **WantAgent** object. | -| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. | +| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. | | callback | AsyncCallback\ | No | Callback used to return the result.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -733,24 +586,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -764,7 +617,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // trigger callback function triggerCallback(data) { - console.info("==========================>triggerCallback=======================>"); + console.info('==========================>triggerCallback=======================>'); } var triggerInfo = { @@ -779,7 +632,7 @@ WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void -Checks whether two **WantAgent** objects are equal. This API uses an asynchronous callback to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -793,17 +646,17 @@ Checks whether two **WantAgent** objects are equal. This API uses an asynchronou **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent1 = data; wantAgent2 = data; @@ -812,24 +665,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -843,7 +696,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // equal callback function equalCallback(err, data) { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); } WantAgent.equal(wantAgent1, wantAgent2, equalCallback) ``` @@ -854,7 +707,7 @@ WantAgent.equal(wantAgent1, wantAgent2, equalCallback) equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -Checks whether two **WantAgent** objects are equal. This API uses a promise to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -873,33 +726,33 @@ Checks whether two **WantAgent** objects are equal. This API uses a promise to r **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -910,13 +763,13 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; }); WantAgent.equal(wantAgent1, wantAgent2).then((data) => { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); }); ``` @@ -937,31 +790,31 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -972,7 +825,7 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); @@ -1003,31 +856,31 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1038,15 +891,14 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; + WantAgent.getOperationType(wantAgent).then((OperationType) => { + console.log('getOperationType success, OperationType: ' + OperationType); + }).catch((err) => { + console.log('getOperationType fail, err: ' + err); + }) }); - -WantAgent.getOperationType(wantAgent).then((OperationType) => { - console.log('getOperationType success, OperationType: ' + OperationType); -}).catch((err) => { - console.log('getOperationType fail, err: ' + err); -}) ``` diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index bda4ad227b32b18130682bb4fe10db9a446535ec..2b2fa3af70da2fd1725ef0221b8fd7cf5654f531 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -1,7 +1,9 @@ -# WebSocket Connection +# @ohos.net.webSocket (WebSocket Connection) ->![](public_sys-resources/icon-note.gif) **NOTE:** ->The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **webSocket** module implements WebSocket connection management and operation. + +> **NOTE**
+> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index 92f40c92f26257e614135694d49d69608ea32a23..83d89392cd8ade90901018fbe5721ce53ba54f2e 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -1,6 +1,6 @@ -# @ohos.web.webview (Webview) +# @ohos.web.webview The **Webview** module provides APIs for web control. @@ -19,6 +19,46 @@ The **Webview** module provides APIs for web control. ```ts import web_webview from '@ohos.web.webview'; ``` + +### once + +once(type: string, callback: Callback\): void + +Registers a one-time callback for web events of the specified type. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | -------------------- | +| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | +| headers | Callback\ | Yes | Callback to register.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +web_webview.once("webInited", () => { + console.log("setCookie") + web_webview.WebCookieManager.setCookie("www.example.com", "a=b") +}) + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebMessagePort Implements a **WebMessagePort** object to send and receive messages. @@ -61,7 +101,7 @@ struct WebComponent { ### postMessageEvent -postMessageEvent(message: string): void +postMessageEvent(message: WebMessage): void Sends a message. For the complete sample code, see [postMessage](#postmessage). @@ -71,7 +111,7 @@ Sends a message. For the complete sample code, see [postMessage](#postmessage). | Name | Type | Mandatory| Description | | ------- | ------ | ---- | :------------- | -| message | string | Yes | Message to send.| +| message | [WebMessage](#webmessage) | Yes | Message to send.| **Error codes** @@ -113,7 +153,7 @@ struct WebComponent { ### onMessageEvent -onMessageEvent(callback: (result: string) => void): void +onMessageEvent(callback: (result: WebMessage) => void): void Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). @@ -123,7 +163,7 @@ Registers a callback to receive messages from the HTML5 side. For the complete s | Name | Type | Mandatory| Description | | -------- | -------- | ---- | :------------------- | -| result | string | Yes | Message received.| +| result | [WebMessage](#webmessage) | Yes | Message received.| **Error codes** @@ -152,7 +192,17 @@ struct WebComponent { try { this.ports = this.controller.createWebMessagePorts(); this.ports[1].onMessageEvent((msg) => { - console.log("received message from html5, on message:" + msg); + if (typeof(msg) == "string") { + console.log("received string message from html5, string is:" + msg); + } else if (typeof(msg) == "object") { + if (msg instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + msg.byteLength); + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } }) } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); @@ -166,13 +216,40 @@ struct WebComponent { ## WebviewController -Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs in the **WebviewController** can be invoked only after it has been bound to the target **\** component. +Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\** component. + +### initializeWebEngine + +static initializeWebEngine(): void + +Loads the dynamic link library (DLL) file of the web engine. This API can be called before the **\** component is initialized to improve the startup performance. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +The following code snippet exemplifies calling this API after the EntryAbility is created. + +```ts +// xxx.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import web_webview from '@ohos.web.webview'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("EntryAbility onCreate") + web_webview.WebviewController.initializeWebEngine() + globalThis.abilityWant = want + console.log("EntryAbility onCreate done") + } +} +``` ### Creating an Object ```ts // xxx.ets -import web_webview from '@ohos.web.webview' +import web_webview from '@ohos.web.webview'; @Entry @Component @@ -1397,8 +1474,21 @@ struct WebComponent { // 2. Send one of the message ports to the HTML side, which can then save and use the port. this.controller.postMessage('__init_port__', [this.ports[0]], '*'); // 3. Register a callback for the other message port on the application side. - this.ports[1].onMessageEvent((result: string) => { - var msg = 'Got msg from HTML: ' + result; + this.ports[1].onMessageEvent((result: WebMessage) => { + var msg = 'Got msg from HTML:'; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } this.receivedFromHtml = msg; }) } catch (error) { @@ -1456,7 +1546,21 @@ window.addEventListener('message', function (event) { The h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. h5Port.onmessage = function (event) { // 2. Receive the message sent from the eTS side. - var msg = 'Got message from ets:' + event.data; + var msg = 'Got message from ets:'; + var result = event.data; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } output.innerHTML = msg; } } @@ -1759,7 +1863,7 @@ struct WebComponent { getTitle(): string -Obtains the title of the file selector. +Obtains the title of the current web page. **System capability**: SystemCapability.Web.Webview.Core @@ -1767,7 +1871,7 @@ Obtains the title of the file selector. | Type | Description | | ------ | -------------------- | -| string | Title of the file selector.| +| string | Title of the current web page.| **Error codes** @@ -2123,6 +2227,222 @@ struct WebComponent { } ``` +### scrollTo + +scrollTo(x:number, y:number): void + +Scrolls the page to the specified absolute position. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| +| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollTo') + .onClick(() => { + try { + this.controller.scrollTo(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### scrollBy + +scrollBy(deltaX:number, deltaY:number): void + +Scrolls the page by the specified amount. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| +| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollBy') + .onClick(() => { + try { + this.controller.scrollBy(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### slideScroll + +slideScroll(vx:number, vy:number): void + +Simulates a slide-to-scroll action on the page at the specified velocity. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| +| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('slideScroll') + .onClick(() => { + try { + this.controller.slideScroll(500, 500); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + ### getOriginalUrl getOriginalUrl(): string @@ -2244,7 +2564,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 401 | Invalid input parameter. | **Example** @@ -2275,7 +2594,7 @@ struct WebComponent { ### hasImage -hasImage(callback: AsyncCallback): void +hasImage(callback: AsyncCallback\): void Checks whether this page contains images. This API uses an asynchronous callback to return the result. @@ -2294,7 +2613,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 401 | Invalid input parameter. | **Example** @@ -2312,7 +2630,7 @@ struct WebComponent { Button('hasImageCb') .onClick(() => { try { - this.controller.hasImage((err, data) => { + this.controller.hasImage((error, data) => { if (error) { console.info(`hasImage error: ` + JSON.stringify(error)) return; @@ -2331,7 +2649,7 @@ struct WebComponent { ### hasImage -hasImage(): Promise +hasImage(): Promise\ Checks whether this page contains images. This API uses a promise to return the result. @@ -2350,7 +2668,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 401 | Invalid input parameter. | **Example** @@ -2396,7 +2713,7 @@ Clears the cache in the application. This API will clear the cache for all webvi | Name | Type | Mandatory| Description | | -------- | ------- | ---- | -------------------------------------------------------- | -| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **false** means to only clear the cache in the RAM.| +| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **true** means to clear the cache in the ROM and RAM at the same time, and **false** means to only clear the cache in the RAM.| **Error codes** @@ -2405,7 +2722,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 401 | Invalid input parameter. | **Example** @@ -2483,9 +2799,58 @@ struct WebComponent { } ``` +### customizeSchemes + +static customizeSchemes(schemes: Array\): void + +Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\** component is initialized. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | -------------------------------------- | +| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + responseweb: WebResourceResponse = new WebResourceResponse() + scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true} + scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true} + scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true} + + aboutToAppear():void { + try { + web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]) + } catch(error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + } + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onInterceptRequest((event) => { + console.log('url:' + event.request.getRequestUrl()) + return this.responseweb + }) + } + } +} +``` + ## WebCookieManager -Implements a **WebCookie** object to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookie** object. +Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. ### getCookie @@ -3600,7 +3965,7 @@ Implements a **WebAsyncController** object, which can be used to control the beh @Component struct WebComponent { controller: WebController = new WebController(); - webAsyncController: WebAsyncController = new web_webview.WebAsyncController(this.controller) + webAsyncController: web_webview.WebAsyncController = new web_webview.WebAsyncController(this.controller) build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -3635,8 +4000,8 @@ Stores this web page. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | | callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise.| **Example** @@ -3677,14 +4042,14 @@ Stores this web page. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise | Promise used to return the save path if the operation is successful and null otherwise.| +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the save path if the operation is successful and null otherwise. | **Example** @@ -4100,6 +4465,15 @@ Provides the element information of the area being clicked. For details about th | type | [HitTestTypeV9](#hittesttypev9) | Yes| No| Element type of the area being clicked.| | extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.| +## WebMessage + +Describes the data types supported for [WebMessagePort](#webmessageport). + +| Type | Description | +| -------- | -------------------------------------- | +| string | String type.| +| ArrayBuffer | Binary type.| + ## WebStorageOrigin Provides usage information of the Web SQL Database. @@ -4143,14 +4517,6 @@ Obtains the page record with the specified index in the history stack. | --------------------------- | ------------ | | [HistoryItem](#historyitem) | Historical page record.| -**Error codes** - -For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). - -| ID| Error Message | -| -------- | ----------------------- | -| 401 | Invalid input parameter | - **Example** ```ts @@ -4172,7 +4538,7 @@ struct WebComponent { let list = this.controller.getBackForwardEntries(); let historyItem = list.getItemAtIndex(list.currentIndex); console.log("HistoryItem: " + JSON.stringify(historyItem)); - this.icon = item.icon; + this.icon = historyItem.icon; } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -4196,4 +4562,14 @@ Describes a historical page record. | historyRawUrl | string | Yes | No | Original URL of the historical page. | | title | string | Yes | No | Title of the historical page. | -### +## WebCustomScheme + +Defines a custom URL scheme. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| -------------- | --------- | ---- | ---- | ---------------------------- | +| schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters and include only lowercase letters, digits, periods (.), plus signs (+), and hyphens (-). | +| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | +| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | diff --git a/en/application-dev/reference/arkui-js/figures/en-us-attributes.gif b/en/application-dev/reference/arkui-js/figures/en-us-attributes.gif new file mode 100644 index 0000000000000000000000000000000000000000..77a11bb928c4b0d6e66073dd844320fc4e10229c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us-attributes.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image1.png b/en/application-dev/reference/arkui-js/figures/en-us_image1.png new file mode 100644 index 0000000000000000000000000000000000000000..971b33355ee838054f24e2a7005c3ef3906a24d1 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image1.png differ diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md index 125067139d62be03f2a19995e9181df6010a1f77..f580a31338e6e8d145d963c1b2f7662f1113e06c 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md @@ -17,7 +17,7 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse | Name | Type | Description | | ------ | ------ | ------------------------------------------------------------ | | offset | number | Proportion of the distance between the color stop and the start point to the total length. The value ranges from 0 to 1. | -| color | string | Gradient color to set. | +| color | string | Gradient color to set. | **Example** @@ -35,9 +35,9 @@ export default { const el =this.$refs.canvas; const ctx = el.getContext('2d'); const gradient = ctx.createLinearGradient(50,0,300,100); - gradient.addColorStop(0.0, 'red') - gradient.addColorStop(0.5, 'white') - gradient.addColorStop(1.0, 'green') + gradient.addColorStop(0.0, '#ff0000') + gradient.addColorStop(0.5, '#ffffff') + gradient.addColorStop(1.0, '#00ff00') ctx.fillStyle = gradient ctx.fillRect(0, 0, 300, 300) } diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index 0ebefab7d190de7f8ca8bd76b570444c0a2aa70b..8df65d142a4129699c45f44b69c1c5f1fbe96829 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -1682,9 +1682,9 @@ Creates a linear gradient and returns a **CanvasGradient** object. For details, // Linear gradient: start(50,0) end(300,100) var gradient = ctx.createLinearGradient(50,0, 300,100); // Add three color stops - gradient.addColorStop(0.0, 'red'); - gradient.addColorStop(0.5, 'white'); - gradient.addColorStop(1.0, 'green'); + gradient.addColorStop(0.0, '#ff0000'); + gradient.addColorStop(0.5, '#ffffff'); + gradient.addColorStop(1.0, '#00ff00'); // Set the fill style and draw a rectangle ctx.fillStyle = gradient; ctx.fillRect(0, 0, 500, 500); diff --git a/en/application-dev/reference/arkui-js/js-components-common-attributes.md b/en/application-dev/reference/arkui-js/js-components-common-attributes.md index 357385f9747d820873c0c7aebb9ac8a8c2647960..416087236c246f61e692f8b4207d7d9161b31c9f 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-attributes.md +++ b/en/application-dev/reference/arkui-js/js-components-common-attributes.md @@ -31,5 +31,114 @@ Rendering attributes are used to set whether a component is rendered. | if | boolean | - | Whether the element is added or removed.| | show | boolean | - | Whether the element is displayed or hidden.| -> **NOTE**
+> **NOTE** +> > Do not set styles in attribute fields. + +## Example + +### Example 1 + +```html + +
+ + + + {{ $item.value }} + + +
+``` + +```css +/* xxx.css */ +#container { + flex-direction: column; + width: 100%; + margin-top: 10px; +} +.text { + font-size: 50px; + font-weight: 500; + margin-left: 12px; +} +.listItem { + width: 100%; + height: 100px; + line-height: 60px; + border-bottom: 1px solid #DEDEDE; + font-size: 20px; +} +.btn{ + width: 280px; + font-size: 26px; + margin: 10px 0; +} +``` + +```js +// xxx.js +export default { + data: { + visible: true, + display: true, + title: "", + i: 4, + array: [ + {"value": "Item 0"}, + {"value": "Item 1"}, + {"value": "Item 2"}, + {"value": "Item 3"}, + ], + }, + toggleShow: function() { + this.array.push ({"value": "Item" + this.i }) + this.i++ + }, + toggleDisplay: function() { + this.display = !this.display + }, +} +``` + +![en-us-attributes](figures/en-us-attributes.gif) + +### Example 2 + +```html + +
+
+ hello world +
+
+ hello world +
+
+``` + +```css +/* xxx.css */ +.container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 100%; +} +.text1{ + width: 90%; + height: 100px; + background-color: aqua; +} +.text2{ + width: 90%; + height: 100px; + background-color: blue; +} +``` + +![en-us_image1](figures/en-us_image1.png) diff --git a/en/application-dev/reference/arkui-js/js-components-common-styles.md b/en/application-dev/reference/arkui-js/js-components-common-styles.md index b32dbc08734817999f0968ebb47bfd41cea2e693..611529aec1de7dc133ff4fab8c784622cb60591a 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-styles.md +++ b/en/application-dev/reference/arkui-js/js-components-common-styles.md @@ -42,7 +42,7 @@ You can set universal styles for components in the **style** attribute or **.css | backdrop-filter5+ | string | - | Syntax: backdrop-filter: blur(px)
Radius of the background blur area within the component layout. If this style is not set, the default value **0** (no blur) is used. Percentage values are not supported.
Example:
- backdrop-filter: blur(10px) | | window-filter5+ | string | - | Syntax: window-filter: blur(percent), style5+
Blur degree and style for windows within the component layout. If this style is not set, the default value **0%** (no blur area) is used. Different blur degrees and styles for multiple blur areas are not supported. Available values of **style** are as follows: small_light (default value), medium_light, large_light, xlarge_light, small_dark, medium_dark, large_dark, xlarge_dark
Example:
- window-filter: blur(50%)
- window-filter: blur(10%), large_light | | opacity | number | 1 | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. | -| display | string | flex | Type of the box containing an element. Available values are as follows:
- **flex**: flexible layout
- **none**: not rendered
- **grid**: grid layout (available only **div** supports the **display** style)| +| display | string | flex | Type of the box containing an element. Available values are as follows:
- **flex**: flexible layout
- **none**: not rendered
- **grid**: grid layout (available only for the **\
** component) | | visibility | string | visible | Whether to display the box containing an element. The invisible box occupies layout space. (To remove the box, set the **display** attribute to **none**.) Available values are as follows:
- **visible**: The element is visible.
- **hidden**: The box is hidden but still takes up space.
If both **visibility** and **display** are set, only **display** takes effect.| | flex | number \| string | - | How to divide available space of the parent component for each child component.
You can set one, two5+, or three5+ values for this style.
Set one value in either of the following ways:
- A unitless number to set **flex-grow**.
- A valid width value5+ to set **flex-basis**.
Set two values5+ in the following ways:
The first value must be a unitless number used to set **flex-grow**. The second value must be either of the following:
- A unitless number to set **flex-shrink**.
- A valid width value to set **flex-basis**.
Set three values5+ in the following ways:
The first value must be a unitless number used to set **flex-grow**. The second value must be a unitless number used to set **flex-shrink**. The third value must be a valid width value used to set **flex-basis**.
This style takes effect only when the container is any of the following components: **\
**, **\**, **\**, **\**, and **\5+**.| | flex-grow | number | 0 | How much a child component will grow. The value specifies allocation of the remaining space on the main axis of the parent component. Size of available space = Container size - Total size of all child components. Value **0** indicates that the child component does not grow.
This style takes effect only when the container is any of the following components: **\
**, **\**, **\**, **\**, and **\5+**.| diff --git a/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md index c97b123b4bc071d0209bbf6c3e8aad9984f7e914..8eebde2cacb7dc2e2409a8c1f6a8274ac4e38390 100644 --- a/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md @@ -14,7 +14,7 @@ In addition to the attributes that are supported by **CanvasRenderingContext2D** | Name | Type | Description | | ------ | ------ | ---------------------------------------- | -| filter | string | Image filter.
Available options are as follows:
- **blur**: applies the Gaussian blur for the image.
- **brightness**: applies a linear multiplication to the image to make it look brighter or darker.
- **contrast**: adjusts the image contrast.
- **drop-shadow**: sets a shadow effect for the image.
- **grayscale**: converts the image to a grayscale image.
- **hue-rotate**: applies hue rotation to the image.
- **invert**: inverts the input image.
- **opacity**: sets the opacity of the image.
- **saturate**: sets the saturation of the image.
- **sepia**: converts the image to dark brown. | +| filter | string | Image filter.
Available options are as follows:
- **blur**: applies the Gaussian blur for the image.
- **brightness**: applies a linear multiplication to the image to make it look brighter or darker.
- **contrast**: adjusts the image contrast.
- **drop-shadow**: sets a shadow effect for the image.
- **grayscale**: converts the image to a grayscale image.
- **hue-rotate**: applies hue rotation to the image.
- **invert**: inverts the image.
- **opacity**: sets the image opacity.
- **saturate**: sets the image saturation.
- **sepia**: converts the image to sepia.| **Example** ```html @@ -199,13 +199,13 @@ export default { var offscreenCanvasCtx = offscreen.getContext("2d"); offscreenCanvasCtx.transform(1, 0, 1.7, 1, 0, 0); - offscreenCanvasCtx.fillStyle = 'gray'; + offscreenCanvasCtx.fillStyle = '#a9a9a9'; offscreenCanvasCtx.fillRect(40, 40, 50, 20); offscreenCanvasCtx.fillRect(40, 90, 50, 20); // Non-skewed rectangles offscreenCanvasCtx.resetTransform(); - offscreenCanvasCtx.fillStyle = 'red'; + offscreenCanvasCtx.fillStyle = '#ff0000'; offscreenCanvasCtx.fillRect(40, 40, 50, 20); offscreenCanvasCtx.fillRect(40, 90, 50, 20); diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 7061cde570c5bf521e9eddc4ef232af1e3a8050b..25736a22dced9dd795af1edd130de06ab02248cf 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -102,7 +102,6 @@ - [Counter](ts-container-counter.md) - [Flex](ts-container-flex.md) - [FlowItem](ts-container-flowitem.md) - - [GridContainer](ts-container-gridcontainer.md) - [GridCol](ts-container-gridcol.md) - [GridRow](ts-container-gridrow.md) - [Grid](ts-container-grid.md) @@ -124,25 +123,25 @@ - [TabContent](ts-container-tabcontent.md) - [WaterFlow](ts-container-waterflow.md) - Media Components - - [Video](ts-media-components-video.md) + - [Video](ts-media-components-video.md) - Drawing Components - - [Circle](ts-drawing-components-circle.md) - - [Ellipse](ts-drawing-components-ellipse.md) - - [Line](ts-drawing-components-line.md) - - [Polyline](ts-drawing-components-polyline.md) - - [Polygon](ts-drawing-components-polygon.md) - - [Path](ts-drawing-components-path.md) - - [Rect](ts-drawing-components-rect.md) - - [Shape](ts-drawing-components-shape.md) + - [Circle](ts-drawing-components-circle.md) + - [Ellipse](ts-drawing-components-ellipse.md) + - [Line](ts-drawing-components-line.md) + - [Polyline](ts-drawing-components-polyline.md) + - [Polygon](ts-drawing-components-polygon.md) + - [Path](ts-drawing-components-path.md) + - [Rect](ts-drawing-components-rect.md) + - [Shape](ts-drawing-components-shape.md) - Canvas Components - - [Canvas](ts-components-canvas-canvas.md) - - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) - - [CanvasGradient](ts-components-canvas-canvasgradient.md) - - [ImageBitmap](ts-components-canvas-imagebitmap.md) - - [ImageData](ts-components-canvas-imagedata.md) - - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) - - [Path2D](ts-components-canvas-path2d.md) - - [Lottie](ts-components-canvas-lottie.md) + - [Canvas](ts-components-canvas-canvas.md) + - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) + - [CanvasGradient](ts-components-canvas-canvasgradient.md) + - [ImageBitmap](ts-components-canvas-imagebitmap.md) + - [ImageData](ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) + - [Path2D](ts-components-canvas-path2d.md) + - [Lottie](ts-components-canvas-lottie.md) - Animation - [AnimatorProperty](ts-animatorproperty.md) - [Explicit Animatio](ts-explicit-animation.md) diff --git a/en/application-dev/reference/arkui-ts/figures/alphabet.gif b/en/application-dev/reference/arkui-ts/figures/alphabet.gif new file mode 100644 index 0000000000000000000000000000000000000000..5a5a3e4bab1f7f104afd27199125972c6cb611c0 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/alphabet.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif index cc49b51652e53b6caa3888b054dbea94c2f498eb..35b1bf68c0e0c323eb4c5171be6fbf368c6eb576 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001189634870.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001189634870.gif new file mode 100644 index 0000000000000000000000000000000000000000..cba972ca736015ad30288b21bb8069cb540414c2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001189634870.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378392.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378392.gif deleted file mode 100644 index 438c67b65f13bfcd1ee3eb19e4f0c1265ae16278..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378392.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058403.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058403.gif deleted file mode 100644 index c7532ed87726ac7591901514a7396b617daa10f0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058403.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/relativecontainer.png b/en/application-dev/reference/arkui-ts/figures/relativecontainer.png index 574fcaa48023d14a579eaa843ebc59f1b961a29f..eff44d4efadaeb8dc94da8d166333c5956878f27 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/relativecontainer.png and b/en/application-dev/reference/arkui-ts/figures/relativecontainer.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index 4bdc96f244d22a65d2689971492f84103f8f134e..eb5d3e065f671025dbdd28450b53f2fa955996c2 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 @@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| 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://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 files in the directory package path have the read permission. | +| 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://path** prefix are supported, which are used to access the image path provided by a data ability. Before loading images, the application must [request the required permissions](../../file-management/medialibrary-overview.md#requesting-permissions).
\- 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 files in the directory package path have the read permission.| ## Attributes @@ -38,7 +38,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported. | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.
Default value: **ImageFit.Cover** | | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.
Default value: **ImageRepeat.NoRepeat**
**NOTE**
This attribute is not applicable to SVG images.| -| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
**NOTE**
This attribute is not applicable to SVG images and **PixelMap** objects. | +| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
**NOTE**
This attribute is not applicable to SVG images.
This attribute is not applicable to **PixelMap** objects.| | renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.
Default value: **ImageRenderMode.Original**
**NOTE**
This attribute is not applicable to SVG images.| | sourceSize | {
width: number,
height: number
} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.
**NOTE**
This attribute is not applicable to **PixelMap** objects.| | matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false** | @@ -74,11 +74,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name | Description | +| Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status. | -| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels. | -| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered. | +| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status.
| +| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.| +| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.| ## Example @@ -161,7 +161,7 @@ The default network timeout period is 5 minutes for loading online images. When ```tsx // @ts-nocheck import http from '@ohos.net.http'; -import ResponseCode from '@ohos.net.http'; +import ResponseCode from '@ohos.net.http' import image from '@ohos.multimedia.image' @@ -176,7 +176,7 @@ struct Index { Column({space: 10}) { Button ("Get Online Image") .onClick(() => { - this.httpRequest(); + this.httpRequest() }) Image(this.image).height(100).width(100) } @@ -187,7 +187,7 @@ struct Index { // Request an online image. private httpRequest() { - let httpRequest = http.createHttp(); + let httpRequest = http.createHttp() httpRequest.request( "https://www.example.com/xxx.png", // Enter a specific URL of the online image. @@ -207,7 +207,7 @@ struct Index { this.image = pixelMap }) } else { - console.log("response code: " + code); + console.log("response code: " + code) } } } @@ -216,9 +216,9 @@ 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. +> **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 @@ -356,7 +356,7 @@ struct ImageExample3 { ```ts import fileio from '@ohos.fileio' -import fs from '@ohos.file.fs'; +import fs from '@ohos.file.fs' import context from '@ohos.application.context' @Entry diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md index eb276513bad3c1f1f1c911f15f14f5f3c74f7dba..25743606575892d60be19fa31fd0e60055d01fb9 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md @@ -27,7 +27,7 @@ ImageAnimator() | duration | number | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.
Default value: **1000**| | reverse | boolean | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.
Default value: **false**| | fixedSize | boolean | Whether the image size is the same as the component size.
**true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.
**false**: The width, height, top, and left attributes of each image must be set separately.
Default value: **true**| -| preDecode | number | Whether to enable pre-decoding. The default value **0** indicates that pre-decoding is disabled. The value **2** indicates that two images following the currently playing frame will be cached in advance to improve performance.
Default value: **0**| +| preDecode(deprecated) | number | Number of pre-decoded images. The value **2** indicates that two images following the currently playing page will be pre-decoded to improve performance.
This API is deprecated since API version 9.
Default value: **0**| | fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Status before and after the animation starts. For details about the options, see **FillMode**.
Default value: **FillMode.Forwards**| | iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1**| @@ -102,7 +102,7 @@ struct ImageAnimatorExample { left: 0 } ]) - .state(this.state).reverse(this.reverse).fixedSize(false).preDecode(2) + .state(this.state).reverse(this.reverse).fixedSize(false) .fillMode(FillMode.None).iterations(this.iterations).width(340).height(240) .margin({ top: 100 }) .onStart(() => { @@ -119,6 +119,7 @@ struct ImageAnimatorExample { }) .onFinish(() => { console.info('Finish') + this.state = AnimationStatus.Stopped }) Row() { Button('start').width(100).padding(5).onClick(() => { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index 0e9b480a1326760e25e56bca698bd8e8581bbb68..e2afb3e5eaa55dfb4d4509db3c87ba55821cd748 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -467,13 +467,13 @@ Sets whether to enable geolocation access. By default, this feature is enabled. mediaPlayGestureAccess(access: boolean) -Sets whether a manual click is required for video playback. +Sets whether video playback must be started by user gestures. This API is not applicable to videos that do not have an audio track or whose audio track is muted. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ------ | ------- | ---- | ---- | ----------------- | -| access | boolean | Yes | true | Whether a manual click is required for video playback.| +| access | boolean | Yes | true | Whether video playback must be started by user gestures.| **Example** @@ -522,6 +522,109 @@ Sets whether to enable the multi-window permission. } ``` +### horizontalScrollBarAccess9+ + +horizontalScrollBarAccess(horizontalScrollBar: boolean) + +Sets whether to display the horizontal scrollbar, including the system default scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ----------- | ------- | ---- | ----- | ------------ | +| horizontalScrollBar | boolean | Yes | true | Whether to display the horizontal scrollbar.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .horizontalScrollBarAccess(true) + } + } + } + ``` + + ```html + + + + + Demo + + + + Scroll Test + + + ``` + +### verticalScrollBarAccess9+ + +verticalScrollBarAccess(verticalScrollBar: boolean) + +Sets whether to display the vertical scrollbar, including the system default scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ----------- | ------- | ---- | ----- | ------------ | +| verticalScrollBarAccess | boolean | Yes | true | Whether to display the vertical scrollbar.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .verticalScrollBarAccess(true) + } + } + } + ``` + + ```html + + + + + Demo + + + + Scroll Test + + + ``` + + ### cacheMode cacheMode(cacheMode: CacheMode) @@ -707,13 +810,13 @@ Sets whether to block online downloads. defaultFixedFontSize(size: number) -Sets the default fixed font size of the web page. +Sets the default fixed font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ---------------------------- | -| size | number | Yes | 13 | Default fixed font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 13 | Default fixed font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -724,11 +827,11 @@ Sets the default fixed font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 16 + @State fontSize: number = 16 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .defaultFixedFontSize(this.size) + .defaultFixedFontSize(this.fontSize) } } } @@ -738,13 +841,13 @@ Sets the default fixed font size of the web page. defaultFontSize(size: number) -Sets the default font size of the web page. +Sets the default font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ------------------------ | -| size | number | Yes | 16 | Default font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 16 | Default font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -755,11 +858,11 @@ Sets the default font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 13 + @State fontSize: number = 13 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .defaultFontSize(this.size) + .defaultFontSize(this.fontSize) } } } @@ -769,13 +872,44 @@ Sets the default font size of the web page. minFontSize(size: number) -Sets the minimum font size of the web page. +Sets the minimum font size for the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ------------------------ | +| size | number | Yes | 8 | Minimum font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State fontSize: number = 13 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .minFontSize(this.fontSize) + } + } + } + ``` + +### minLogicalFontSize9+ + +minLogicalFontSize(size: number) + +Sets the minimum logical font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ------------------------ | -| size | number | Yes | 8 | Minimum font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 8 | Minimum logical font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -786,27 +920,28 @@ Sets the minimum font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 13 + @State fontSize: number = 13 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .minFontSize(this.size) + .minLogicalFontSize(this.fontSize) } } } ``` + ### webFixedFont9+ webFixedFont(family: string) -Sets the fixed font family of the web page. +Sets the fixed font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | --------- | ---------------------------- | -| family | string | Yes | monospace | Fixed font family of the web page.| +| family | string | Yes | monospace | Fixed font family to set.| **Example** @@ -831,13 +966,13 @@ Sets the fixed font family of the web page. webSansSerifFont(family: string) -Sets the sans serif font family of the web page. +Sets the sans serif font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ---------- | --------------------------------- | -| family | string | Yes | sans-serif | Sans serif font family of the web page.| +| family | string | Yes | sans-serif | Sans serif font family to set.| **Example** @@ -862,13 +997,13 @@ Sets the sans serif font family of the web page. webSerifFont(family: string) -Sets the serif font family of the web page. +Sets the serif font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ---------------------------- | -| family | string | Yes | serif | Serif font family of the web page.| +| family | string | Yes | serif | Serif font family to set.| **Example** @@ -893,13 +1028,13 @@ Sets the serif font family of the web page. webStandardFont(family: string) -Sets the standard font family of the web page. +Sets the standard font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ---------- | ------------------------------- | -| family | string | Yes | sans serif | Standard font family of the web page.| +| family | string | Yes | sans serif | Standard font family to set.| **Example** @@ -924,13 +1059,13 @@ Sets the standard font family of the web page. webFantasyFont(family: string) -Sets the fantasy font family of the web page. +Sets the fantasy font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ------- | ------------------------------ | -| family | string | Yes | fantasy | Fantasy font family of the web page.| +| family | string | Yes | fantasy | Fantasy font family to set.| **Example** @@ -955,13 +1090,13 @@ Sets the fantasy font family of the web page. webCursiveFont(family: string) -Sets the cursive font family of the web page. +Sets the cursive font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ------- | ------------------------------ | -| family | string | Yes | cursive | Cursive font family of the web page.| +| family | string | Yes | cursive | Cursive font family to set.| **Example** @@ -982,6 +1117,100 @@ Sets the cursive font family of the web page. } ``` +### darkMode9+ + +darkMode(mode: WebDarkMode) + +Sets the web dark mode. By default, web dark mode is disabled. When it is enabled, the **\** component enables the dark theme defined for web pages if the theme has been defined in **prefer-color-scheme** of a media query, and remains unchanged otherwise. To enable the forcible dark mode, use this API with [forceDarkAccess](#forcedarkaccess9). + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | ----------- | ---- | --------------- | ------------------ | +| mode | [WebDarkMode](#webdarkmode9) | Yes | WebDarkMode.Off | Web dark mode to set.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State mode: WebDarkMode = WebDarkMode.On + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .darkMode(this.mode) + } + } + } + ``` + +### forceDarkAccess9+ + +forceDarkAccess(access: boolean) + +Sets whether to enable forcible dark mode for the web page. By default, this feature is turned off. This API is applicable only when dark mode is enabled in [darkMode](#darkmode9). + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | ------- | ---- | ----- | ------------------ | +| access | boolean | Yes | false | Whether to enable forcible dark mode for the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State mode: WebDarkMode = WebDarkMode.On + @State access: boolean = true + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .darkMode(this.mode) + .forceDarkAccess(this.access) + } + } + } + ``` + +### pinchSmooth9+ + +pinchSmooth(isEnabled: boolean) + +Sets whether to enable smooth pinch mode for the web page. + +**Parameters** + +| Name | Type| Mandatory| Default Value| Description | +| --------- | -------- | ---- | ------ | -------------------------- | +| isEnabled | boolean | Yes | false | Whether to enable smooth pinch mode for the web page.| + +**Example** + + ```ts +// xxx.ets +import web_webview from '@ohos.web.webview' +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .pinchSmooth(true) + } + } +} + ``` + ## Events The universal events are not supported. @@ -998,7 +1227,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1056,7 +1285,7 @@ Triggered when this page is about to exit after the user refreshes or closes the | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1117,7 +1346,7 @@ Triggered when **confirm()** is invoked by the web page. | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1177,7 +1406,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1361,7 +1590,7 @@ Triggered when an HTTP error (the response code is greater than or equal to 400) | Name | Type | Description | | ------- | ---------------------------------------- | --------------- | | request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. | -| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.| +| response | [WebResourceResponse](#webresourceresponse) | Encapsulation of a resource response.| **Example** @@ -1564,7 +1793,7 @@ Triggered when loading of the web page is complete. This API is used by an appli } ``` -### onRenderExited +### onRenderExited9+ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void) @@ -1831,7 +2060,7 @@ Invoked when an HTTP authentication request is received. | Name | Type | Description | | ------- | ------------------------------------ | ---------------- | -| handler | [HttpAuthHandler](#httpauthhandler9) | The user's operation. | +| handler | [HttpAuthHandler](#httpauthhandler9) | User operation. | | host | string | Host to which HTTP authentication credentials apply.| | realm | string | Realm to which HTTP authentication credentials apply. | @@ -1900,7 +2129,7 @@ Invoked when an SSL error occurs during resource loading. | Name | Type | Description | | ------- | ------------------------------------ | -------------- | -| handler | [SslErrorHandler](#sslerrorhandler9) | The user's operation.| +| handler | [SslErrorHandler](#sslerrorhandler9) | User operation.| | error | [SslError](#sslerror9) | Error code. | **Example** @@ -1945,7 +2174,7 @@ Invoked when an SSL error occurs during resource loading. ### onClientAuthenticationRequest9+ -onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\, issuers : Array\}) => void) +onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array, issuers : Array}) => void) Invoked when an SSL client certificate request is received. @@ -1953,11 +2182,11 @@ Invoked when an SSL client certificate request is received. | Name | Type | Description | | -------- | ---------------------------------------- | --------------- | -| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation. | +| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | User operation. | | host | string | Host name of the server that requests a certificate. | | port | number | Port number of the server that requests a certificate. | -| keyTypes | Array\ | Acceptable asymmetric private key types. | -| issuers | Array\ | Issuer of the certificate that matches the private key.| +| keyTypes | Array | Acceptable asymmetric private key types. | +| issuers | Array | Issuer of the certificate that matches the private key.| **Example** ```ts @@ -2008,7 +2237,7 @@ Invoked when a permission request is received. | Name | Type | Description | | ------- | ---------------------------------------- | -------------- | -| request | [PermissionRequest](#permissionrequest9) | The user's operation.| +| request | [PermissionRequest](#permissionrequest9) | User operation.| **Example** @@ -2051,7 +2280,7 @@ Invoked when a permission request is received. onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean) -Invoked when a context menu is displayed upon a long press on a specific element (such as an image or link). +Shows a context menu after the user clicks the right mouse button or long presses a specific element, such as an image or a link. **Parameters** @@ -2131,7 +2360,7 @@ Registers a callback for receiving a request to obtain the geolocation informati | Name | Type | Description | | ----------- | ------------------------------- | -------------- | | origin | string | Index of the origin. | -| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.| +| geolocation | [JsGeolocation](#jsgeolocation) | User operation.| **Example** @@ -2285,6 +2514,7 @@ Registers a callback for window creation. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { @@ -2626,7 +2856,7 @@ Notifies the **\** component of the user's confirm operation in the dialog ## FullScreenExitHandler9+ -Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see onFullScreenEnter. +Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9). ### exitFullScreen9+ @@ -2830,15 +3060,15 @@ Obtains the MIME type of the resource response. ### setResponseData9+ -setResponseData(data: string) +setResponseData(data: string | number) Sets the data in the resource response. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | ----------- | -| data | string | Yes | - | Resource response data to set.| +| Name| Type | Mandatory| Default Value| Description | +| ------ | ---------------- | ---- | ------ | ------------------------------------------------------------ | +| data | string \| number | Yes | - | Resource response data to set. When set to a number, the value indicates a file handle.| ### setResponseEncoding9+ @@ -2900,6 +3130,18 @@ Sets the status code of the resource response. | ---- | ------ | ---- | ---- | ------------- | | code | number | Yes | - | Status code to set.| +### setResponseIsReady9+ + +setResponseIsReady(IsReady: boolean) + +Sets whether the resource response data is ready. + +**Parameters** + +| Name | Type| Mandatory| Default Value| Description | +| ------- | -------- | ---- | ------ | -------------------------- | +| IsReady | boolean | Yes | true | Whether the resource response data is ready.| + ## FileSelectorResult9+ Notifies the **\** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9). @@ -3098,11 +3340,46 @@ Grants the permission for resources requested by the web page. | Name | Type | Mandatory | Default Value | Description | | --------- | --------------- | ---- | ---- | ------------- | -| resources | Array\ | Yes | - | List of accessible resources requested by the web page.| +| resources | Array\ | Yes | - | List of resources that can be requested by the web page with the permission to grant.| + +## ContextMenuSourceType9+ +| Name | Description | +| -------------------- | ---------- | +| None | Other event sources. | +| Mouse | Mouse event. | +| LongPress | Long press event. | + +## ContextMenuMediaType9+ + +| Name | Description | +| ------------ | ----------- | +| None | Non-special media or other media types.| +| Image | Image. | + +## ContextMenuInputFieldType9+ + +| Name | Description | +| ------------ | ----------- | +| None | Non-input field. | +| PlainText | Plain text field, such as the text, search, or email field. | +| Password | Password field. | +| Number | Numeric field. | +| Telephone | Phone number field.| +| Other | Field of any other type. | + +## ContextMenuEditStateFlags9+ + +| Name | Description | +| ------------ | ----------- | +| NONE | Editing is not allowed. | +| CAN_CUT | The cut operation is allowed. | +| CAN_COPY | The copy operation is allowed. | +| CAN_PASTE | The paste operation is allowed. | +| CAN_SELECT_ALL | The select all operation is allowed.| ## WebContextMenuParam9+ -Provides the information about the context menu that is displayed when a page element is long pressed. For the sample code, see [onContextMenuShow](#oncontextmenushow9). +Implements a context menu, which is displayed after the user clicks the right mouse button or long presses a specific element, such as an image or a link. For the sample code, see [onContextMenuShow](#oncontextmenushow9). ### x9+ @@ -3176,9 +3453,81 @@ Checks whether image content exists. | ------- | ------------------------- | | boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.| +### getMediaType9+ + +getMediaType(): ContextMenuMediaType + +Obtains the media type of this web page element. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuMediaType](#contextmenumediatype9) | Media type of the web page element.| + +### getSelectionText9+ + +getSelectionText(): string + +Obtains the selected text. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| string | Selected text for the context menu. If no text is selected, null is returned.| + +### getSourceType9+ + +getSourceType(): ContextMenuSourceType + +Obtains the event source of the context menu. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuSourceType](#contextmenusourcetype9) | Event source of the context menu.| + +### getInputFieldType9+ + +getInputFieldType(): ContextMenuInputFieldType + +Obtains the input field type of this web page element. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuInputFieldType](#contextmenuinputfieldtype9) | Input field type.| + +### isEditable9+ + +isEditable(): boolean + +Checks whether this web page element is editable. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| boolean | Returns **true** if the web page element is editable; returns **false** otherwise.| + +### getEditStateFlags9+ + +getEditStateFlags(): number + +Obtains the edit state flag of this web page element. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| number | Edit state flag of the web page element. For details, see [ContextMenuEditStateFlags](#contextmenueditstateflags9).| + ## WebContextMenuResult9+ -Implements a **WebContextMenuResult** object. For the sample code, see onContextMenuShow. +Implements a **WebContextMenuResult** object. For the sample code, see [onContextMenuShow](#oncontextmenushow9). ### closeContextMenu9+ @@ -3192,6 +3541,30 @@ copyImage(): void Copies the image specified in **WebContextMenuParam**. +### copy9+ + +copy(): void + +Performs the copy operation related to this context menu. + +### paste9+ + +paste(): void + +Performs the paste operation related to this context menu. + +### cut9+ + +cut(): void + +Performs the cut operation related to this context menu. + +### selectAll9+ + +selectAll(): void + +Performs the select all operation related to this context menu. + ## JsGeolocation Implements the **PermissionRequest** object. For the sample code, see [onGeolocationShow Event](#ongeolocationshow). @@ -3208,24 +3581,28 @@ Sets the geolocation permission status of a web page. | ------ | ------- | ---- | ---- | ---------------------------------------- | | origin | string | Yes | - | Index of the origin. | | allow | boolean | Yes | - | Geolocation permission status. | -| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.| +| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. You can manage the geolocation permissions saved to the system through [GeolocationPermissions9+](../apis/js-apis-webview.md#geolocationpermissions).| ## WebController Implements a **WebController** to control the behavior of the **\** component. A **WebController** can control only one **\** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\** component. +This API is deprecated since API version 9. You are advised to use [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller). + ### Creating an Object ``` webController: WebController = new WebController() ``` -### requestFocus +### requestFocus(deprecated) requestFocus() Requests focus for this web page. +This API is deprecated since API version 9. You are advised to use [requestFocus9+](../apis/js-apis-webview.md#requestfocus). + **Example** ```ts @@ -3247,12 +3624,14 @@ Requests focus for this web page. } ``` -### accessBackward +### accessBackward(deprecated) accessBackward(): boolean Checks whether going to the previous page can be performed on the current page. +This API is deprecated since API version 9. You are advised to use [accessBackward9+](../apis/js-apis-webview.md#accessbackward). + **Return value** | Type | Description | @@ -3281,12 +3660,14 @@ Checks whether going to the previous page can be performed on the current page. } ``` -### accessForward +### accessForward(deprecated) accessForward(): boolean Checks whether going to the next page can be performed on the current page. +This API is deprecated since API version 9. You are advised to use [accessForward9+](../apis/js-apis-webview.md#accessforward). + **Return value** | Type | Description | @@ -3315,12 +3696,14 @@ Checks whether going to the next page can be performed on the current page. } ``` -### accessStep +### accessStep(deprecated) accessStep(step: number): boolean Performs a specific number of steps forward or backward from the current page. +This API is deprecated since API version 9. You are advised to use [accessStep9+](../apis/js-apis-webview.md#accessstep). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3356,12 +3739,14 @@ Performs a specific number of steps forward or backward from the current page. } ``` -### backward +### backward(deprecated) backward(): void Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. +This API is deprecated since API version 9. You are advised to use [backward9+](../apis/js-apis-webview.md#backward). + **Example** ```ts @@ -3383,12 +3768,14 @@ Goes to the previous page based on the history stack. This API is generally used } ``` -### forward +### forward(deprecated) forward(): void Goes to the next page based on the history stack. This API is generally used together with **accessForward**. +This API is deprecated since API version 9. You are advised to use [forward9+](../apis/js-apis-webview.md#forward). + **Example** ```ts @@ -3444,12 +3831,14 @@ Performs a specific number of steps forward or backward on the current page base } ``` -### deleteJavaScriptRegister +### deleteJavaScriptRegister(deprecated) deleteJavaScriptRegister(name: string) Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refresh) API. +This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister9+](../apis/js-apis-webview.md#deletejavascriptregister). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3478,12 +3867,14 @@ Deletes a specific application JavaScript object that is registered with the win } ``` -### getHitTest +### getHitTest(deprecated) getHitTest(): HitTestType Obtains the element type of the area being clicked. +This API is deprecated since API version 9. You are advised to use [getHitTest9+](../apis/js-apis-webview.md#gethittest). + **Return value** | Type | Description | @@ -3678,7 +4069,7 @@ Obtains the default user agent of the current web page. } ``` -### loadData +### loadData(deprecated) loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }) @@ -3688,6 +4079,8 @@ If **baseUrl** is set to a data URL, the encoded string will be loaded by the ** If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **\** component as a non-encoded string in a manner similar to **loadUrl**. +This API is deprecated since API version 9. You are advised to use [loadData9+](../apis/js-apis-webview.md#loaddata). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3723,7 +4116,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces } ``` -### loadUrl +### loadUrl(deprecated) loadUrl(options: { url: string | Resource, headers?: Array\ }) @@ -3733,6 +4126,8 @@ The object injected through **loadUrl** is valid only in the current document. I The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**. +This API is deprecated since API version 9. You are advised to use [loadUrl9+](../apis/js-apis-webview.md#loadurl). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3761,12 +4156,14 @@ The object injected through **registerJavaScriptProxy** is still valid on a new } ``` -### onActive +### onActive(deprecated) onActive(): void Invoked when the **\** component enters the active state. +This API is deprecated since API version 9. You are advised to use [onActive9+](../apis/js-apis-webview.md#onactive). + **Example** ```ts @@ -3788,12 +4185,14 @@ Invoked when the **\** component enters the active state. } ``` -### onInactive +### onInactive(deprecated) onInactive(): void Invoked when the **\** component enters the inactive state. +This API is deprecated since API version 9. You are advised to use [onInactive9+](../apis/js-apis-webview.md#oninactive). + **Example** ```ts @@ -3815,11 +4214,13 @@ Invoked when the **\** component enters the inactive state. } ``` -### zoom +### zoom(deprecated) zoom(factor: number): void Sets a zoom factor for the current web page. +This API is deprecated since API version 9. You are advised to use [zoom9+](../apis/js-apis-webview.md#zoom). + **Parameters** | Name | Type | Mandatory | Description | @@ -3914,12 +4315,14 @@ Zooms out of this web page by 20%. } ``` -### refresh +### refresh(deprecated) refresh() Invoked when the **\** component refreshes the web page. +This API is deprecated since API version 9. You are advised to use [refresh9+](../apis/js-apis-webview.md#refresh). + **Example** ```ts @@ -3941,11 +4344,13 @@ Invoked when the **\** component refreshes the web page. } ``` -### registerJavaScriptProxy +### registerJavaScriptProxy(deprecated) registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\ }) -Registers a JavaScript object and invokes the methods of the object in the window. You must invoke the [refresh](#refresh) API for the registration to take effect. +Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. You must invoke the [refresh](#refresh) API for the registration to take effect. + +This API is deprecated since API version 9. You are advised to use [registerJavaScriptProxy9+](../apis/js-apis-webview.md#registerjavascriptproxy). **Parameters** @@ -4007,12 +4412,14 @@ Registers a JavaScript object and invokes the methods of the object in the windo ``` -### runJavaScript +### runJavaScript(deprecated) runJavaScript(options: { script: string, callback?: (result: string) => void }) Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. +This API is deprecated since API version 9. You are advised to use [runJavaScript9+](../apis/js-apis-webview.md#runjavascript). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -4066,12 +4473,14 @@ Executes a JavaScript script. This API uses an asynchronous callback to return t ``` -### stop +### stop(deprecated) stop() Stops page loading. +This API is deprecated since API version 9. You are advised to use [stop9+](../apis/js-apis-webview.md#stop). + **Example** ```ts @@ -4093,12 +4502,14 @@ Stops page loading. } ``` -### clearHistory +### clearHistory(deprecated) clearHistory(): void Clears the browsing history. +This API is deprecated since API version 9. You are advised to use [clearHistory9+](../apis/js-apis-webview.md#clearhistory). + **Example** ```ts @@ -4626,7 +5037,7 @@ Obtains the cookie value corresponding to the specified URL. Column() { Button('getCookie') .onClick(() => { - let value = webview.WebCookieManager.getCookie('www.example.com') + let value = web_webview.WebCookieManager.getCookie('www.example.com') console.log("value: " + value) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4676,44 +5087,10 @@ Sets a cookie value for the specified URL. } ``` -### saveCookieSync9+ -saveCookieSync(): boolean - -Saves the cookies in the memory to the drive. This API returns the result synchronously. - -**Return value** - -| Type | Description | -| ------- | -------------------- | -| boolean | Operation result.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('saveCookieSync') - .onClick(() => { - let result = web_webview.WebCookieManager.saveCookieSync() - console.log("result: " + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - ### saveCookieAsync9+ saveCookieAsync(): Promise\ -Saves cookies in the memory to the drive. This API uses a promise to return the value. +Saves the cookies in the memory to the drive. This API uses a promise to return the value. **Return value** @@ -4752,7 +5129,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the ### saveCookieAsync9+ saveCookieAsync(callback: AsyncCallback\): void -Saves cookies in the memory to the drive. This API uses an asynchronous callback to return the result. +Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. **Parameters** @@ -4998,158 +5375,7 @@ Deletes all session cookies. Column() { Button('deleteSessionCookie') .onClick(() => { - webview.WebCookieManager.deleteSessionCookie() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -## WebDataBase9+ -Implements the **WebDataBase** object. - -### existHttpAuthCredentials9+ - -static existHttpAuthCredentials(): boolean - -Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. - -**Return value** - -| Type | Description | -| ------- | ---------------------------------------- | -| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('existHttpAuthCredentials') - .onClick(() => { - let result = web_webview.WebDataBase.existHttpAuthCredentials() - console.log('result: ' + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### deleteHttpAuthCredentials9+ - -static deleteHttpAuthCredentials(): void - -Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('deleteHttpAuthCredentials') - .onClick(() => { - web_webview.WebDataBase.deleteHttpAuthCredentials() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getHttpAuthCredentials9+ - -static getHttpAuthCredentials(host: string, realm: string): Array\ - -Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ----- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host to which HTTP authentication credentials apply.| -| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | - -**Return value** - -| Type | Description | -| --------------- | ---------------------- | -| Array\ | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - host: string = "www.spincast.org" - realm: string = "protected example" - username_password: string[] - build() { - Column() { - Button('getHttpAuthCredentials') - .onClick(() => { - this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm) - console.log('num: ' + this.username_password.length) - ForEach(this.username_password, (item) => { - console.log('username_password: ' + item) - }, item => item) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### saveHttpAuthCredentials9+ - -static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void - -Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host to which HTTP authentication credentials apply.| -| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | -| username | string | Yes | - | User name. | -| password | string | Yes | - | Password. | - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - host: string = "www.spincast.org" - realm: string = "protected example" - build() { - Column() { - Button('saveHttpAuthCredentials') - .onClick(() => { - web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche") + web_webview.WebCookieManager.deleteSessionCookie() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5157,783 +5383,88 @@ Saves HTTP authentication credentials for a given host and realm. This API retur } ``` -## GeolocationPermissions9+ - -Implements a **GeolocationPermissions** object. - -### allowGeolocation9+ - -static allowGeolocation(origin: string): void - -Allows the specified origin to use the geolocation information. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| - -**Example** +## MessageLevel - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('allowGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.allowGeolocation(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Name | Description | +| ----- | :---- | +| Debug | Debug level.| +| Error | Error level.| +| Info | Information level.| +| Log | Log level.| +| Warn | Warning level. | -### deleteGeolocation9+ +## RenderExitReason -static deleteGeolocation(origin: string): void +Enumerates the reasons why the rendering process exits. -Clears the geolocation permission status of a specified origin. +| Name | Description | +| -------------------------- | ----------------- | +| ProcessAbnormalTermination | The rendering process exits abnormally. | +| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| +| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | +| ProcessOom | The program memory is running low. | +| ProcessExitUnknown | Other reason. | -**Parameters** +## MixedMode -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| +| Name | Description | +| ---------- | ---------------------------------- | +| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| +| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | +| None | HTTP and HTTPS hybrid content cannot be loaded. | -**Example** +## CacheMode +| Name | Description | +| ------- | ------------------------------------ | +| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| +| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | +| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | +| Only | The cache alone is used to load the resources. | - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('deleteGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.deleteGeolocation(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +## FileSelectorMode +| Name | Description | +| -------------------- | ---------- | +| FileOpenMode | Open and upload a file. | +| FileOpenMultipleMode | Open and upload multiple files. | +| FileOpenFolderMode | Open and upload a folder.| +| FileSaveMode | Save a file. | -### deleteAllGeolocation9+ + ## HitTestType -static deleteAllGeolocation(): void +| Name | Description | +| ------------- | ------------------------ | +| EditText | Editable area. | +| Email | Email address. | +| HttpAnchor | Hyperlink whose **src** is **http**. | +| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| +| Img | HTML::img tag. | +| Map | Geographical address. | +| Phone | Phone number. | +| Unknown | Unknown content. | -Clears the geolocation permission status of all sources. +## SslError9+ -**Example** +Enumerates the error codes returned by **onSslErrorEventReceive** API. - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('deleteAllGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.deleteAllGeolocation() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Name | Description | +| ------------ | ----------- | +| Invalid | Minor error. | +| HostMismatch | The host name does not match. | +| DateInvalid | The certificate has an invalid date. | +| Untrusted | The certificate issuer is not trusted.| -### getAccessibleGeolocation9+ +## ProtectedResourceType9+ -static getAccessibleGeolocation(origin: string, callback: AsyncCallback\): void +| Name | Description | Remarks | +| --------- | ------------- | -------------------------- | +| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| -Obtains the geolocation permission status of the specified source. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------------------------ | ---- | ---- | ---------------------------------------- | -| origin | string | Yes | - | Index of the origin. | -| callback | AsyncCallback\ | Yes | - | Callback used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('getAccessibleGeolocationAsync') - .onClick(() => { - web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { - if (error) { - console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)) - return - } - console.log('getAccessibleGeolocationAsync result: ' + result) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getAccessibleGeolocation9+ - -static getAccessibleGeolocation(origin: string): Promise\ - -Obtains the geolocation permission status of the specified source. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| - -**Return value** - -| Type | Description | -| ------------------ | ---------------------------------------- | -| Promise\ | Promise used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('getAccessibleGeolocationPromise') - .onClick(() => { - web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => { - console.log('getAccessibleGeolocationPromise result: ' + result) - }).catch(error => { - console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getStoredGeolocation9+ - -static getStoredGeolocation(callback: AsyncCallback\\>): void - -Obtains the geolocation permission status of all sources. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | -------------------------------- | ---- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('getStoredGeolocationAsync') - .onClick(() => { - web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { - if (error) { - console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)) - return - } - let origins_str: string = origins.join() - console.log('getStoredGeolocationAsync origins: ' + origins_str) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getStoredGeolocation9+ - -static getStoredGeolocation(): Promise\\> - -Obtains the geolocation permission status of all sources. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | -------------------------------- | ---- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.| - -**Return value** - -| Type | Description | -| -------------------------- | -------------------------------- | -| Promise\\> | Promise used to return the geolocation permission status of all sources.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('getStoredGeolocationPromise') - .onClick(() => { - web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => { - let origins_str: string = origins.join() - console.log('getStoredGeolocationPromise origins: ' + origins_str) - }).catch(error => { - console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -## WebStorage9+ -Implements the **WebStorage** object, which can be used to manage the Web SQL and the HTML5 Web Storage API. All **\** components in an application share one **WebStorage**. -### deleteAllData9+ -static deleteAllData(): void - -Deletes all data in the Web SQL Database. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('deleteAllData') - .onClick(() => { - web_webview.WebStorage.deleteAllData() - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### deleteOrigin9+ -static deleteOrigin(origin : string): void - -Deletes all data in the specified origin. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getHttpAuthCredentials') - .onClick(() => { - web_webview.WebStorage.deleteOrigin(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOrigins9+ -static getOrigins(callback: AsyncCallback\>) : void - -Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the information about the origins. For details, see **WebStorageOrigin**.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOrigins') - .onClick(() => { - web_webview.WebStorage.getOrigins((error, origins) => { - if (error) { - console.log('error: ' + error) - return - } - for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin) - console.log('usage: ' + origins[i].usage) - console.log('quota: ' + origins[i].quota) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOrigins9+ -static getOrigins() : Promise\> - -Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. - -**Return value** - -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise> | Promise used to return the information about the origins. For details, see **WebStorageOrigin**.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOrigins') - .onClick(() => { - web_webview.WebStorage.getOrigins() - .then(origins => { - for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin) - console.log('usage: ' + origins[i].usage) - console.log('quota: ' + origins[i].quota) - } - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginQuota9+ -static getOriginQuota(origin : string, callback : AsyncCallback\) : void - -Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | --------- | -| origin | string | Yes | Index of the origin.| -| callback | AsyncCallback\ | Yes | Callback used to return the storage quota of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { - if (error) { - console.log('error: ' + error) - return - } - console.log('quota: ' + quota) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginQuota9+ -static getOriginQuota(origin : string) : Promise\ - -Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Return value** - -| Type | Description | -| ---------------- | ----------------------- | -| Promise\ | Promise used to return the storage quota of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginQuota(this.origin) - .then(quota => { - console.log('quota: ' + quota) - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginUsage9+ -static getOriginUsage(origin : string, callback : AsyncCallback\) : void - -Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---------- | -| origin | string | Yes | Index of the origin.| -| callback | AsyncCallback\ | Yes | Callback used to return the storage usage of the origin. | - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginUsage') - .onClick(() => { - web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { - if (error) { - console.log('error: ' + error) - return - } - console.log('usage: ' + usage) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginUsage9+ -static getOriginUsage(origin : string) : Promise\ - -Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Return value** - -| Type | Description | -| ---------------- | ---------------------- | -| Promise\ | Promise used to return the storage usage of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginUsage(this.origin) - .then(usage => { - console.log('usage: ' + usage) - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -## WebStorageOrigin9+ - -Provides usage information about the Web SQL Database. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| -| usage | number | Yes | Storage usage of the origin. | -| quota | number | Yes | Storage quota of the origin. | - -## MessageLevel - -| Name | Description | -| ----- | :---- | -| Debug | Debug level.| -| Error | Error level.| -| Info | Information level.| -| Log | Log level.| -| Warn | Warning level. | - -## RenderExitReason - -Enumerates the reasons why the rendering process exits. - -| Name | Description | -| -------------------------- | ----------------- | -| ProcessAbnormalTermination | The rendering process exits abnormally. | -| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| -| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | -| ProcessOom | The program memory is running low. | -| ProcessExitUnknown | Other reason. | - -## MixedMode - -| Name | Description | -| ---------- | ---------------------------------- | -| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| -| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | -| None | HTTP and HTTPS hybrid content cannot be loaded. | - -## CacheMode +## WebDarkMode9+ | Name | Description | | ------- | ------------------------------------ | -| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| -| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | -| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | -| Only | The cache alone is used to load the resources. | - -## FileSelectorMode -| Name | Description | -| -------------------- | ---------- | -| FileOpenMode | Open and upload a file. | -| FileOpenMultipleMode | Open and upload multiple files. | -| FileOpenFolderMode | Open and upload a folder.| -| FileSaveMode | Save a file. | - - ## HitTestType - -| Name | Description | -| ------------- | ------------------------ | -| EditText | Editable area. | -| Email | Email address. | -| HttpAnchor | Hyperlink whose **src** is **http**. | -| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| -| Img | HTML::img tag. | -| Map | Geographical address. | -| Phone | Phone number. | -| Unknown | Unknown content. | - -## SslError9+ - -Enumerates the error codes returned by **onSslErrorEventReceive** API. - -| Name | Description | -| ------------ | ----------- | -| Invalid | Minor error. | -| HostMismatch | The host name does not match. | -| DateInvalid | The certificate has an invalid date. | -| Untrusted | The certificate issuer is not trusted.| - -## ProtectedResourceType9+ - -| Name | Description | Remarks | -| --------- | ------------- | -------------------------- | -| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| - -## WebAsyncController - -Implements the **WebAsyncController** object, which can be used to control the behavior of a **\** component with asynchronous callbacks. A **WebAsyncController **object controls one **\** component. - -### Creating an Object - -``` -webController: WebController = new WebController(); -webAsyncController: WebAsyncController = new WebAsyncController(webController); -``` - -### storeWebArchive9+ - -storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback): void - -Stores this web page. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. -| callback | AsyncCallback | Yes | Callback used to return the save path if the operation is successful and null otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('saveWebArchive') - .onClick(() => { - let webAsyncController = new web_webview.WebAsyncController(this.controller) - webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { - if (filename != null) { - console.info(`save web archive success: ${filename}`) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### storeWebArchive9+ - -storeWebArchive(baseName: string, autoName: boolean): Promise - -Stores this web page. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. - -**Return value** - -| Type | Description | -| --------------- | -------------------------------- | -| Promise | Promise used to return the save path if the operation is successful and null otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - build() { - Column() { - Button('saveWebArchive') - .onClick(() => { - let webAsyncController = new web_webview.WebAsyncController(this.controller); - webAsyncController.storeWebArchive("/data/storage/el2/base/", true) - .then(filename => { - if (filename != null) { - console.info(`save web archive success: ${filename}`) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Off | The web dark mode is disabled. | +| On | The web dark mode is enabled. | +| Auto | The web dark mode setting follows the system settings. | ## WebMessagePort9+ @@ -6158,7 +5689,7 @@ Sets the message port in this object. For the complete sample code, see [postMes ## DataResubmissionHandler9+ -Implements the **DataResubmissionHandler** for resubmitting or canceling the web form data. +Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. ### resend9+ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index 5430e54558a7cfd30a7bc139820d130316a1ad97..f775992c63793b3f41e30d819fab405be931be90 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -6,27 +6,26 @@ The **\** can accept and display the EGL/OpenGL ES and media data in > > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - - ## Child Components - Child components are not supported when **type** is set to **"surface"**.\ - Since API version 9, child components are supported when **type** is set to **"component"**. +Child components are not supported when **type** is set to **"surface"**. + +Since API version 9, child components are supported when **type** is set to **"component"**. ## APIs - XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) +XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters.| -| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The content of the component is displayed individually, without being combined with that of other components. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.| -| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when the component type is **"surface"**.| -| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke the methods of the component. This parameter is valid only when the component type is **"surface"**. | +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | +| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The content of the component is displayed individually, without being combined with that of other components. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.| +| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when the component type is **"surface"**.| +| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.| -> **NOTE**
+> **NOTE** > > When **type** is set to **"component"**, the **\** functions as a container, where child components are laid out vertically. > @@ -46,7 +45,7 @@ The **\** can accept and display the EGL/OpenGL ES and media data in ## Events -The following events are supported only when **type** is set to **"surface"**. The [universal events and gestures](./Readme-EN.md) are not supported. +The following events are supported only when **type** is set to **"surface"**. The [universal events](ts-universal-events-click.md) and [universal gestures](ts-gesture-settings.md) are not supported. ### onLoad @@ -56,9 +55,9 @@ Triggered when the plug-in is loaded. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------ | ---- | ----------------------- | -| event | object | No | Context of the **\** object. The APIs contained in the context are defined at the C++ layer by developers.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| event | object | No | Context of the **\** object. The APIs contained in the context are defined at the C++ layer by developers.| ### onDestroy @@ -99,7 +98,7 @@ Sets the width and height of the surface held by the **\**. This API **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ------------- | ------ | ---- | ----------------------- | | surfaceWidth | number | Yes | Width of the surface held by the **\**.| | surfaceHeight | number | Yes | Height of the surface held by the **\**.| 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 d0c3c2e1860d77390c679134eefc540ddcae238d..7c8b95655a9470ea7fd1951132f7b2c7974a45da 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 @@ -41,9 +41,9 @@ struct Page45 { .backgroundColor('#ffff00') .onReady(() => { var grad = this.context.createLinearGradient(50, 0, 300, 100) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') this.context.fillStyle = grad this.context.fillRect(0, 0, 500, 500) }) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md index bbfdaa6a6a21679e5612634c6fa490ef0ceee187..6bb371dfa5dc1e8cb3c88c9b1618e035caf8294c 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md @@ -27,34 +27,35 @@ loadAnimation( path: string, container: object, render: string, loop: boolean, autoplay: boolean, name: string ): AnimationItem -Loads an animation. Before calling this API, declare the **Animator('__lottie_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**. +Loads an animation. Before calling this API, declare the **Animator('__lottie_ets')** object and make sure the canvas layout is complete. This API can be used together with the lifecycle callback **onReady()** of the **Canvas** component. **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | --------------------------- | ---- | ---------------------------------------- | -| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| -| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| -| render | string | Yes | Rendering type. The value can only be **"canvas"**. | -| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| -| autoplay | boolean | No | Whether to automatically play the animation.
Default value: **true** | +| Name | Type | Mandatory| Description | +| -------------- | --------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| +| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| +| render | string | Yes | Rendering type. The value can only be **"canvas"**. | +| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| +| autoplay | boolean | No | Whether to automatically play the animation.
Default value: **true** | | name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation.
Default value: null | -| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | +| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | ## lottie.destroy destroy(name: string): void -Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. +Destroys the animation. This API must be called when a page exits. This API can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| +| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** API. By default, all animations are destroyed. | **Example** + ```ts // xxx.ets import lottie from '@ohos/lottieETS' @@ -133,7 +134,7 @@ Plays a specified animation. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| +| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** API. By default, all animations are played. | **Example** @@ -152,7 +153,7 @@ Pauses a specified animation. The next time **lottie.play()** is called, the ani | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused. | **Example** @@ -165,13 +166,13 @@ Pauses a specified animation. The next time **lottie.play()** is called, the ani togglePause(name: string): void -Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**. +Pauses or plays a specified animation. This API is equivalent to the switching between **lottie.play()** and **lottie.pause()**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused or played. | **Example** @@ -190,7 +191,7 @@ Stops the specified animation. The next time **lottie.play()** is called, the an | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are stopped. | **Example** @@ -209,8 +210,8 @@ Sets the playback speed of the specified animation. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | -| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.| -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. | **Example** @@ -230,7 +231,7 @@ Sets the direction in which the specified animation plays. | Name | Type | Mandatory | Description | | --------- | ------------------ | ---- | ---------------------------------------- | | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1 | -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. | **Example** @@ -241,7 +242,7 @@ Sets the direction in which the specified animation plays. ## AnimationItem -Defines an **AnimationItem** object, which is returned by the **loadAnimation** interface and has attributes and interfaces. The attributes are described as follows: +Defines an **AnimationItem** object, which is returned by the **loadAnimation** API and has attributes and APIs. The attributes are described as follows: | Name | Type | Description | | ----------------- | ---------------------------------------- | ---------------------------------------- | @@ -253,18 +254,18 @@ Defines an **AnimationItem** object, which is returned by the **loadAnimation** | totalFrames | number | Total number of frames in the animation segment that is being played. | | frameRate | number | Frame rate (frame/s). | | frameMult | number | Frame rate (frame/ms). | -| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| -| playDirection | number | Playback direction. The options are **1** (forward) and **-1** (backward). | +| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | +| playDirection | number | Playback direction.
**1**: forward.
**-1**: backward. | | playCount | number | Number of times the animation plays. | | isPaused | boolean | Whether the current animation is paused. The value **true** means that the animation is paused. | -| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** interface needs to be called to start playing.| -| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | +| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** API needs to be called to start playing. | +| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | | renderer | any | Animation rendering object, which depends on the rendering type. | | animationID | string | Animation ID. | | timeCompleted | number | Number of frames that are played for an animation sequence. The value is affected by the setting of **AnimationSegment** and is the same as the value of **totalFrames**.| | segmentPos | number | ID of the current animation segment. The value is a positive integer greater than or equal to 0. | | isSubframeEnabled | boolean | Whether the precision of **currentFrame** is a floating point number. | -| segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. | +| segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. | ## AnimationItem.play @@ -309,7 +310,7 @@ Destroys an animation. pause(name?: string): void -Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame. +Pauses an animation. When the **play** API is called next time, the animation is played from the current frame. **Parameters** @@ -328,7 +329,7 @@ Pauses an animation. When the **play** interface is called next time, the animat togglePause(name?: string): void -Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**. +Pauses or plays an animation. This API is equivalent to the switching between **play** and **pause**. **Parameters** @@ -347,7 +348,7 @@ Pauses or plays an animation. This method is equivalent to the switching between stop(name?: string): void -Stops an animation. When the **play** interface is called next time, the animation is played from the first frame. +Stops an animation. When the **play** API is called next time, the animation is played from the first frame. **Parameters** @@ -372,7 +373,7 @@ Sets the playback speed of an animation. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | -| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | **Example** @@ -411,8 +412,8 @@ Sets the animation to stop at the specified frame or time. | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | -| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress.
Default value: **false** | -| name | string | No | Name of the target animation. By default, the value is null. | +| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress.
Default value: **false** | +| name | string | No | Name of the target animation. By default, the value is null. | **Example** @@ -435,8 +436,8 @@ Sets the animation to start from the specified frame or time progress. | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | -| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress.
Default value: **false** | -| name | string | No | Name of the target animation. By default, the value is null. | +| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress.
Default value: **false** | +| name | string | No | Name of the target animation.
Default value: null | **Example** @@ -459,7 +460,7 @@ Sets the animation to play only the specified segment. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | ---------------------------------------- | | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle.| -| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | +| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | **Example** @@ -475,7 +476,7 @@ Sets the animation to play only the specified segment. resetSegments(forceFlag: boolean): void -Resets the settings configured by the **playSegments** method to play all the frames. +Resets the settings configured by the **playSegments** API to play all the frames. **Parameters** @@ -526,7 +527,7 @@ Sets the precision of the **currentFrame** attribute to display floating-point n getDuration(inFrames?: boolean): void -Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface. +Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** API. **Parameters** @@ -545,7 +546,7 @@ Obtains the duration (irrelevant to the playback speed) or number of frames for addEventListener<T = any>(name: AnimationEventName, callback: AnimationEventCallback<T>): () => void -Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener. +Adds an event listener. After the event is complete, the specified callback is triggered. This API returns the function object that can delete the event listener. **Parameters** @@ -578,7 +579,7 @@ Removes an event listener. | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| -| callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | +| callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | **Example** diff --git a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md index 1b9fba3579fe3c18a8a7d8225e65bdcc2e3d163c..97b08d90ca88b2cef08ac931cc6a6405c2236dd5 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md @@ -134,7 +134,7 @@ struct AlphabetIndexerSample { .selectedFont({size: 16, weight: FontWeight.Bolder}) // Font style of the selected text. .popupFont({ size: 30, weight: FontWeight.Bolder}) // Font style of the pop-up text. .itemSize(28) // Size of an item in the alphabetic index bar. - .alignStyle(IndexerAlign.Left) // Position of the pop-up window relative to the center of the indexer bar's top border, which is left in this example. + .alignStyle(IndexerAlign.Left) // The pop-up window is displayed on the right of the alphabetic index bar. .onSelect((index: number) => { console.info(this.value[index] + ' Selected!') }) @@ -162,4 +162,4 @@ struct AlphabetIndexerSample { } ``` -![en-us_image_0000001212378392](figures/en-us_image_0000001212378392.gif) +![alphabet](figures/alphabet.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md b/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md index 06c65aa8f4147948d57226c034da55dd5e1e4840..f0e9f85f122e630c6f73f5443d0d4260abaaf5cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md @@ -16,7 +16,7 @@ The **\** component is used for element alignment in complex * A child component can set the container or another child component as the anchor. * To show in the **\**, child components must have an ID. The container ID is fixed at **__container__**. * Three positions of the child component in a direction can use three positions of the container or another child components in the same direction as anchors. If anchors are set for more than two positions in a single direction, the third position is skipped. - * The child component size set on the frontend page is not affected by the **\** rules. + * The child component size set on the frontend page is not affected by the **\** rules. If two or more **alignRules** values are set for one direction of the child component, you are not advised to set the size for this direction. * If offset is required after the alignment, it can be set through **offset**. * Exceptions * When a mutual or circular dependency occurs, none of the child components in the container are drawn. @@ -39,62 +39,60 @@ RelativeContainer() struct Index { build() { Row() { - Button("Extra button").width(100).height(50) RelativeContainer() { - Button("Button 1") - .width(120) - .height(30) + Row().width(100).height(100) + .backgroundColor("#FF3333") .alignRules({ - middle: { anchor: "__container__", align: HorizontalAlign.Center }, + top: {anchor: "__container__", align: VerticalAlign.Top}, + left: {anchor: "__container__", align: HorizontalAlign.Start} }) - .id("bt1") - .borderWidth(1) - .borderColor(Color.Black) + .id("row1") - Text("This is text 2") - .fontSize(20) - .padding(10) + Row().width(100).height(100) + .backgroundColor("#FFCC00") .alignRules({ - bottom: { anchor: "__container__", align: VerticalAlign.Bottom }, - top: { anchor: "bt1", align: VerticalAlign.Bottom }, - right: { anchor: "bt1", align: HorizontalAlign.Center } + top: {anchor: "__container__", align: VerticalAlign.Top}, + right: {anchor: "__container__", align: HorizontalAlign.End} }) - .id("tx2") - .borderWidth(1) - .borderColor(Color.Black) - .height(30) - - Button("Button 3") - .width(100) - .height(100) + .id("row2") + + Row().height(100) + .backgroundColor("#FF6633") .alignRules({ - left: { anchor: "bt1", align: HorizontalAlign.End }, - top: { anchor: "tx2", align: VerticalAlign.Center }, - bottom: { anchor: "__container__", align: VerticalAlign.Bottom } + top: {anchor: "row1", align: VerticalAlign.Bottom}, + left: {anchor: "row1", align: HorizontalAlign.End}, + right: {anchor: "row2", align: HorizontalAlign.Start} }) - .id("bt3") - .borderWidth(1) - .borderColor(Color.Black) + .id("row3") - Text("This is text 4") - .fontSize(20) - .padding(10) + Row() + .backgroundColor("#FF9966") .alignRules({ - left: { anchor: "tx2", align: HorizontalAlign.End }, - right: { anchor: "__container__", align: HorizontalAlign.End }, - top: { anchor: "__container__", align: VerticalAlign.Top }, - bottom: { anchor: "bt3", align: VerticalAlign.Top } + top: {anchor: "row3", align: VerticalAlign.Bottom}, + bottom: {anchor: "__container__", align: VerticalAlign.Bottom}, + left: {anchor: "__container__", align: HorizontalAlign.Start}, + right: {anchor: "row1", align: HorizontalAlign.End} }) - .id("tx4") - .borderWidth(1) - .borderColor(Color.Black) + .id("row4") + + Row() + .backgroundColor("#FF66FF") + .alignRules({ + top: {anchor: "row3", align: VerticalAlign.Bottom}, + bottom: {anchor: "__container__", align: VerticalAlign.Bottom}, + left: {anchor: "row2", align: HorizontalAlign.Start}, + right: {anchor: "__container__", align: HorizontalAlign.End} + }) + .id("row5") } - .width(200).height(200) - .backgroundColor(Color.Orange) + .width(300).height(300) + .margin({left: 100}) + .border({width:2, color: "#6699FF"}) } .height('100%') } } + ``` ![relative container](figures/relativecontainer.png) diff --git a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md index daf2238308091eaab298b7a757f0ef6e844eceb3..b2802444ab2e297ffc599263910afea57fee2465 100644 --- a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md +++ b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md @@ -20,7 +20,7 @@ animateTo(value: AnimateParam, event: () => void): void | -------- | -------- | -------- | | duration | number | Animation duration, in ms.
Default value: **1000**| | tempo | number | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.
Default value: **1.0**| -| curve | Curve \| Curves | Animation curve.
Default value: **Curve.Linear**| +| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | Animation curve.
Default value: **Curve.Linear**| | delay | number | Delay of animation playback, in ms. By default, the playback is not delayed.
Default value: **0**| | iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1**| | playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.
Default value: **PlayMode.Normal**| diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 4c6a674c969dcbbfdacdafbf39ccc008bdeb178d..22e6077c68daf2b9cc835c9af1b514ed7670e57e 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -1674,7 +1674,7 @@ struct Fill { region.lineTo(270, 90) region.closePath() // Fill path - this.offContext.fillStyle = 'green' + this.offContext.fillStyle = '#00ff00' this.offContext.fill(region, "evenodd") var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -2534,7 +2534,7 @@ struct CanvasExample { .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.save() // save the default state - this.offContext.fillStyle = "green" + this.offContext.fillStyle = "#00ff00" this.offContext.fillRect(20, 20, 100, 100) this.offContext.restore() // restore to the default state this.offContext.fillRect(150, 75, 100, 100) @@ -2575,7 +2575,7 @@ struct CanvasExample { .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.save() // save the default state - this.offContext.fillStyle = "green" + this.offContext.fillStyle = "#00ff00" this.offContext.fillRect(20, 20, 100, 100) this.offContext.restore() // restore to the default state this.offContext.fillRect(150, 75, 100, 100) @@ -2625,9 +2625,9 @@ Creates a linear gradient. .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.offContext.createLinearGradient(50,0, 300,100) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') this.offContext.fillStyle = grad this.offContext.fillRect(0, 0, 500, 500) var image = this.offContext.transferToImageBitmap() @@ -2679,9 +2679,9 @@ Creates a linear gradient. .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.offContext.createRadialGradient(200,200,50, 200,200,200) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') this.offContext.fillStyle = grad this.offContext.fillRect(0, 0, 500, 500) var image = this.offContext.transferToImageBitmap() 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 ecdaffd3f3407f079e1044031caaf43a9d2af843..2256aa963c944561e69ccbf110a656347afd448a 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -8,7 +8,7 @@ The framework provides four pixel units, with vp as the reference data unit. | 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.| +| 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. | ## Pixel Unit Conversion diff --git a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md index 2c8ba7c33a29b398ae2144c6435fe0d6a10671a6..2e0e8610515d57f66aa28d424140c657da95f368 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md @@ -42,4 +42,4 @@ struct AreaExample { } ``` -![en-us_image_0000001257058403](figures/en-us_image_0000001257058403.gif) +![en-us_image_0000001189634870](figures/en-us_image_0000001189634870.gif) \ No newline at end of file diff --git a/en/application-dev/reference/errorcodes/errorcode-avsession.md b/en/application-dev/reference/errorcodes/errorcode-avsession.md index 98b811bd159ccf0be5eed06746622a3686e96bce..a072aa68d0d35b21470b3c68e55b06a856466932 100644 --- a/en/application-dev/reference/errorcodes/errorcode-avsession.md +++ b/en/application-dev/reference/errorcodes/errorcode-avsession.md @@ -4,7 +4,7 @@ **Error Message** -Session service exception +Session service exception. **Description** @@ -24,7 +24,7 @@ The session service is killed during session restart. **Error Message** -The session does not exist +The session does not exist. **Description** @@ -44,7 +44,7 @@ The session has been destroyed, and no session record exists on the server. **Error Message** -The session controller does not exist +The session controller does not exist. **Description** @@ -62,7 +62,7 @@ Query the session record and create the corresponding controller. **Error Message** -The remote session connection failed +The remote session connection failed. **Description** @@ -80,7 +80,7 @@ Stop sending control commands to the session. Subscribe to output device changes **Error Message** -Invalid session command +Invalid session command. **Description** @@ -98,7 +98,7 @@ Stop sending the command or event. Query the commands supported by the session, **Error Message** -The session not active +The session is not activated. **Description** @@ -116,7 +116,7 @@ Stop sending the command or event. Subscribe to the session activation status, a **Error Message** -Command or event overload +Too many commands or events. **Description** diff --git a/en/application-dev/reference/errorcodes/errorcode-datashare.md b/en/application-dev/reference/errorcodes/errorcode-datashare.md new file mode 100644 index 0000000000000000000000000000000000000000..1dae1ebbae1af4b9940ffa6a81e9130eeaa4a94d --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-datashare.md @@ -0,0 +1,21 @@ +# DataShare Error Codes + +## 15700010 Failed to Create a DataShareHelper + +**Error Message** + +The dataShareHelper is not initialized successfully. + +**Description** + +The **DataShareHelper** class fails to be created. + +**Possible Causes** + +1. The **uri** specified in **createDataHelper** is incorrect. +2. The **context** specified in **createDataHelper** is incorrect. **DataShare** supports only the stage model. + +**Solution** + +1. Obtain the correct URI. +2. Check that the context of the stage model is used. diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md index f355a8fc938732f1e08b31ef3932d23f363db913..20a8a497c4cd041709840826f689ea52fec4b121 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md @@ -59,6 +59,6 @@ Application resources can be accessed via an absolute or relative path. In this ## Configuration Files -If you are developing a widget in the FA model, configure the **config.json** file. For details, see [FA Widget Development](../../ability/fa-formability.md#configuring-the-widget-configuration-file). +If you are developing a widget in the FA model, configure the **config.json** file. -If you are developing a widget in the stage model, configure **ExtensionAbility** under **extensionAbilities** in the **module.json5** file. For details, see [Stage Widget Development](../../ability/stage-formextension.md#configuring-the-widget-configuration-file). +If you are developing a widget in the stage model, configure **ExtensionAbility** under **extensionAbilities** in the **module.json5** file. diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md index 968ea8493c824313dc3828b99b098ba59031420f..2ebbe2b66d3bc4feac7fb0d090e2833e761f88c9 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md @@ -99,11 +99,11 @@ You can also implement redirection to the target application using a **want**, w | Selector | Type | Default Value | Description | | ------ | ------ | -------- | ---------------------------------------- | | action | string | "router" | Event type.
- **"router"**: redirection event.
- **"message"**: message event.| -| want | [Want](../apis/js-apis-application-Want.md) | - | Information about the target application. For details, see the **want** format. | +| want | [Want](../apis/js-apis-app-ability-want.md) | - | Information about the target application. For details, see the **want** format. | - ```json - { +```json + { "data": { "mainAbility": "xxx.xxx.xxx" }, @@ -124,9 +124,9 @@ You can also implement redirection to the target application using a **want**, w } } } - ``` +``` - In API version 8, the [featureAbility.getWant](../apis/js-apis-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters. + In API version 8, the [featureAbility.getWant](../apis/js-apis-ability-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters. - Message event properties diff --git a/en/application-dev/reference/syscap.md b/en/application-dev/reference/syscap.md index 295ec50046c660282964f41679bd7a3377ca846b..c800e185a8bd87029a9c83d4ab63065edcc448ce 100644 --- a/en/application-dev/reference/syscap.md +++ b/en/application-dev/reference/syscap.md @@ -4,7 +4,7 @@ ### System Capabilities and APIs -SysCap is short for SystemCapability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association. +SystemCapability (SysCap in short) refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association. ![image-20220326064841782](figures/image-20220326064841782.png) diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md index 0e45400d14daae6417908bf13ed0127d1ccb7284..20396da04e28f5c408b971d717f4af7bcbc3ca58 100644 --- a/en/application-dev/security/accesstoken-guidelines.md +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -13,7 +13,7 @@ This document describes the following operations: ## Declaring Permissions in the Configuration File -During the development, you need to declare the permissions required by your application one by one in the project configuration file. The application cannot obtain the permissions that are not declared in the configuration file. OpenHarmony provides two application models: FA model and stage model. For more information, see Application Models. The application bundle and configuration file vary with the application model. +During the development, you need to declare the permissions required by your application one by one in the project configuration file. The application cannot obtain the permissions that are not declared in the configuration file. OpenHarmony provides two application models: FA model and stage model. For more information, see [Application Models](../application-models/application-model-description.md). The application bundle and configuration file vary with the application model. > **NOTE**
The default APL of an application is **normal**. When an application needs the **system_basic** or **system_core** APL, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-permissions-in-the-acl). @@ -119,7 +119,7 @@ For example, if an application needs to access audio files of a user and capture If an application needs to access user privacy information or use system abilities, for example, accessing location or calendar information or using the camera to take photos or record videos, it must request the permission from users. A permission verification is performed first to determine whether the current invoker has the corresponding permission. If the application has not obtained that permission, a dialog box will be displayed to request user authorization. The following figure shows an example. -> **NOTE**
Each time before an API protected by a permission is accessed, the **requestPermissionsFromUser()** API will be called to request user authorization. After a permission is dynamically granted, the user may revoke the permission. Therefore, the previously granted authorization status cannot be persistent. +> **NOTE**
Each time before an API protected by a permission is accessed, the [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) API will be called to request user authorization. After a permission is dynamically granted, the user may revoke the permission. Therefore, the previously granted authorization status cannot be persistent. ### Stage Model @@ -127,20 +127,20 @@ Example: Request the permission to read calendar information for an app. 1. Apply for the **ohos.permission.READ_CALENDAR** permission. For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file). -2. Call **requestPermissionsFromUser()** in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of **requestPermissionsFromUser()** indicates whether the application has the target permission. If yes, the target API can be called normally. - +2. Call [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) indicates whether the app has the target permission. If yes, the target API can be called normally. + Request user authorization in UIAbility. ```typescript import UIAbility from '@ohos.app.ability.UIAbility'; - import Window from '@ohos.window'; + import window from '@ohos.window'; import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import { Permissions } from '@ohos.abilityAccessCtrl'; export default class EntryAbility extends UIAbility { // ... - onWindowStageCreate(windowStage: Window.WindowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability let context = this.context; let AtManager = abilityAccessCtrl.createAtManager(); diff --git a/en/application-dev/security/app-provision-structure.md b/en/application-dev/security/app-provision-structure.md index d31cd6c690769d9a3ec6767a7f8187f5d9bfc4e7..a772f024a4179af75e30dcf4f6bc0483ed0f86b0 100644 --- a/en/application-dev/security/app-provision-structure.md +++ b/en/application-dev/security/app-provision-structure.md @@ -4,18 +4,18 @@ The **HarmonyAppProvision** configuration file (also called profile) is the file ## Configuration File Internal Structure The **HarmonyAppProvision** file consists of several parts, which are described in the table below. -| Name | Description | Data Type| Yes | Initial Value Allowed| +| Name | Description | Data Type| Mandatory | Initial Value Allowed| | ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- | -| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes| No | -| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes| No| +| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes | No | +| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes | No| | uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No| -| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes| No| +| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes | No| | issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes | No| | validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No | | bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes | No | -| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | Yes | -| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | Yes | -| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | Yes | +| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | Yes | +| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | Yes | +| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | Yes | | app-privilege-capabilities | Privilege information required by the application bundle. For details, see the [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). | String array| No | Yes | An example of the **HarmonyAppProvision** file is as follows: @@ -58,42 +58,42 @@ An example of the **HarmonyAppProvision** file is as follows: | Name | Description | Data Type| Mandatory | Initial Value Allowed| | ---------- | ------------------------------- | ------- | ------- | --------- | -| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | -| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | +| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | +| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | ### Internal Structure of the bundle-info Object | Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | -------- | --------- | -| developer-id | Unique ID of the developer.| String | Yes | No | -| development-certificate | Information about the [debug certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | -| distribution-certificate | Information about the [release certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No | -| bundle-name | Bundle name of the application.| String | Yes | No | -| apl | [Ability privilege level (APL)](accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No | +| developer-id | Unique ID of the developer.| String | Yes | No | +| development-certificate | Information about the [debug certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | +| distribution-certificate | Information about the [release certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No | +| bundle-name | Bundle name of the application.| String | Yes | No | +| apl | [Ability privilege level (APL)](accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No | | app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (normal application). Only system applications are allowed to call system APIs. If a normal application calls a system API, the call cannot be successful or the application may run abnormally.| String | Yes | No | ### Internal Structure of the acls Object -The **acls** object contains the [ACL](accesstoken-overview.md) configured for your application. It should be noted that you still need to add the ACL information to the **requestPermissions** attribute in the application configuration file. +The **acls** object contains the [ACL](accesstoken-overview.md) configured for your application. It should be noted that you still need to add the ACL information to the [**requestPermissions**](../quick-start/module-configuration-file.md#requestpermissions) attribute in the application configuration file. | Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No| No | +| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No | No | ### Internal Structure of the permissions Object -The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to add the ACL information to the **requestPermissions** attribute in the application configuration file. +The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to add the ACL information to the [**requestPermissions**](../quick-start/module-configuration-file.md#requestpermissions) attribute in the application configuration file. | Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| restricted-permissions | [Restricted permissions](accesstoken-overview.md) required for your application.| String array | No | No | +| restricted-permissions | [Restricted permissions](accesstoken-overview.md) required for your application.| String array | No | No | ### Internal Structure of the debug-info Object The **debug-info** object contains debugging information of your application, mainly device management and control information. | Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No | -| device-ids | IDs of devices on which your application can be debugged.| String array | Optional| No | +| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No | +| device-ids | IDs of devices on which your application can be debugged.| String array | No | No | ## Modifying the HarmonyAppProvision Configuration File diff --git a/en/application-dev/security/userauth-guidelines.md b/en/application-dev/security/userauth-guidelines.md index 85a82669d954947eea30a5e0cd82cc036f84b018..2902e73fe80c57942023674bb174cac384a218e2 100644 --- a/en/application-dev/security/userauth-guidelines.md +++ b/en/application-dev/security/userauth-guidelines.md @@ -1,113 +1,239 @@ # User Authentication Development > ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
-> This development guide applies to the SDK of API Version 8 or later. +> This guide applies to the SDK for API version 9. ## When to Use -2D and 3D facial recognition used in identity authentication scenarios such as device unlocking, application login, and payment +User authentication supports facial recognition and fingerprint recognition and can be used in identity authentication scenarios such as device unlocking, application login, and payment. ## Available APIs -The userIAM_userAuth module provides methods for checking the support for user authentication, and performing and canceling authentication. You can perform authentication based on biometric features such as facial characteristics. For more details, see [API Reference](../reference/apis/js-apis-useriam-userauth.md). +The **userIAM_userAuth** module provides APIs for user authentication, including querying authentication capabilities, and initiating or canceling authentication. Users can use biometric feature information, such as facial and fingerprints, to perform authentications. For more details about the APIs, see [User Authentication](../reference/apis/js-apis-useriam-userauth.md). -Before performing authentication, check whether the device supports user authentication, including the authentication type and level. If user authentication is not supported, consider using another authentication type. The following table lists the APIs available for user authentication. +Before authentication, you must specify the [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8) and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to check whether the device supports the authentication capabilities. **Table 1** APIs of user authentication -| API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| getVersion() : number | Obtains the version information of an authentication object. | -| getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number | Checks whether the device supports the specified authentication type and level.| -| auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array | Performs user authentication. This method uses asynchronous callback to return the result. | -| cancelAuth(contextID : Uint8Array) : number | Cancels an authentication. | - -## How to Develop - -Before starting the development, make the following preparations: - -1. Add the ohos.permission.ACCESS_BIOMETRIC permission declaration to the application permission file. -2. Add **import userIAM_userAuth from '@ohos.userIAM.userAuth'** to the code file. - -The development procedure is as follows: - -1. Obtain an **Authenticator** singleton object. The sample code is as follows: - - ```js - let auth = new userIAM_userAuth.UserAuth(); - ``` - -2. (Optional) Obtain the version information of the authenticated object. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - let version = auth.getVersion(); - console.info("auth version = " + version); - ``` - -3. Check whether the device supports the authentication capabilities based on the specified authentication type and level. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - ``` - -4. Perform an authentication. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` - -5. Cancel the authentication. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - // Obtain contextId using auth(). - let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - console.info("auth onResult result = " + result); - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - console.info("auth onAcquireInfo module = " + module); - } - }); - let cancelCode = auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` +| API | Description | +| ---------- | ----------------------- | +| getVersion() : number | Obtains the version information of an authentication object. | +| getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void | Checks whether the device supports the specified authentication type and level.| +| getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel : AuthTrustLevel): AuthInstance | Obtains an **AuthInstance** instance for user authentication.| +| on(name : AuthEventKey, callback : AuthEvent) : void | Subscribes to the user authentication events of the specified type.| +| off(name : AuthEventKey) : void | Unsubscribes from the user authentication events of the specific type.| +| start: void | Starts user authentication. | +| cancel: void | Cancel this user authentication. | + +## Obtaining Authentication Object Version Information + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Use [getVersion](../reference/apis/js-apis-useriam-userauth.md#useriam_userauthgetversion9) to obtain the version information. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + // Obtain version information. + try { + let version = userIAM_userAuth.getVersion(); + console.info("auth version = " + version); + } catch (error) { + console.info("get version failed, error = " + error); + } + ``` + +## Checking Authentication Capabilities Supported by a Device + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8) and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8), and call [getAvailableStatus](../reference/apis/js-apis-useriam-userauth.md#useriam_userauthgetavailablestatus9) to check whether the current device supports the authentication capabilities. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + // Check whether the authentication capabilities are supported. + try { + userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + console.info("current auth trust level is supported"); + } catch (error) { + console.info("current auth trust level is not supported, error = " + error); + } + ``` + +## Performing Authentication and Subscribing to the Authentication Result + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the challenge, [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8), and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to obtain an authentication object. + +3. Use [on](../reference/apis/js-apis-useriam-userauth.md#on9) to subscribe to the authentication result. + +4. Use [start](../reference/apis/js-apis-useriam-userauth.md#start9) to initiate an authentication and return the authentication result through [callback](../reference/apis/js-apis-useriam-userauth.md#callback9). + +5. Use [off](../reference/apis/js-apis-useriam-userauth.md#off9) to unsubscribe from the authentication result. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + let authType = userIAM_userAuth.UserAuthType.FACE; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Subscribe to the authentication result. + try { + auth.on("result", { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + console.log("authV9 result " + result.result); + console.log("authV9 token " + result.token); + console.log("authV9 remainAttempts " + result.remainAttempts); + console.log("authV9 lockoutDuration " + result.lockoutDuration); + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + + // Unsubscribe from the authentication result. + try { + auth.off("result"); + console.info("cancel subscribe authentication event success"); + } catch (error) { + console.info("cancel subscribe authentication event failed, error = " + error); + } + ``` + +## Performing Authentication and Subscribing to Authentication Tip Information + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the challenge, [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8), and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to obtain an authentication object. + +3. Use [on](../reference/apis/js-apis-useriam-userauth.md#on9) to subscribe to the authentication tip information. + +4. Use [start](../reference/apis/js-apis-useriam-userauth.md#start9) to initiate an authentication and return the tip information through [callback](../reference/apis/js-apis-useriam-userauth.md#callback9). + +5. Use [off](../reference/apis/js-apis-useriam-userauth.md#off9) to unsubscribe from the authentication tip information. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + let authType = userIAM_userAuth.UserAuthType.FACE; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Subscribe to authentication tip information. + try { + auth.on("tip", { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // Do something. + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // Do something. + default: + // Do others. + } + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + + // Unsubscribe from authentication tip information. + try { + auth.off("tip"); + console.info("cancel subscribe tip information success"); + } catch (error) { + console.info("cancel subscribe tip information failed, error = " + error); + } + ``` + +## Canceling User Authentication + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the challenge, [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8), and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to obtain an authentication object. + +3. Use [start](../reference/apis/js-apis-useriam-userauth.md#start9) to initiate an authentication. + +4. Use [cancel](../reference/apis/js-apis-useriam-userauth.md#cancel9) to cancel this authentication. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + let authType = userIAM_userAuth.UserAuthType.FACE; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + + // Cancel the authentication. + try { + auth.cancel(); + console.info("cancel auth success"); + } catch (error) { + console.info("cancel auth failed, error = " + error); + } + ``` diff --git a/en/application-dev/task-management/Readme-EN.md b/en/application-dev/task-management/Readme-EN.md index efc153e1b229c56a83c630a98aee1cecf5c72cac..f4b1d6d548e5e739daf352ddf16a8df310a47d05 100644 --- a/en/application-dev/task-management/Readme-EN.md +++ b/en/application-dev/task-management/Readme-EN.md @@ -8,6 +8,6 @@ - [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md) - Agent-Powered Scheduled Reminder - - [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md) - - [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md) + - [Agent-Powered Reminder Overview](reminder-agent-overview.md) + - [Agent-Powered Reminder Development](reminder-agent-development.md) diff --git a/en/application-dev/task-management/background-agent-scheduled-reminder-guide.md b/en/application-dev/task-management/background-agent-scheduled-reminder-guide.md deleted file mode 100644 index ed220944dd102466ec190ca09d6066a8818acd3e..0000000000000000000000000000000000000000 --- a/en/application-dev/task-management/background-agent-scheduled-reminder-guide.md +++ /dev/null @@ -1,180 +0,0 @@ -# Agent-Powered Scheduled Reminder Development - -## When to Use - -You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. - - -## Available APIs - -**reminderAgentManager** encapsulates the APIs for publishing and canceling reminders. - -For details about the APIs, see [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md). - -**Table 1** Major APIs in reminderAgentManager - -| Name| Description| -| -------- | -------- | -| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | -| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| -| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application.| -| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application.| -| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder.| -| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type.| - -## How to Develop - -> **NOTE** -> -> 1. To publish a reminder through the reminder agent, your application must apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. ->2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8). -> 3. The reminder agent can be used only after being authorized by the user. - -1. Define a reminder agent. - -2. Publish the reminder agent. - -```ts -import reminderAgentManager from '@ohos.reminderAgentManager'; -import notification from '@ohos.notification'; - -// Sample code for defining a reminder agent for a countdown timer: -let timer : reminderAgentManager.ReminderRequestTimer = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10, - actionButton: [ - { - title: "close", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - } - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} - -// Sample code for defining a reminder agent for a calendar event: -let calendar : reminderAgentManager.ReminderRequestCalendar = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, - dateTime: { - year: 2050, - month: 7, - day: 30, - hour: 11, - minute: 14, - second: 30 - }, - repeatMonths: [1], - repeatDays: [1], - actionButton: [ - { - title: "close", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} - -// Sample code for defining a reminder agent for an alarm: -let alarm : reminderAgentManager.ReminderRequestAlarm = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, - hour: 11, - minute: 14, - daysOfWeek: [0], - actionButton: [ - { - title: "close", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} - -@Entry -@Component -struct Index { - @State message: string = 'test' - - publishReminder() { - try { - reminderAgentManager.publishReminder(timer).then(res => { - console.log("publishReminder promise reminderId:" + res); - }).catch(err => { - console.log("publishReminder err code:" + err.code + " message:" + err.message); - }) - } catch (error) { - console.log("publishReminder code:" + error.code + " message:" + error.message); - }; - } - - build() { - Row() { - Column() { - Text("Index") - .fontSize(50) - .fontWeight(FontWeight.Bold) - - Button() { Text('Countdown reminder agent').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // Sample code for publishing the reminder agent. - this.publishReminder(); - }) - - } - .width('100%') - } - .height('100%') - } -} -``` diff --git a/en/application-dev/task-management/background-agent-scheduled-reminder-overview.md b/en/application-dev/task-management/background-agent-scheduled-reminder-overview.md deleted file mode 100644 index 22c530571ad2770a279b9c94df998b6d773a5f1f..0000000000000000000000000000000000000000 --- a/en/application-dev/task-management/background-agent-scheduled-reminder-overview.md +++ /dev/null @@ -1,12 +0,0 @@ -# Agent-Powered Scheduled Reminder Overview - -According to the OpenHarmony background activity specifications, a third-party application will be suspended if it does not execute background tasks after switching to the background. In practice, an application may need to process certain work at specified moments, no matter what state it is in. For example, a shopping application needs to remind users of flash sale activities at some time points. Generally, a timer is used to achieve the preceding scenario. When the timer expires, the system starts the application to execute the task. However, some applications abuse the timer mechanism so they can be frequently waken up when running in the background. To avoid malicious background activities and meet service requirements of applications, OpenHarmony introduces the agent-powered scheduled reminder. -With the agent-powered scheduled reminder, the timing and pop-up notification functions of an application will be taken over by the reminder agent in the background, even when the application is suspended or exits. This prevents an application from being frequently woken up and helps reduce power consumption. - -## Notification Instance Types - -- **Countdown timers**: Applications can use this type to implement short-time timing notification services. - -- **Calendar events**: Applications can use this type to implement long-time notification services. - -- **Alarm clocks**: Applications can use this type to implement alarm-related services. diff --git a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md index 0b8ea31ca804f848d1e931b65a7e5f5812e656c2..61f1431ea4d26eb8579246b8ecec1f58fab56327 100644 --- a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md +++ b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md @@ -1,22 +1,22 @@ -## Efficiency Resource Request Development +# Efficiency Resource Request Development -### When to Use +## When to Use To further balance power consumption overhead of the system, privileged system applications can be suspended in the background as other applications. To ensure normal provisioning of important functions, efficiency resource APIs are provided for these applications so that they can execute special tasks and use specific system resources in the background. For example, if they want to receive common events when suspended, they can use the APIs to request the common event resources. To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions. -### Available APIs +## Available APIs **Table 1** Main APIs for efficiency resources -| API | Description | -| ---------------------------------------- | ---------------------------------------- | -| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | Requests efficiency resources.| -| resetAllEfficiencyResources():void | Releases efficiency resources. | +| API | Description | +| ---------------------------------------- | ---------- | +| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#efficiencyresourcesrequest)): boolean | Requests efficiency resources. | +| resetAllEfficiencyResources():void | Releases efficiency resources.| -### How to Develop +## How to Develop 1. When a privileged application in the background needs to use special resources, request the target resources from the system. @@ -51,5 +51,3 @@ console.info("the result of request is: " + res); // Release all efficiency resources. backgroundTaskManager.resetAllEfficiencyResources(); ``` - - \ No newline at end of file diff --git a/en/application-dev/task-management/figures/en-us_image_0000001416585578.png b/en/application-dev/task-management/figures/en-us_image_0000001416585578.png new file mode 100644 index 0000000000000000000000000000000000000000..7603dfb263fe088c0a71a99be541838566b53268 Binary files /dev/null and b/en/application-dev/task-management/figures/en-us_image_0000001416585578.png differ diff --git a/en/application-dev/task-management/reminder-agent-development.md b/en/application-dev/task-management/reminder-agent-development.md new file mode 100644 index 0000000000000000000000000000000000000000..c749a9f4cc9615e836e2163632390b8821e55072 --- /dev/null +++ b/en/application-dev/task-management/reminder-agent-development.md @@ -0,0 +1,181 @@ +# Agent-Powered Reminder Development + + +## Available APIs + +The agent-powered reminder feature provides APIs for publishing background reminders. You can call these APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. The APIs are encapsulated in the [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md) class. + +**Table 1** Major APIs in reminderAgentManager + +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | +| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.) | +| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application. | +| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application. | +| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder. | +| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type. | + + +## How to Develop + +1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. [Enable the notification feature](../notification/notification-enable.md). + +3. Import the modules. + + ```js + import reminderAgentManager from '@ohos.reminderAgentManager'; + import notificationManager from '@ohos.notificationManager'; + ``` + +4. Define a reminder agent. You can define the following types of reminder agents based on project requirements. + - Countdown timer + + ```js + let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // The reminder type is countdown timer. + triggerTimeInSeconds: 10, + actionButton: [ // Set the button type and title displayed in the reminder notification. The Close and Snooze types are supported, and the Snooze type must be used together with the snoozeTimes and timeInterval parameters. + { + title: 'close', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + } + ], + wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + maxScreenWantAgent: {// Information about the target ability that is automatically started when the specified reminder time arrives is displayed in full screen. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + title:'this is title', // Reminder title. + content:'this is content', // Reminder content. + expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires. + notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one. + slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. + } + ``` + - Calendar event + + ```js + let targetReminderAgent: reminderAgentManager.ReminderRequestCalendar = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, // The reminder type is calendar event. + dateTime: { // Reminder time. + year: 2023, + month: 7, + day: 30, + hour: 11, + minute: 14, + second: 30 + }, + repeatMonths: [1], // Month in which the reminder repeats. + repeatDays: [1], // Date on which the reminder repeats. + actionButton: [ // Set the button type and title displayed in the reminder notification. The Close and Snooze types are supported, and the Snooze type must be used together with the snoozeTimes and timeInterval parameters. + { + title: 'close', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: 'snooze', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + ringDuration: 5, // Ringing duration, in seconds. + snoozeTimes: 2, // Number of reminder snooze times. + timeInterval: 5, // Reminder snooze interval, in seconds. + title:'this is title', // Reminder title. + content:'this is content', // Reminder content. + expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires. + snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed. + notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one. + slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. + } + ``` + - Alarm clock + + ```js + let targetReminderAgent: reminderAgentManager.ReminderRequestAlarm = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, // The reminder type is alarm clock. + hour: 23, // Hour portion of the reminder time. + minute: 9, // Minute portion of the reminder time. + daysOfWeek: [2], // Days of a week when the reminder repeats.. + actionButton: [ // Set the button type and title displayed in the reminder notification. The Close and Snooze types are supported, and the Snooze type must be used together with the snoozeTimes and timeInterval parameters. + { + title: 'close', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: 'snooze', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + ringDuration: 5, // Ringing duration, in seconds. + snoozeTimes: 2, // Number of reminder snooze times. + timeInterval: 5, // Reminder snooze interval, in seconds. + title:'this is title', // Reminder title. + content:'this is content', // Reminder content. + expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires. + snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed. + notificationId: 99, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one. + slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. + } + ``` + +5. Publish the reminder agent. After the agent is published, your application can use the agent-powered reminder feature. + + ```js + try { + reminderAgentManager.publishReminder(targetReminderAgent).then(res => { + console.info('publishReminder promise reminderId: ' + res); + let reminderId: number = res; + // ... + }).catch(err => { + console.info('publishReminder err code: ' + err.code + ' message:' + err.message); + }) + } catch (error) { + console.info('publishReminder code: ' + error.code + ' message:' + error.message); + } + ``` + + The following figure shows the running effect of an alarm clock. + + ![en-us_image_0000001416585578](figures/en-us_image_0000001416585578.png) + +6. To delete a reminder task, call [reminderAgentManager.cancelReminder()](../reference/apis/js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder). + + ```js + let reminderId = 0; // The reminderId is obtained from the callback after the agent is published. + + try { + reminderAgentManager.cancelReminder(reminderId).then(() => { + console.log("cancelReminder promise"); + }).catch(err => { + console.log("promise err code: " + err.code + ", message:" + err.message); + }); + } catch (error) { + console.log("cancelReminder code: " + error.code + ", message: " + error.message); + }; + ``` + + + + \ No newline at end of file diff --git a/en/application-dev/task-management/reminder-agent-overview.md b/en/application-dev/task-management/reminder-agent-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6f0f4c5f99b60715e7c1a29841c9ca5aadf70cb8 --- /dev/null +++ b/en/application-dev/task-management/reminder-agent-overview.md @@ -0,0 +1,14 @@ +# Agent-Powered Reminder Overview + + +To deliver a better user experience, OpenHarmony 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. However, for some applications that are running in the background or have exited, notifications may need to be sent at a specified time. For example, a shopping application wants to remind users of flash sale activities at some time points. To meet these service requirements, OpenHarmony provides the agent-powered redminder feature. After an application switches to the background or exits, their timing and pop-up notification functions are taken over by the background agent. + + +OpenHarmony provides the following types of background agents: + + +- Countdown timers: Applications can use this type to implement short-time timing notification services. + +- Calendar events: Applications can use this type to implement long-time notification services. + +- Alarm clocks: Applications can use this type to implement alarm-related services. diff --git a/en/application-dev/tools/Readme-EN.md b/en/application-dev/tools/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..5dfe93a6a9584920a5da457ac61964dcb183a99c --- /dev/null +++ b/en/application-dev/tools/Readme-EN.md @@ -0,0 +1,9 @@ +# Debugging Tools + +- [Ability Assistant](aa-tool.md) +- [Bundle Manager](bm-tool.md) +- Packing and Unpacking Tools + - [Packaging Tool](packing-tool.md) + - [Unpacking Tool](unpacking-tool.md) +- [Common Event Manager](cem-tool.md) +- [Advanced Notification Manager](anm-tool.md) diff --git a/en/application-dev/tools/aa-tool.md b/en/application-dev/tools/aa-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..e03cdd52c6df142c13a06c918ae242c4115b323c --- /dev/null +++ b/en/application-dev/tools/aa-tool.md @@ -0,0 +1,119 @@ +# Ability Assistant + + +The Ability Assistant provides the application debugging and testing capabilities that enable you to start applications and test cases. With this tool, you can send commands (started with **aa**) in the hdc shell to perform various system operations, such as starting application components, forcibly stopping processes, and printing application component information. + + +- help + +Displays help information for the Ability Assistant. + +**Return value** + +Returns the help information. + +**Method** + + + ```bash + aa help + ``` + + +- start + +Starts an application component. The target component can be the PageAbility and ServiceAbility components of the FA model or the UIAbility and ServiceExtensionAbility components of the Stage model. The **visible** tag in the configuration file of the target component cannot be set to **false**. + + | Name| Description| + | -------- | -------- | + | -h/--help | Help information.| + | -d | Device ID. Optional.| + | -a | Ability name. Mandatory.| + | -b | Bundle name. Mandatory.| +| -D | Debugging mode. Optional.| + +**Return value** + +Returns "start ability successfully." if the ability is started; returns "error: failed to start ability." and the corresponding error information otherwise. + +**Method** + + + ```bash + aa start [-d ] -a -b [-D] +``` + +- stop-service + +Stops a ServiceAbility. + + | Name| Description| + | -------- | -------- | + | -h/--help | Help information.| + | -d | Device ID. Optional.| + | -a | Ability name. Mandatory.| +| -b | Bundle name. Mandatory.| + +**Return value** + +Returns "stop service ability successfully." if the ServiceAbility is stopped; returns "error: failed to stop service ability." otherwise. + +**Method** + + + ```bash + aa stop-service [-d ] -a -b +``` + +- dump + + Prints information about an application component. + + | Name| Level-2 Parameter| Description| + | -------- | -------- | -------- | + | -h/--help | - | Help information.| + | -a/--all | - | Application component information in all missions.| + | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Mission stack information.
The following values are available for **type**:
- NORMAL
- DEFAULT_STANDARD
- DEFAULT_SINGLE
- LAUNCHER | + | -e/--extension | elementName | Extended component information.| + | -u/--userId | UserId | Mission stack information of a specified user ID. This parameter must be used together with other parameters. Example commands: **aa dump -a -u 100** and **aa dump -d -u 100**.| + | -d/--data | - | DataAbility information.| +| -i/--ability | AbilityRecord ID | Detailed information about an application component.| + | -c/--client | - | Detailed information about an application component. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| + + **Method** + + + ```bash +aa dump -a + ``` + + ![aa-dump-a](figures/aa-dump-a.png) + + + ```bash +aa dump -l + ``` + + ![aa-dump-l](figures/aa-dump-l.png) + + + ```bash +aa dump -i 12 + ``` + + ![aa-dump-i](figures/aa-dump-i.png) + +- force-stop + +Forcibly stops a process based on the bundle name. + +**Return value** + +Returns "force stop process successfully." if the process is forcibly stopped; returns "error: failed to force stop process." otherwise. + +**Method** + + + ```bash + aa force-stop + ``` diff --git a/en/application-dev/tools/anm-tool.md b/en/application-dev/tools/anm-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..5a738bc22ff538676158bb3da32aacf9b507097c --- /dev/null +++ b/en/application-dev/tools/anm-tool.md @@ -0,0 +1,71 @@ +# Advanced Notification Manager + +The Advanced Notification Manager provides the notification debugging and testing capabilities that enable you to print notifications and set notification parameters. With this tool, you can send commands (started with **anm**) in the hdc shell to perform various system operations, such as printing notification details, setting the number of cached notifications, and enabling the notification capability. + +### help + +* **Function** + + Prints help information. + +* **Method** + + ```bash + anm help + ``` + +### dump + +* **Function** + + Prints information about notifications. + +* **Method** + + ```bash + anm dump [] + ``` + + The table below describes the available options. + + | Name | Description | + | ---------------- | ---------------------------------- | + | -A/--active | Information about all active notifications. | + | -R/--recent | Information about recent notifications. | + | -D/--distributed | Information about distributed notifications from other devices. | + | -b/--bundle | Bundle name. Optional.| + | -u/--user-id | User ID. Optional. | + | -h/--help | Help information. | + +* **Example**: Print information about active notifications. + + ```bash + anm dump -A + ``` + ![anm-dump-A](figures/anm-dump-A.png) + +### Setting + +* **Function** + + Sets notification parameters. + +* **Method** + + ```bash + anm setting [] + ``` + + The table below describes the available options. + + | Name | Description | + | ------------------------ | ------------------------------------ | + | -c/--recent-count | Maximum number of recent notifications stored in the memory.| + | -e/--enable-notification | Whether to enable the notification capability. | + | -h/--help | Help information. | + +* **Example**: Set the maximum number of recent notifications stored in the memory to 100. + + ```bash + anm setting -c 100 + ``` diff --git a/en/application-dev/tools/bm-tool.md b/en/application-dev/tools/bm-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..879a2f123b2e2ea9a1dc8ce30c38da81458dc2e3 --- /dev/null +++ b/en/application-dev/tools/bm-tool.md @@ -0,0 +1,275 @@ +# Bundle Manager + + +The Bundle Manager provides the bundle debugging and testing capabilities that enable you to install, uninstall, update, and query a bundle (application). With this tool, you can send commands (started with **bm**) in the hdc shell to perform various system operations, such as installing and uninstalling a bundle and querying bundle information. + +**Table 1** bm commands + +| Name| Description| +| -------- | -------- | +| help | Displays the commands supported by the Bundle Manager tool.| +| install | Installs a bundle.| +| uninstall | Uninstalls a bundle.| +| dump | Queries bundle information.| +| clean | Clears the cache and data of a bundle.| +| enable | Enables a bundle. A bundle can be used after being enabled.| +| disable | Disables a bundle. A bundle cannot be used after being disabled.| +| get | Obtains the UDID of a device.| +| quickfix | Performs patch-related operations, such as installing or querying a patch.| + + +## Help Command + +**Table 2** Help command + +| Name| Description| +| -------- | -------- | +| bm help | Displays the commands supported by the bm tool.| + +Example + + +```bash +# Display the help information. +bm help +``` + + +## Installation Command + +```bash +bm install [-h] [-p path] [-u userId] [-r] [-w waitting-time] +``` + +**Table 3** Installation command parameters + +| Name| Mandatory| Description| +| -------- | -------- | -------- | +| -h | No| Used to display the parameters supported by the **install** command. By default, the help information is displayed.| +| -p | Yes| Path of the HAP to install. You can specify a path to install one or more HAPs at the same time.| +| -u | No| User whose HAP is to be installed. By default, the current user's HAP is installed.| +| -r | No| Whether to install the HAP in overwrite mode. By default, the HAP is installed in overwrite mode.| +| -w | No| Time that the Bundle Manager tool waits before installing the HAP. The minimum waiting time is 5s, and the maximum waiting time is 600s. The default waiting time is 5s.| + + +Example + +```bash +bm install -p /data/app/ohosapp.hap -u 100 -w 5s -r +// The execution result is as follows: +install bundle successfully. +``` + + +## Uninstall Command + +```bash +bm uninstall [-h help] [-n bundleName] [-m moduleName] [-u userId] [-k] +``` + +**Table 4** Uninstall command parameters + +| Name| Mandatory| Description| +| -------- | -------- | -------- | +| -h | No| Used to display the parameters supported by the **uninstall** command. By default, the help information is displayed.| +| -n | Yes| Name of the bundle to uninstall.| +| -m | No| Module of the bundle to uninstall. By default, all modules are uninstalled.| +| -u | No| User whose bundle is to be uninstalled. By default, the current user's bundle is uninstalled.| +| -k | No| Whether the application data is retained when the bundle is uninstalled. By default, the application data is deleted along the uninstall.| + + +Example + +```bash +bm uninstall -n com.ohos.app -m com.ohos.app.EntryAbility -u 100 -k +// The execution result is as follows: +uninstall bundle successfully. +``` + + +## Dump Command + +```bash +bm dump [-h help] [-a] [-n bundleName] [-s shortcutInfo] [-u userId] [-d deviceId] +``` + + +If **-u** is not specified, the command applies to all users. + +**Table 5** Dump command parameters + +| Name| Mandatory| Description| +| -------- | -------- | -------- | +| -h | No| Used to display the parameters supported by the **dump** command. By default, the help information is displayed.| +| -a | Yes| Used to display all bundles installed in the system.| +| -n | Yes| Used to display the details of a bundle.| +| -s | Yes| Used to display the shortcut information of a bundle.| +| -d | No| Used to display the bundle information on a given device. By default, the bundle information on the current device is queried.| +| -u | No| Used to display the bundle information for a given user. By default, the bundle information of the current user is queried.| + + +Example + +```bash +# Display the names of all bundles installed in the system. +bm dump -a +# Display the details of a bundle. +bm dump -n com.ohos.app -u 100 +# Display the shortcut information of a bundle. +bm dump -s com.ohos.app -u 100 +# Display cross-device bundle information. +bm dump -n com.ohos.app -d xxxxx +``` + + +## Clean Command + +```bash +bm clean [-h] [-c] [-n bundleName] [-d] [-u userId] +``` + + +If **-u** is not specified, the command applies to all active users. + +**Table 6** Clean command parameters + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **clean** command.| +| -c -n | Used to clear the cache data of a bundle.| +| -d -n | Used to clear the data directory of a bundle.| +| -u | Used to clear the cache data of a bundle for a given user.| + + +Example + +```bash +# Clear the cache data of a bundle. +bm clean -c -n com.ohos.app -u 100 +// The execution result is as follows: +clean bundle cache files successfully. +# Clear the user data of a bundle. +bm clean -d -n com.ohos.app -u 100 +// The execution result is as follows: +clean bundle data files successfully. +``` + + +## Enable Command + +```bash +bm enable [-h] [-n bundleName] [-a abilityName] [-u userId] +``` + + +If **-u** is not specified, the command applies to all active users. + +**Table 7** Enable command parameters + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **enable** command.| +| -n | Used to enable a bundle.| +| -a | Used to enable an ability with a specified bundle name.| +| -u | Used to enable a bundle for a given user.| + + +Example + +```bash +# Enable a bundle. +bm enable -n com.ohos.app -a com.ohos.app.EntryAbility -u 100 +// The execution result is as follows: +enable bundle successfully. +``` + + +## Disable Command + +```bash +bm disable [-h] [-n bundleName] [-a abilityName] [-u userId] +``` + + +If **-u** is not specified, the command applies to all active users. + +**Table 8** Disabled command parameters + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **disable** command.| +| -n | Used to disable a bundle.| +| -a | Used to disable an ability with a specified bundle name.| +| -u | Used to disable a bundle for a given user.| + +Example + +```bash +# Disable a bundle. +bm disable -n com.ohos.app -a com.ohos.app.EntryAbility -u 100 +// The execution result is as follows: +disable bundle successfully. +``` + + +## Obtaining UDID + +```bash +bm get [-h] [-u] +``` + +**Table 9** Parameters used in the command for obtaining the UDID + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **get** command.| +| -u | Used to obtain the UDID of a device.| + + +Example + +```bash +# Obtain the UDID of a device. +bm get -u +// The execution result is as follows: +udid of current device is : +23CADE0C +``` + + +## Quick Fix + +```bash +bm quickfix [-h] [-a -f filePath] [-q -b bundleName] +``` + +**Table 10** Parameters used in the command for quick fix + +| Name| Description| +| -------- | -------- | +| -h | Used to display the commands supported by **quickfix**.| +| -a -f | Used to run the quick fix patch installation command. **file-path** corresponds to the hqf file. You can pass in one or more hqf files or the directory where the hqf file is located.| +| -q -b | Used to display the patch information based on the bundle name. **bundle-name** indicates the bundle name.| + + +Example + +```bash +# Display patch package information by the bundle name. +bm quickfix -q -b com.ohos.app +// The execution result is as follows: +// Information as follows: +// ApplicationQuickFixInfo: +// bundle name: com.ohos.app +// bundle version code: xxx +// bundle version name: xxx +// patch version code: x +// patch version name: +// cpu abi: +// native library path: +// type: +# Patch installation in the quick fix: +bm quickfix -a -f /data/app/ +// The execution result is as follows: +apply quickfix succeed. +``` diff --git a/en/application-dev/tools/cem-tool.md b/en/application-dev/tools/cem-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..beaf1a86e38b11508d5551a48e018cf98e7e7a6e --- /dev/null +++ b/en/application-dev/tools/cem-tool.md @@ -0,0 +1,85 @@ +# Common Event Manager + +The Common Event Manager provides the common event debugging and testing capabilities that enable you to print common event information and publish common events. With this tool, you can send commands (started with **cem**) in the hdc shell to perform various system operations, such as printing all common event subscribers, sent common events, and recipients, as well as publishing common events. + +## Commands + +### help + +* Function + + Prints help information. + +* Method + + ``` + cem help + ``` + +### publish + +* Function + + Publishes a common event. + +* Method + + ``` + cem publish [] + ``` + + The table below describes the available options. + + | Name | Description | + | ------------ | ------------------------------------------ | + | -e/--event | Name of the common event to publish. Mandatory. | + | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published.| + | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | + | -c/--code | Result code of the common event. Optional. | + | -d/--data | Data carried in the common event. Optional. | + | -h/--help | Help information. | + +* Example + + ```bash + # Publish a common event named testevent. + cem publish --event "testevent" + ``` + + ![cem-publish-event](figures/cem-publish-event.png) + + ```bash + # Publish a sticky, ordered common event named testevent. The result code of the event is 100 and the data carried is this is data. + cem publish -e "testevent" -s -o -c 100 -d "this is data" + ``` + + ![cem-publish-all](figures/cem-publish-all.png) + +### dump + +* Function + + Displays information about common events. + +* Method + + ``` + cem dump [] + ``` + + The table below describes the available options. + + | Name | Description | + | ---------- | -------------------------------------------- | + | -a/--all | Information about all common events that have been sent since system startup.| + | -e/--event | Information about a specific event. | + | -h/--help | Help information. | + +* Example + + ```bash + # Display details of a common event named testevent. + cem dump -e "testevent" + ``` + + ![cem-dump-e](figures/cem-dump-e.png) diff --git a/en/application-dev/tools/figures/aa-dump-a.png b/en/application-dev/tools/figures/aa-dump-a.png new file mode 100644 index 0000000000000000000000000000000000000000..ae8d41f65f68d73895be5bbbb539c0d220b2a9a5 Binary files /dev/null and b/en/application-dev/tools/figures/aa-dump-a.png differ diff --git a/en/application-dev/tools/figures/aa-dump-i.png b/en/application-dev/tools/figures/aa-dump-i.png new file mode 100644 index 0000000000000000000000000000000000000000..12998c5ba3e7d667d1147b6e825f8d110d5c5c5e Binary files /dev/null and b/en/application-dev/tools/figures/aa-dump-i.png differ diff --git a/en/application-dev/tools/figures/aa-dump-l.png b/en/application-dev/tools/figures/aa-dump-l.png new file mode 100644 index 0000000000000000000000000000000000000000..a6797eef284990e3fa25e71562ac8afbddf0821d Binary files /dev/null and b/en/application-dev/tools/figures/aa-dump-l.png differ diff --git a/en/application-dev/tools/figures/anm-dump-A.png b/en/application-dev/tools/figures/anm-dump-A.png new file mode 100644 index 0000000000000000000000000000000000000000..368e6f2d810976486e786a4c8f0603a87ad48540 Binary files /dev/null and b/en/application-dev/tools/figures/anm-dump-A.png differ diff --git a/en/application-dev/tools/figures/cem-dump-e.png b/en/application-dev/tools/figures/cem-dump-e.png new file mode 100644 index 0000000000000000000000000000000000000000..c2422ba0e51011174c333985ad7647f170e0f126 Binary files /dev/null and b/en/application-dev/tools/figures/cem-dump-e.png differ diff --git a/en/application-dev/tools/figures/cem-publish-all.png b/en/application-dev/tools/figures/cem-publish-all.png new file mode 100644 index 0000000000000000000000000000000000000000..99526e1f7245d101914354e2a89d5e97d710c27f Binary files /dev/null and b/en/application-dev/tools/figures/cem-publish-all.png differ diff --git a/en/application-dev/tools/figures/cem-publish-event.png b/en/application-dev/tools/figures/cem-publish-event.png new file mode 100644 index 0000000000000000000000000000000000000000..f0ca7e73093f1be72c743bd7c08467f11e2a0e05 Binary files /dev/null and b/en/application-dev/tools/figures/cem-publish-event.png differ diff --git a/en/application-dev/tools/packing-tool.md b/en/application-dev/tools/packing-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..36b5c7fdc295604d7bc46db5e01300e517514ade --- /dev/null +++ b/en/application-dev/tools/packing-tool.md @@ -0,0 +1,90 @@ +# Packaging Tool + + +The packaging tool is a commissioning tool provided by OpenHarmony. It can generate HAP files in command line mode, pack multiple HAP files into an App Pack, or pack multiple HAP files and App Packs into an App Pack. App Pack is the application package format required for releasing an application on AppGallery. + + +The **app_packing_tool.jar** package can be found in the OpenHarmony SDK downloaded locally. + + +- Packing folders into an HAP file + +The command in the stage model is as follows: + + + ```bash + java -jar app_packing_tool.jar --mode