You need to sign in or sign up before continuing.
提交 54218d5c 编写于 作者: 田雨 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into master

Signed-off-by: N田雨 <tianyu55@huawei.com>
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
- ExtensionAbility Component - ExtensionAbility Component
- [ExtensionAbility Component Overview](extensionability-overview.md) - [ExtensionAbility Component Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md)
- [AccessibilityExtensionAbility](accessibilityextensionability.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md)
- [InputMethodExtensionAbility](inputmethodextentionability.md) - [InputMethodExtensionAbility](inputmethodextentionability.md)
...@@ -37,9 +36,9 @@ ...@@ -37,9 +36,9 @@
- [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md) - [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md)
- Widget Event Development - Widget Event Development
- [Widget Event Capability Overview](arkts-ui-widget-event-overview.md) - [Widget Event Capability Overview](arkts-ui-widget-event-overview.md)
- [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md)
- [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md) - [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md)
- [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md) - [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md)
- [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md)
- Widget Data Interaction - Widget Data Interaction
- [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md) - [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md)
- [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md) - [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md)
...@@ -62,8 +61,8 @@ ...@@ -62,8 +61,8 @@
- [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md) - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.md)
- [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md) - [Multi-device Collaboration (for System Applications Only)](hop-multi-device-collaboration.md)
- [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md) - [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md)
- IPC - Process Model
- [Process Model](process-model-stage.md) - [Process Model Overview](process-model-stage.md)
- Common Events - Common Events
- [Introduction to Common Events](common-event-overview.md) - [Introduction to Common Events](common-event-overview.md)
- Common Event Subscription - Common Event Subscription
...@@ -74,13 +73,13 @@ ...@@ -74,13 +73,13 @@
- [Publishing Common Events](common-event-publish.md) - [Publishing Common Events](common-event-publish.md)
- [Removing Sticky Common Events](common-event-remove-sticky.md) - [Removing Sticky Common Events](common-event-remove-sticky.md)
- [Background Services](background-services.md) - [Background Services](background-services.md)
- Inter-Thread Communication - Thread Model
- [Thread Model](thread-model-stage.md) - [Thread Model Overview](thread-model-stage.md)
- [Using Emitter for Inter-Thread Communication](itc-with-emitter.md) - [Using Emitter for Inter-Thread Communication](itc-with-emitter.md)
- [Using Worker for Inter-Thread Communication](itc-with-worker.md) - [Using Worker for Inter-Thread Communication](itc-with-worker.md)
- Mission Management - Mission Management
- [Mission Management Scenarios](mission-management-overview.md) - [Mission Management Scenarios](mission-management-overview.md)
- [Mission Management and Launch Type](mission-management-launch-type.md) - [Mission and Launch Type](mission-management-launch-type.md)
- [Page Stack and MissionList](page-mission-stack.md) - [Page Stack and MissionList](page-mission-stack.md)
- [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md)
- [Application Configuration File](config-file-stage.md) - [Application Configuration File](config-file-stage.md)
...@@ -120,12 +119,12 @@ ...@@ -120,12 +119,12 @@
- [Context](application-context-fa.md) - [Context](application-context-fa.md)
- [Want](want-fa.md) - [Want](want-fa.md)
- [Component Startup Rules](component-startup-rules-fa.md) - [Component Startup Rules](component-startup-rules-fa.md)
- IPC - Process Model
- [Process Model](process-model-fa.md) - [Process Model Overview](process-model-fa.md)
- [Common Events](common-event-fa.md) - [Common Events](common-event-fa.md)
- [Background Services](rpc.md) - [Background Services](rpc.md)
- Inter-Thread Communication - Thread Model
- [Thread Model](thread-model-fa.md) - [Thread Model Overview](thread-model-fa.md)
- [Inter-Thread Communication](itc-fa-overview.md) - [Inter-Thread Communication](itc-fa-overview.md)
- [Mission Management](mission-management-fa.md) - [Mission Management](mission-management-fa.md)
- [Application Configuration File](config-file-fa.md) - [Application Configuration File](config-file-fa.md)
......
# DataShareExtensionAbility (for System Applications Only)
DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [Cross-Application Data Sharing Overview](../database/share-device-data-across-apps-overview.md).
# Mission Management and Launch Type # Mission and Launch Type
One UIAbility instance corresponds to one mission. The number of UIAbility instances is related to the UIAbility launch type, specified by **launchType**, which is configured in the **config.json** file in the FA model and the [module.json5](../quick-start/module-configuration-file.md) file in the stage model. One UIAbility instance corresponds to one mission. The number of UIAbility instances is related to the UIAbility launch type, specified by **launchType**, which is configured in the **config.json** file in the FA model and the [module.json5](../quick-start/module-configuration-file.md) file in the stage model.
...@@ -11,13 +11,13 @@ The following describes how the mission list manager manages the UIAbility insta ...@@ -11,13 +11,13 @@ The following describes how the mission list manager manages the UIAbility insta
![mission-and-singleton](figures/mission-and-singleton.png) ![mission-and-singleton](figures/mission-and-singleton.png)
- **multiton**: Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a **UIAbility** instance is created in the application process. - **multiton**: Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a UIAbility instance is created in the application process.
**Figure 2** Missions and multiton mode **Figure 2** Missions and multiton mode
![mission-and-multiton](figures/mission-and-multiton.png) ![mission-and-multiton](figures/mission-and-multiton.png)
- **specified**: The ([onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)) method of [AbilityStage](abilitystage.md) determines whether to create an instance. - **specified**: The ([onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)) method of [AbilityStage](abilitystage.md) determines whether to create a UIAbility instance.
**Figure 3** Missions and specified mode **Figure 3** Missions and specified mode
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
Before getting started with the development of mission management, be familiar with the following concepts related to mission management: Before getting started with the development of mission management, be familiar with the following concepts related to mission management:
- AbilityRecord: minimum unit for the system service to manage a UIAbility instance. It corresponds to a UIAbility component instance of an application. - AbilityRecord: minimum unit for the system service to manage a UIAbility instance. It corresponds to a UIAbility component instance of an application. A maximum of 512 UIAbility instances can be managed on the system service side.
- MissionRecord: minimum unit for mission management. One MissionRecord has only one AbilityRecord. In other words, a UIAbility component instance corresponds to a mission. - MissionRecord: minimum unit for mission management. One MissionRecord has only one AbilityRecord. In other words, a UIAbility component instance corresponds to a mission.
...@@ -30,9 +30,9 @@ Missions are managed by system applications (such as home screen), rather than t ...@@ -30,9 +30,9 @@ Missions are managed by system applications (such as home screen), rather than t
A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created. A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created.
To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. 2. You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions.
```ts ```ts
import missionManager from '@ohos.app.ability.missionManager' import missionManager from '@ohos.app.ability.missionManager'
......
# Process Model (FA Model) # Process Model Overview (FA Model)
The OpenHarmony process model is shown below. The OpenHarmony process model is shown below.
......
# Process Model (Stage Model) # Process Model Overview (Stage Model)
The OpenHarmony process model is shown below. The OpenHarmony process model is shown below.
......
# Thread Model (FA Model) # Thread Model Overview (FA Model)
There are three types of threads in the FA model: There are three types of threads in the FA model:
- Main thread - Main thread
Manages other threads. Manages other threads.
- Ability thread - Ability thread
- One ability thread for each ability. - One ability thread for each ability.
...@@ -19,10 +17,8 @@ Manages other threads. ...@@ -19,10 +17,8 @@ Manages other threads.
Performs time-consuming operations Performs time-consuming operations
Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks.
> **NOTE** > **NOTE**
> >
> The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread. > The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread.
# Thread Model (Stage Model) # Thread Model Overview (Stage Model)
For an OpenHarmony application, each process has a main thread to provide the following functionalities: For an OpenHarmony application, each process has a main thread to provide the following functionalities:
......
...@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing ...@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing
The file URIs are in the following format: The file URIs are in the following format:
file://&lt;bundleName&gt;/&lt;path&gt;/\#networkid=&lt;networkid&gt; file://&lt;bundleName&gt;/&lt;path&gt;
- **file**: indicates a file URI. - **file**: indicates a file URI.
...@@ -20,8 +20,6 @@ The file URIs are in the following format: ...@@ -20,8 +20,6 @@ The file URIs are in the following format:
- *path*: specifies the application sandbox path of the file. - *path*: specifies the application sandbox path of the file.
- *networkid* (optional): specifies the device to which the file belongs in a distributed file system. Leave this parameter unspecified if the file location does not need to be set.
## Sharing a File with Another Application ## Sharing a File with Another Application
Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path). Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path).
......
...@@ -18,8 +18,6 @@ ...@@ -18,8 +18,6 @@
- [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](js-apis-app-form-formExtensionAbility.md) - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](js-apis-app-form-formExtensionAbility.md)
- [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md)
- [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md)
- Stage Model (To Be Deprecated Soon)
- [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md)
- FA Model - FA Model
- [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md)
- [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md) - [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md)
...@@ -39,10 +37,12 @@ ...@@ -39,10 +37,12 @@
- [@ohos.app.ability.Want (Want)](js-apis-app-ability-want.md) - [@ohos.app.ability.Want (Want)](js-apis-app-ability-want.md)
- [@ohos.app.ability.wantAgent (WantAgent)](js-apis-app-ability-wantAgent.md) - [@ohos.app.ability.wantAgent (WantAgent)](js-apis-app-ability-wantAgent.md)
- [@ohos.app.ability.wantConstant (wantConstant)](js-apis-app-ability-wantConstant.md) - [@ohos.app.ability.wantConstant (wantConstant)](js-apis-app-ability-wantConstant.md)
- [@ohos.app.businessAbilityRouter (Business Ability Router)](js-apis-businessAbilityRouter.md)
- [@ohos.app.form.formBindingData (formBindingData)](js-apis-app-form-formBindingData.md) - [@ohos.app.form.formBindingData (formBindingData)](js-apis-app-form-formBindingData.md)
- [@ohos.app.form.formHost (FormHost)](js-apis-app-form-formHost.md) - [@ohos.app.form.formHost (FormHost)](js-apis-app-form-formHost.md)
- [@ohos.app.form.formInfo (FormInfo)](js-apis-app-form-formInfo.md) - [@ohos.app.form.formInfo (FormInfo)](js-apis-app-form-formInfo.md)
- [@ohos.app.form.formProvider (FormProvider)](js-apis-app-form-formProvider.md) - [@ohos.app.form.formProvider (FormProvider)](js-apis-app-form-formProvider.md)
- [@ohos.application.uriPermissionManager (URI Permission Management)](js-apis-uripermissionmanager.md)
- Both Models (To Be Deprecated Soon) - Both Models (To Be Deprecated Soon)
- [@ohos.ability.dataUriUtils (DataUriUtils)](js-apis-ability-dataUriUtils.md) - [@ohos.ability.dataUriUtils (DataUriUtils)](js-apis-ability-dataUriUtils.md)
- [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md) - [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md)
...@@ -139,6 +139,10 @@ ...@@ -139,6 +139,10 @@
- [NotificationSlot](js-apis-inner-notification-notificationSlot.md) - [NotificationSlot](js-apis-inner-notification-notificationSlot.md)
- [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md) - [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md)
- [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) - [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md)
- Common Events
- [Common Events of the Bundle Management Subsystem](common_event/commonEvent-bundleManager.md)
- [Common Events of the Notification Service](common_event/commonEvent-ans.md)
- [Common Events of the Telephony Subsystem](common_event/commonEvent-telephony.md)
- Bundle Management - Bundle Management
- [@ohos.bundle.appControl (appControl)](js-apis-appControl.md) - [@ohos.bundle.appControl (appControl)](js-apis-appControl.md)
- [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md) - [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md)
...@@ -148,6 +152,7 @@ ...@@ -148,6 +152,7 @@
- [@ohos.bundle.freeInstall (freeInstall)](js-apis-freeInstall.md) - [@ohos.bundle.freeInstall (freeInstall)](js-apis-freeInstall.md)
- [@ohos.bundle.installer (installer)](js-apis-installer.md) - [@ohos.bundle.installer (installer)](js-apis-installer.md)
- [@ohos.bundle.launcherBundleManager (launcherBundleManager)](js-apis-launcherBundleManager.md) - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](js-apis-launcherBundleManager.md)
- [@ohos.bundle.overlay (overlay)](js-apis-overlay.md)
- [@ohos.zlib (Zip)](js-apis-zlib.md) - [@ohos.zlib (Zip)](js-apis-zlib.md)
- bundleManager - bundleManager
- [abilityInfo](js-apis-bundleManager-abilityInfo.md) - [abilityInfo](js-apis-bundleManager-abilityInfo.md)
...@@ -155,18 +160,22 @@ ...@@ -155,18 +160,22 @@
- [AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md) - [AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md)
- [bundleInfo](js-apis-bundleManager-bundleInfo.md) - [bundleInfo](js-apis-bundleManager-bundleInfo.md)
- [BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md) - [BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md)
- [BusinessAbilityInfo](js-apis-bundleManager-businessAbilityInfo.md)
- [dispatchInfo](js-apis-bundleManager-dispatchInfo.md) - [dispatchInfo](js-apis-bundleManager-dispatchInfo.md)
- [elementName](js-apis-bundleManager-elementName.md) - [elementName](js-apis-bundleManager-elementName.md)
- [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) - [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)
- [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)
- [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)
- [metadata](js-apis-bundleManager-metadata.md) - [metadata](js-apis-bundleManager-metadata.md)
- [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md)
- [permissionDef](js-apis-bundleManager-permissionDef.md) - [permissionDef](js-apis-bundleManager-permissionDef.md)
- [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)
- [SharedBundleInfo](js-apis-bundleManager-sharedBundleInfo.md)
- [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md)
- UI Page - UI Page
- [@ohos.animator (Animator)](js-apis-animator.md) - [@ohos.animator (Animator)](js-apis-animator.md)
- [@ohos.arkui.componentSnapshot (Component Snapshot)](js-apis-arkui-componentSnapshot.md)
- [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md)
- [@ohos.curves (Interpolation Calculation)](js-apis-curve.md) - [@ohos.curves (Interpolation Calculation)](js-apis-curve.md)
- [@ohos.matrix4 (Matrix Transformation)](js-apis-matrix4.md) - [@ohos.matrix4 (Matrix Transformation)](js-apis-matrix4.md)
...@@ -264,7 +273,7 @@ ...@@ -264,7 +273,7 @@
- [@ohos.net.connection (Network Connection Management)](js-apis-net-connection.md) - [@ohos.net.connection (Network Connection Management)](js-apis-net-connection.md)
- [@ohos.net.ethernet (Ethernet Connection Management)](js-apis-net-ethernet.md) - [@ohos.net.ethernet (Ethernet Connection Management)](js-apis-net-ethernet.md)
- [@ohos.net.http (Data Request)](js-apis-http.md) - [@ohos.net.http (Data Request)](js-apis-http.md)
- [@ohos.net.policy (Network Policy Management)](js-apis-net-policy.md) - [@ohos.net.mdns (mDNS Management)](js-apis-net-mdns.md)
- [@ohos.net.sharing (Network Sharing)](js-apis-net-sharing.md) - [@ohos.net.sharing (Network Sharing)](js-apis-net-sharing.md)
- [@ohos.net.socket (Socket Connection)](js-apis-socket.md) - [@ohos.net.socket (Socket Connection)](js-apis-socket.md)
- [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md) - [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md)
...@@ -449,4 +458,4 @@ ...@@ -449,4 +458,4 @@
- [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)
- [shortcutInfo](js-apis-bundle-ShortcutInfo.md) - [shortcutInfo](js-apis-bundle-ShortcutInfo.md)
- data/rdb - data/rdb
- [resultSet (Result Set)](js-apis-data-resultset.md) - [resultSet](js-apis-data-resultset.md)
\ No newline at end of file \ No newline at end of file
...@@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability'; ...@@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability';
| Name | Type | Description | | Name | Type | Description |
| ----------- | -------------------- | ------------------------------------------------------------ | | ----------- | -------------------- | ------------------------------------------------------------ |
| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Level-2 module **DataAbilityHelper**. | | DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Level-2 module **DataAbilityHelper**. |
| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | Level-2 module **PacMap**.| | PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Level-2 module **PacMap**.|
| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | Level-2 module **DataAbilityOperation**.| | DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | Level-2 module **DataAbilityOperation**.|
| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | Level-2 module **DataAbilityResult**.| | DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | Level-2 module **DataAbilityResult**.|
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.| | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.|
......
# @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry) # @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry)
**AbilityDelegatorRegistry**, a module of the [Test Framework](../../ability-deprecated/ability-delegator.md), is used to obtain [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) and [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) objects. **AbilityDelegator** provides APIs for creating **AbilityMonitor** objects, which can be used to listen for ability lifecycle changes. **AbilityDelegatorArgs** provides APIs for obtaining test parameters. **AbilityDelegatorRegistry**, a module of the [arkXtest User Guide](../../application-test/arkxtest-guidelines.md), is used to obtain [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) and [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) objects. **AbilityDelegator** provides APIs for creating **AbilityMonitor** objects, which can be used to listen for ability lifecycle changes. **AbilityDelegatorArgs** provides APIs for obtaining test parameters.
> **NOTE** > **NOTE**
> >
......
...@@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common'; ...@@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common';
| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.| | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.|
| ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Level-2 module **ServiceExtensionContext**.| | ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Level-2 module **ServiceExtensionContext**.|
| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | Level-2 module **EventHub**.| | EventHub | [EventHub](js-apis-inner-application-eventHub.md) | Level-2 module **EventHub**.|
| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | Level-2 module **PacMap**.| | PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Level-2 module **PacMap**.|
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.| | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.|
| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.| | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.|
......
...@@ -130,6 +130,6 @@ import Want from '@ohos.application.Want'; ...@@ -130,6 +130,6 @@ import Want from '@ohos.application.Want';
}); });
``` ```
- For more details and examples, see [Want](../../application-models/want-overview.md). - For more details and examples, see [Application Model](../../application-models/application-model-composition.md).
<!--no_check--> <!--no_check-->
...@@ -81,7 +81,7 @@ Unsubscribes from bundle installation, uninstall, and update events. ...@@ -81,7 +81,7 @@ Unsubscribes from bundle installation, uninstall, and update events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------------------------- | -------- | ---- | ---------------------------------------------------------- | | ---------------------------- | -------- | ---- | ---------------------------------------------------------- |
| type| BundleChangedEvent| Yes | Type of the event to unsubscribe from. | | type| BundleChangedEvent| Yes | Type of the event to unsubscribe from. |
| callback | callback\<BundleChangedInfo>| No | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| | callback | callback\<BundleChangedInfo>| No | Callback used for the unsubscription. By default, no value is passed, and all callbacks of the current event are unsubscribed from.|
**Example** **Example**
......
...@@ -232,7 +232,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -232,7 +232,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message | | ID| Error Message |
| -------- | ----------------------------------------- | | -------- | ----------------------------------------- |
| 17700004 | The specified user ID is not found. |
| 17700023 | The specified default app does not exist. | | 17700023 | The specified default app does not exist. |
| 17700025 | The specified type is invalid. | | 17700025 | The specified type is invalid. |
...@@ -415,7 +414,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -415,7 +414,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message | | ID| Error Message |
| -------- | ---------------------------------------------- | | -------- | ---------------------------------------------- |
| 17700004 | The specified user ID is not found. |
| 17700025 | The specified type is invalid. | | 17700025 | The specified type is invalid. |
| 17700028 | The specified ability does not match the type. | | 17700028 | The specified ability does not match the type. |
...@@ -574,7 +572,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -574,7 +572,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message | | ID| Error Message |
| -------- | ----------------------------------- | | -------- | ----------------------------------- |
| 17700004 | The specified user ID is not found. |
| 17700025 | The specified type is invalid. | | 17700025 | The specified type is invalid. |
**Example** **Example**
......
...@@ -3,10 +3,8 @@ ...@@ -3,10 +3,8 @@
The **cloudSyncManager** module provides APIs for changing the cloud and device service status and notifying the data changes. The **cloudSyncManager** module provides APIs for changing the cloud and device service status and notifying the data changes.
> **NOTE** > **NOTE**
>
> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications. > - The APIs of this module are system APIs and cannot be called by third-party applications.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
...@@ -36,6 +34,15 @@ Changes the device-cloud file synchronization switch for an application. This AP ...@@ -36,6 +34,15 @@ Changes the device-cloud file synchronization switch for an application. This AP
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
**Example** **Example**
```js ```js
...@@ -65,6 +72,15 @@ Changes the device-cloud file synchronization switch for an application. This AP ...@@ -65,6 +72,15 @@ Changes the device-cloud file synchronization switch for an application. This AP
| status | boolean | Yes | State of the cloud-device file synchronization switch to set. The value **true** means to enable this function; the value **false** means the opposite.| | status | boolean | Yes | State of the cloud-device file synchronization switch to set. The value **true** means to enable this function; the value **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
**Example** **Example**
```js ```js
...@@ -78,6 +94,7 @@ Changes the device-cloud file synchronization switch for an application. This AP ...@@ -78,6 +94,7 @@ Changes the device-cloud file synchronization switch for an application. This AP
} }
}); });
``` ```
## cloudSyncManager.notifyDataChange ## cloudSyncManager.notifyDataChange
notifyDataChange(accountId: string, bundleName: string): Promise&lt;void&gt;; notifyDataChange(accountId: string, bundleName: string): Promise&lt;void&gt;;
...@@ -99,6 +116,15 @@ Notifies the cloud and device services of the application data change in the clo ...@@ -99,6 +116,15 @@ Notifies the cloud and device services of the application data change in the clo
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the application data change in the cloud.| | Promise&lt;void&gt; | Promise used to return the application data change in the cloud.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
**Example** **Example**
```js ```js
...@@ -127,6 +153,15 @@ Notifies the cloud and device services of the application data change in the clo ...@@ -127,6 +153,15 @@ Notifies the cloud and device services of the application data change in the clo
| bundleName | string | Yes | Bundle name of the application.| | bundleName | string | Yes | Bundle name of the application.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the application data change in the cloud.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the application data change in the cloud.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
**Example** **Example**
```js ```js
......
# @ohos.file.environment (Directory Environment Capability) # @ohos.file.environment (Directory Environment Capability)
The **Environment** module provides APIs for obtaining the root directories of the storage and public files. The **Environment** module provides APIs for obtaining the root directories of the storage and user files.
> **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. > - 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 of this module are system APIs and cannot be called by third-party applications. > - The APIs of this module are system APIs and cannot be called by third-party applications.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
...@@ -28,6 +27,15 @@ Obtains the root directory of the storage. This API uses a promise to return the ...@@ -28,6 +27,15 @@ Obtains the root directory of the storage. This API uses a promise to return the
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;string&gt; | Promise used to return the root directory of the storage.| | Promise&lt;string&gt; | Promise used to return the root directory of the storage.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 202 | The caller is not a system application |
| 13900020 | Invalid argument |
| 13900042 | Unknown error |
**Example** **Example**
```js ```js
...@@ -52,6 +60,15 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac ...@@ -52,6 +60,15 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac
| -------- | --------------------------- | ---- | -------------------------------- | | -------- | --------------------------- | ---- | -------------------------------- |
| callback | AsyncCallback&lt;string&gt; | Yes | Asynchronous callback invoked to return the root directory of the storage.| | callback | AsyncCallback&lt;string&gt; | Yes | Asynchronous callback invoked to return the root directory of the storage.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 202 | The caller is not a system application |
| 13900020 | Invalid argument |
| 13900042 | Unknown error |
**Example** **Example**
```js ```js
...@@ -68,7 +85,7 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac ...@@ -68,7 +85,7 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac
getUserDataDir():Promise&lt;string&gt; getUserDataDir():Promise&lt;string&gt;
Obtains the root directory of public files. This API uses a promise to return the result. Obtains the root directory of user files. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.Environment **System capability**: SystemCapability.FileManagement.File.Environment
...@@ -76,7 +93,16 @@ Obtains the root directory of public files. This API uses a promise to return th ...@@ -76,7 +93,16 @@ Obtains the root directory of public files. This API uses a promise to return th
| Type | Description | | Type | Description |
| --------------------- | ------------------ | | --------------------- | ------------------ |
| Promise&lt;string&gt; | Promise returned with the root directory of public files.| | Promise&lt;string&gt; | Promise used to return the root directory of user files.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 202 | The caller is not a system application |
| 13900020 | Invalid argument |
| 13900042 | Unknown error |
**Example** **Example**
...@@ -92,7 +118,7 @@ Obtains the root directory of public files. This API uses a promise to return th ...@@ -92,7 +118,7 @@ Obtains the root directory of public files. This API uses a promise to return th
getUserDataDir(callback:AsyncCallback&lt;string&gt;): void getUserDataDir(callback:AsyncCallback&lt;string&gt;): void
Obtains the root directory of public files. This API uses an asynchronous callback to return the result. Obtains the root directory of user files. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.Environment **System capability**: SystemCapability.FileManagement.File.Environment
...@@ -100,7 +126,16 @@ Obtains the root directory of public files. This API uses an asynchronous callba ...@@ -100,7 +126,16 @@ Obtains the root directory of public files. This API uses an asynchronous callba
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------------- | | -------- | --------------------------- | ---- | -------------------------------- |
| callback | AsyncCallback&lt;string&gt; | Yes | Asynchronous callback used to return the root directory of public files.| | callback | AsyncCallback&lt;string&gt; | Yes | Asynchronous callback used to return the root directory of user files.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID | Error Message |
| ---------------------------- | ---------- |
| 202 | The caller is not a system application |
| 13900020 | Invalid argument |
| 13900042 | Unknown error |
**Example** **Example**
......
...@@ -41,9 +41,9 @@ Obtains the URI of a file in synchronous mode. ...@@ -41,9 +41,9 @@ Obtains the URI of a file in synchronous mode.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------- | ---------- | | ---------------------------- | ---------- |
| string | File URI obtained.| | string | File URI obtained.|
**Error codes** **Error codes**
...@@ -52,7 +52,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod ...@@ -52,7 +52,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod
| ---------------------------- | ---------- | | ---------------------------- | ---------- |
| 401 | The input parameter is invalid | | 401 | The input parameter is invalid |
**Example** **Example**
```js ```js
......
...@@ -14,7 +14,7 @@ import fs from '@ohos.file.fs'; ...@@ -14,7 +14,7 @@ import fs from '@ohos.file.fs';
## Guidelines ## Guidelines
Before using the APIs provided by this module to perform operations on a file or folder, obtain the application sandbox path of the file or folder as follows: Before using the APIs provided by this module to perform operations on a file or directory, obtain the application sandbox path of the file or directory as follows:
**Stage Model** **Stage Model**
...@@ -29,7 +29,7 @@ export default class EntryAbility extends UIAbility { ...@@ -29,7 +29,7 @@ export default class EntryAbility extends UIAbility {
} }
``` ```
**FA Model** FA Model
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
...@@ -58,13 +58,13 @@ Obtains detailed file information. This API uses a promise to return the result. ...@@ -58,13 +58,13 @@ Obtains detailed file information. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------- | ---------- | | ---------------------------- | ---------- |
| Promise&lt;[Stat](#stat)&gt; | Promise used to return the file information obtained.| | Promise&lt;[Stat](#stat)&gt; | Promise used to return the file information obtained.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -94,7 +94,7 @@ Obtains detailed file information. This API uses an asynchronous callback to ret ...@@ -94,7 +94,7 @@ Obtains detailed file information. This API uses an asynchronous callback to ret
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -120,17 +120,17 @@ Obtains detailed file information synchronously. ...@@ -120,17 +120,17 @@ Obtains detailed file information synchronously.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------- | | ------ | ------ | ---- | -------------------------- |
| file | string\|number | Yes | Application sandbox path or FD of the file.| | file | string\|number | Yes | Application sandbox path or file descriptor (FD) of the file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------- | ---------- | | ------------- | ---------- |
| [Stat](#stat) | File information obtained.| | [Stat](#stat) | File information obtained.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -155,13 +155,13 @@ Checks whether a file exists. This API uses a promise to return the result. ...@@ -155,13 +155,13 @@ Checks whether a file exists. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| | Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -193,7 +193,7 @@ Checks whether a file exists. This API uses an asynchronous callback to return t ...@@ -193,7 +193,7 @@ Checks whether a file exists. This API uses an asynchronous callback to return t
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -226,13 +226,13 @@ Synchronously checks whether a file exists. ...@@ -226,13 +226,13 @@ Synchronously checks whether a file exists.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| boolean | Returns **true** if the file exists; returns **false** otherwise.| | boolean | Returns **true** if the file exists; returns **false** otherwise.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -259,19 +259,19 @@ Closes a file. This API uses a promise to return the result. ...@@ -259,19 +259,19 @@ Closes a file. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ | | ---- | ------ | ---- | ------------ |
| file | [File](#file)\|number | Yes | File object or FD of the file to close.| | file | [File](#file)\|number | Yes | File object or FD of the file to close.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -296,14 +296,14 @@ Closes a file. This API uses an asynchronous callback to return the result. ...@@ -296,14 +296,14 @@ Closes a file. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------ | | -------- | ------------------------- | ---- | ------------ |
| file | [File](#file)\|number | Yes | File object or FD of the file to close.| | file | [File](#file)\|number | Yes | File object or FD of the file to close.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file is closed asynchronously.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked immediately after the file is closed.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -329,13 +329,13 @@ Synchronously closes a file. ...@@ -329,13 +329,13 @@ Synchronously closes a file.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ | | ---- | ------ | ---- | ------------ |
| file | [File](#file)\|number | Yes | File object or FD of the file to close.| | file | [File](#file)\|number | Yes | File object or FD of the file to close.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -355,21 +355,21 @@ Copies a file. This API uses a promise to return the result. ...@@ -355,21 +355,21 @@ Copies a file. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | -------------------------- | ---- | ---------------------------------------- | | ---- | -------------------------- | ---- | ---------------------------------------- |
| src | string\|number | Yes | Path or FD of the file to copy. | | src | string\|number | Yes | Path or FD of the file to copy. |
| dest | string\|number | Yes | Destination path of the file or FD of the file created. | | dest | string\|number | Yes | Destination path of the file or FD of the file created. |
| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file of the same name.| | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -393,16 +393,16 @@ Copies a file. This API uses an asynchronous callback to return the result. ...@@ -393,16 +393,16 @@ Copies a file. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------- | ---- | ---------------------------------------- | | -------- | -------------------------- | ---- | ---------------------------------------- |
| src | string\|number | Yes | Path or FD of the file to copy. | | src | string\|number | Yes | Path or FD of the file to copy. |
| dest | string\|number | Yes | Destination path of the file or FD of the file created. | | dest | string\|number | Yes | Destination path of the file or FD of the file created. |
| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.| | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file is copied asynchronously. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked immediately after the file is copied. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -429,15 +429,15 @@ Synchronously copies a file. ...@@ -429,15 +429,15 @@ Synchronously copies a file.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | -------------------------- | ---- | ---------------------------------------- | | ---- | -------------------------- | ---- | ---------------------------------------- |
| src | string\|number | Yes | Path or FD of the file to copy. | | src | string\|number | Yes | Path or FD of the file to copy. |
| dest | string\|number | Yes | Destination path of the file or FD of the file created. | | dest | string\|number | Yes | Destination path of the file or FD of the file created. |
| mode | number | No | Whether to overwrite the file of the same name in the destination path. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.| | mode | number | No | Whether to overwrite the file with the same name in the destination directory. The default value is **0**, which is the only value supported.<br>**0**: overwrite the file with the same name and truncate the part that is not overwritten.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -447,6 +447,93 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem ...@@ -447,6 +447,93 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem
fs.copyFileSync(srcPath, dstPath); fs.copyFileSync(srcPath, dstPath);
``` ```
## fs.copyDir<sup>10+</sup>
copyDir(src: string, dest: string, mode?: number): Promise\<void>
Copies a directory to the specified directory. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- |
| src | string | Yes | Application sandbox path of the directory to copy.|
| dest | string | Yes | Application sandbox path of the destination directory.|
| mode | number | No | Copy mode. The default value is **0**.<br>- **0**: Throw an exception if a file conflict occurs.<br> Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.<br>- **1**: Forcibly overwrite the files with the same name in the destination directory.<br> If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.|
**Return value**
| Type | Description |
| ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example**
```js
// Copy srcPath to destPath.
let srcPath = pathDir + "/srcDir/";
let destPath = pathDir + "/destDir/";
fs.copyDir(srcPath, destPath, 0).then(() => {
console.info("copy directory succeed");
}).catch((err) => {
if (err.code == 13900015) {
for (let i = 0; i < err.data.length; i++) {
console.info("copy directory failed with conflicting files: " + err.data[i].srcFile +
" " + err.data[i].destFile);
}
} else {
console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code);
}
});
```
## fs.copyDir<sup>10+</sup>
copyDir(src: string, dest: string, mode?: number, callback: AsyncCallback\<void>): void
Copies a directory to the specified directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- |
| src | string | Yes | Application sandbox path of the directory to copy.|
| dest | string | Yes | Application sandbox path of the destination directory.|
| mode | number | No | Copy mode. The default value is **0**.<br>- **0**: Throw an exception if a file conflict occurs.<br> Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.<br>- **1**: Forcibly overwrite the files with the same name in the destination directory.<br> If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked immediately after the directory is copied. |
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example**
```js
// Copy srcPath to destPath.
let srcPath = pathDir + "/srcDir/";
let destPath = pathDir + "/destDir/";
fs.copyDir(srcPath, destPath, 0, (err) => {
if (err && err.code == 13900015) {
for (let i = 0; i < err.data.length; i++) {
console.info("copy directory failed with conflicting files: " + err.data[i].srcFile +
" " + err.data[i].destFile);
}
} else if (err) {
console.info("copy directory failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("copy directory succeed");
}
});
```
## fs.mkdir ## fs.mkdir
mkdir(path: string): Promise&lt;void&gt; mkdir(path: string): Promise&lt;void&gt;
...@@ -463,13 +550,13 @@ Creates a directory. This API uses a promise to return the result. ...@@ -463,13 +550,13 @@ Creates a directory. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -499,7 +586,7 @@ Creates a directory. This API uses an asynchronous callback to return the result ...@@ -499,7 +586,7 @@ Creates a directory. This API uses an asynchronous callback to return the result
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -530,7 +617,7 @@ Synchronously creates a directory. ...@@ -530,7 +617,7 @@ Synchronously creates a directory.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -556,13 +643,13 @@ Opens a file. This API uses a promise to return the result. File uniform resourc ...@@ -556,13 +643,13 @@ Opens a file. This API uses a promise to return the result. File uniform resourc
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ----------- | | --------------------- | ----------- |
| Promise&lt;[File](#file)&gt; | Promise used to return the file object.| | Promise&lt;[File](#file)&gt; | Promise used to return the file object.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -593,7 +680,7 @@ Opens a file. This API uses an asynchronous callback to return the result. File ...@@ -593,7 +680,7 @@ Opens a file. This API uses an asynchronous callback to return the result. File
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -625,13 +712,13 @@ Synchronously opens a file. File URIs are supported. ...@@ -625,13 +712,13 @@ Synchronously opens a file. File URIs are supported.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ----------- | | ------ | ----------- |
| [File](#file) | File object opened.| | [File](#file) | File object opened.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -660,13 +747,13 @@ Reads data from a file. This API uses a promise to return the result. ...@@ -660,13 +747,13 @@ Reads data from a file. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ------ | | ---------------------------------- | ------ |
| Promise&lt;number&gt; | Promise used to return the data read.| | Promise&lt;number&gt; | Promise used to return the data read.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -693,16 +780,16 @@ Reads data from a file. This API uses an asynchronous callback to return the res ...@@ -693,16 +780,16 @@ Reads data from a file. This API uses an asynchronous callback to return the res
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- | | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. |
| options | Object | No | The options are as follows:<br>- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| | options | Object | No | The options are as follows:<br>- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when the data is read asynchronously. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when the data is read asynchronously. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -731,21 +818,21 @@ Synchronously reads data from a file. ...@@ -731,21 +818,21 @@ Synchronously reads data from a file.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------- | ---- | ---------------------------------------- | | ------- | ----------- | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. |
| options | Object | No | The options are as follows:<br>- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| | options | Object | No | The options are as follows:<br>- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------- | | ------ | -------- |
| number | Length of the data read.| | number | Length of the data read.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -773,13 +860,13 @@ Deletes a directory. This API uses a promise to return the result. ...@@ -773,13 +860,13 @@ Deletes a directory. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -809,7 +896,7 @@ Deletes a directory. This API uses an asynchronous callback to return the result ...@@ -809,7 +896,7 @@ Deletes a directory. This API uses an asynchronous callback to return the result
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -840,7 +927,7 @@ Synchronously deletes a directory. ...@@ -840,7 +927,7 @@ Synchronously deletes a directory.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -865,13 +952,13 @@ Deletes a file. This API uses a promise to return the result. ...@@ -865,13 +952,13 @@ Deletes a file. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -897,11 +984,11 @@ Deletes a file. This API uses an asynchronous callback to return the result. ...@@ -897,11 +984,11 @@ Deletes a file. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------------------- | | -------- | ------------------------- | ---- | -------------------------- |
| path | string | Yes | Application sandbox path of the file.| | path | string | Yes | Application sandbox path of the file.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file is deleted asynchronously. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked immediately after the file is deleted. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -932,7 +1019,7 @@ Synchronously deletes a file. ...@@ -932,7 +1019,7 @@ Synchronously deletes a file.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -952,21 +1039,21 @@ Writes data into a file. This API uses a promise to return the result. ...@@ -952,21 +1039,21 @@ Writes data into a file. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------------------------------- | ---- | ---------------------------------------- | | ------- | ------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. |
| options | Object | No | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| | options | Object | No | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------- | | --------------------- | -------- |
| Promise&lt;number&gt; | Promise used to return the length of the data written.| | Promise&lt;number&gt; | Promise used to return the length of the data written.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -991,16 +1078,16 @@ Writes data into a file. This API uses an asynchronous callback to return the re ...@@ -991,16 +1078,16 @@ Writes data into a file. This API uses an asynchronous callback to return the re
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. |
| options | Object | No | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| | options | Object | No | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when the data is written asynchronously. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when the data is written asynchronously. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1027,21 +1114,21 @@ Synchronously writes data into a file. ...@@ -1027,21 +1114,21 @@ Synchronously writes data into a file.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------------------------------- | ---- | ---------------------------------------- | | ------- | ------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. |
| options | Object | No | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| | options | Object | No | The options are as follows:<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------- | | ------ | -------- |
| number | Length of the data written in the file.| | number | Length of the data written in the file.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1070,13 +1157,13 @@ Truncates a file. This API uses a promise to return the result. ...@@ -1070,13 +1157,13 @@ Truncates a file. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1108,7 +1195,7 @@ Truncates a file. This API uses an asynchronous callback to return the result. ...@@ -1108,7 +1195,7 @@ Truncates a file. This API uses an asynchronous callback to return the result.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1141,7 +1228,7 @@ Synchronously truncates a file. ...@@ -1141,7 +1228,7 @@ Synchronously truncates a file.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1168,13 +1255,13 @@ Reads the text content of a file. This API uses a promise to return the result. ...@@ -1168,13 +1255,13 @@ Reads the text content of a file. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------- | | --------------------- | ---------- |
| Promise&lt;string&gt; | Promise used to return the content read.| | Promise&lt;string&gt; | Promise used to return the content read.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1205,7 +1292,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu ...@@ -1205,7 +1292,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1237,13 +1324,13 @@ Synchronously reads the text of a file. ...@@ -1237,13 +1324,13 @@ Synchronously reads the text of a file.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------- | | ------ | -------------------- |
| string | Promise used to return the content of the file read.| | string | Promise used to return the content of the file read.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1269,13 +1356,13 @@ Obtains information about a symbolic link. This API uses a promise to return the ...@@ -1269,13 +1356,13 @@ Obtains information about a symbolic link. This API uses a promise to return the
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------- | ---------- | | ---------------------------- | ---------- |
| Promise&lt;[Stat](#stat)&gt; | Promise used to return the symbolic link information obtained. For details, see **stat**.| | Promise&lt;[Stat](#stat)&gt; | Promise used to return the symbolic link information obtained. For details, see **stat**.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1305,7 +1392,7 @@ Obtains information about a symbolic link. This API uses an asynchronous callbac ...@@ -1305,7 +1392,7 @@ Obtains information about a symbolic link. This API uses an asynchronous callbac
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1336,13 +1423,13 @@ Obtains information about a symbolic link synchronously. ...@@ -1336,13 +1423,13 @@ Obtains information about a symbolic link synchronously.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------- | ---------- | | ------------- | ---------- |
| [Stat](#stat) | File information obtained.| | [Stat](#stat) | File information obtained.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1368,13 +1455,13 @@ Renames a file or folder. This API uses a promise to return the result. ...@@ -1368,13 +1455,13 @@ Renames a file or folder. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1406,7 +1493,7 @@ Renames a file or folder. This API uses an asynchronous callback to return the r ...@@ -1406,7 +1493,7 @@ Renames a file or folder. This API uses an asynchronous callback to return the r
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1439,7 +1526,7 @@ Renames a file or folder synchronously. ...@@ -1439,7 +1526,7 @@ Renames a file or folder synchronously.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1459,19 +1546,19 @@ Flushes data of a file to disk. This API uses a promise to return the result. ...@@ -1459,19 +1546,19 @@ Flushes data of a file to disk. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ | | ---- | ------ | ---- | ------------ |
| fd | number | Yes | FD of the file.| | fd | number | Yes | FD of the file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1495,14 +1582,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return ...@@ -1495,14 +1582,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | --------------- | | -------- | ------------------------- | ---- | --------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| Callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| | Callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file data is synchronized in asynchronous mode.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1530,13 +1617,13 @@ Flushes data of a file to disk synchronously. ...@@ -1530,13 +1617,13 @@ Flushes data of a file to disk synchronously.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ | | ---- | ------ | ---- | ------------ |
| fd | number | Yes | FD of the file.| | fd | number | Yes | FD of the file.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1557,19 +1644,19 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** ...@@ -1557,19 +1644,19 @@ Flushes data of a file to disk. This API uses a promise to return the result. **
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ | | ---- | ------ | ---- | ------------ |
| fd | number | Yes | FD of the file.| | fd | number | Yes | FD of the file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1594,14 +1681,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return ...@@ -1594,14 +1681,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ----------------- | | -------- | ------------------------------- | ---- | ----------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file data is synchronized in asynchronous mode.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1628,13 +1715,13 @@ Synchronizes data in a file synchronously. ...@@ -1628,13 +1715,13 @@ Synchronizes data in a file synchronously.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ | | ---- | ------ | ---- | ------------ |
| fd | number | Yes | FD of the file.| | fd | number | Yes | FD of the file.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1662,13 +1749,13 @@ Creates a symbolic link based on a file path. This API uses a promise to return ...@@ -1662,13 +1749,13 @@ Creates a symbolic link based on a file path. This API uses a promise to return
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1700,7 +1787,7 @@ Creates a symbolic link based on a file path. This API uses an asynchronous call ...@@ -1700,7 +1787,7 @@ Creates a symbolic link based on a file path. This API uses an asynchronous call
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1733,7 +1820,7 @@ Synchronously creates a symbolic link based on a file path. ...@@ -1733,7 +1820,7 @@ Synchronously creates a symbolic link based on a file path.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1750,34 +1837,34 @@ listFile(path: string, options?: { ...@@ -1750,34 +1837,34 @@ listFile(path: string, options?: {
filter?: Filter; filter?: Filter;
}): Promise<string[]> }): Promise<string[]>
Lists all files in a directory. This API uses a promise to return the result.<br>This API supports recursive listing of all files (including files in subdirectories) and file filtering. Lists all files in a folder. This API uses a promise to return the result.<br>This API supports recursive listing of all files (including files in subfolders) and file filtering.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| path | string | Yes | Application sandbox path of the folder.| | path | string | Yes | Application sandbox path of the folder.|
| options | Object | No | File filtering options. The files are not filtered by default.| | options | Object | No | File filtering options. The files are not filtered by default.|
**options parameters** **options parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.|
| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.|
| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------- | | --------------------- | ---------- |
| Promise&lt;string[]&gt; | Promise used to return the files names listed.| | Promise&lt;string[]&gt; | Promise used to return the files names listed.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1809,27 +1896,27 @@ listFile(path: string, options?: { ...@@ -1809,27 +1896,27 @@ listFile(path: string, options?: {
filter?: Filter; filter?: Filter;
}, callback: AsyncCallback<string[]>): void }, callback: AsyncCallback<string[]>): void
Lists all files in a directory. This API uses an asynchronous callback to return the result.<br>This API supports recursive listing of all files (including files in subdirectories) and file filtering. Lists all files in a folder. This API uses an asynchronous callback to return the result.<br>This API supports recursive listing of all files (including files in subfolders) and file filtering.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| path | string | Yes | Application sandbox path of the folder.| | path | string | Yes | Application sandbox path of the folder.|
| options | Object | No | File filtering options. The files are not filtered by default.| | options | Object | No | File filtering options. The files are not filtered by default.|
| callback | AsyncCallback&lt;string[]&gt; | Yes | Callback invoked to return the file names listed. | | callback | AsyncCallback&lt;string[]&gt; | Yes | Callback invoked to return the file names listed. |
**options parameters** **options parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.|
| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.|
| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1864,32 +1951,32 @@ listFileSync(path: string, options?: { ...@@ -1864,32 +1951,32 @@ listFileSync(path: string, options?: {
filter?: Filter; filter?: Filter;
}): string[] }): string[]
Lists all files in a directory synchronously. This API supports recursive listing of all files (including files in subdirectories) and file filtering. Lists all files in a folder synchronously. This API supports recursive listing of all files (including files in subfolders) and file filtering.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| path | string | Yes | Application sandbox path of the folder.| | path | string | Yes | Application sandbox path of the folder.|
| options | Object | No | File filtering options. The files are not filtered by default.| | options | Object | No | File filtering options. The files are not filtered by default.|
**options parameters** **options parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| | recursion | boolean | No | Whether to list all files in subfolders recursively. The default value is **false**.|
| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| | listNum | number | No | Number of file names to list. The default value **0** means to list all files.|
| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| | filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------- | | --------------------- | ---------- |
| string[] | File names listed.| | string[] | File names listed.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -1915,32 +2002,32 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem ...@@ -1915,32 +2002,32 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem
moveDir(src: string, dest: string, mode?: number): Promise\<void> moveDir(src: string, dest: string, mode?: number): Promise\<void>
Moves a folder. This API uses a promise to return the result. Moves a directory. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| src | string | Yes | Application sandbox path of the source folder.| | src | string | Yes | Application sandbox path of the directory to move.|
| dest | string | Yes | Application sandbox path of the destination folder.| | dest | string | Yes | Application sandbox path of the destination directory.|
| mode | number | No | Mode for moving the folder. The default value is **0**.<br>- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.<br>- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.<br>- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.<br>- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.| | mode | number | No | Mode for moving the directory. The default value is **0**.<br>- **0**: Throw an exception if a directory conflict occurs.<br> Throw an exception if there is a directory with the same name in the destination directory.<br>- **1**: Throw an exception if a file conflict occurs.<br> Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.<br>- **2**: Forcibly overwrite the conflicting files in the destination directory.<br> If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.<br>- **3**: Forcibly overwrite the conflicting directory.<br> Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
```js ```js
// move directory from srcPath to destPath/srcPath // move directory from srcPath to destPath
let srcPath = pathDir + "/srcDir/"; let srcPath = pathDir + "/srcDir/";
let destPath = pathDir + "/destDir/"; let destPath = pathDir + "/destDir/";
fs.moveDir(srcPath, destPath, 1).then(() => { fs.moveDir(srcPath, destPath, 1).then(() => {
...@@ -1961,27 +2048,27 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem ...@@ -1961,27 +2048,27 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem
moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\<void>): void moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\<void>): void
Moves a folder. This API uses an asynchronous callback to return the result. Moves a directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| src | string | Yes | Application sandbox path of the source folder.| | src | string | Yes | Application sandbox path of the source directory.|
| dest | string | Yes | Application sandbox path of the destination folder.| | dest | string | Yes | Application sandbox path of the destination directory.|
| mode | number | No | Mode for moving the folder. The default value is **0**.<br>- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.<br>- **1**: Throw an exception if the destination directory has files of the same names with the source folder. All files without conflicts in the source folder are moved to the destination folder, and all files without conflicts in the destination folder are retained. The **data** in the error thrown provides information about the conflict files.<br>- **2**: Forcibly overwrite the files with the same names in the destination folder. The files with the the same names in the destination folder are overwritten forcibly; the files without conflicts in the destination folder are retained.<br>- **3**: Forcibly overwrite the destination folder. Move the source folder to the destination directory and make the destination folder completely the same as the source folder. All the original files in the destination folder are not retained.| | mode | number | No | Mode for moving the directory. The default value is **0**.<br>- **0**: Throw an exception if a directory conflict occurs.<br> Throw an exception if there is a directory with the same name in the destination directory.<br>- **1**: Throw an exception if a file conflict occurs.<br> Throw an exception if there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory. All the non-conflicting files in the source directory will be moved to the destination directory, and the non-conflicting files in the destination directory will be retained. The **data** attribute in the error returned provides information about the conflicting files in the Array\<[ConflictFiles](#conflictfiles)> format.<br>- **2**: Forcibly overwrite the conflicting files in the destination directory.<br> If there is a directory with the same name in the destination directory and files with the same name exist in the conflicting directory, all the files with the same name in the destination directory will be overwritten and the non-conflicting files will be retained.<br>- **3**: Forcibly overwrite the conflicting directory.<br> Move the source directory to the destination directory and overwrite the conflicting directory completely. That is, if there is a directory with the same name in the destination directory, all the original files in that directory will not be retained.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the folder is moved. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the directory is moved. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
```js ```js
// move directory from srcPath to destPath/srcPath // move directory from srcPath to destPath
let srcPath = pathDir + "/srcDir/"; let srcPath = pathDir + "/srcDir/";
let destPath = pathDir + "/destDir/"; let destPath = pathDir + "/destDir/";
fs.moveDir(srcPath, destPath, 1, (err) => { fs.moveDir(srcPath, destPath, 1, (err) => {
...@@ -2008,21 +2095,21 @@ Moves a file. This API uses a promise to return the result. ...@@ -2008,21 +2095,21 @@ Moves a file. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| src | string | Yes | Application sandbox path of the source file.| | src | string | Yes | Application sandbox path of the source file.|
| dest | string | Yes | Application sandbox path of the destination file.| | dest | string | Yes | Application sandbox path of the destination file.|
| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| | mode | number | No | Whether to overwrite the file with the same name in the destination directory.<br>The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.<br>The default value is **0**.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------------------- | | ------------------- | ---------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2046,16 +2133,16 @@ Moves a file. This API uses an asynchronous callback to return the result. ...@@ -2046,16 +2133,16 @@ Moves a file. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| src | string | Yes | Application sandbox path of the source file.| | src | string | Yes | Application sandbox path of the source file.|
| dest | string | Yes | Application sandbox path of the destination file.| | dest | string | Yes | Application sandbox path of the destination file.|
| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| | mode | number | No | Whether to overwrite the file with the same name in the destination directory.<br>The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception. <br>The default value is **0**.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file is moved. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file is moved. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2081,15 +2168,15 @@ Moves a file synchronously. ...@@ -2081,15 +2168,15 @@ Moves a file synchronously.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| src | string | Yes | Application sandbox path of the source file.| | src | string | Yes | Application sandbox path of the source file.|
| dest | string | Yes | Application sandbox path of the destination file.| | dest | string | Yes | Application sandbox path of the destination file.|
| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| | mode | number | No | Whether to overwrite the file with the same name in the destination directory.<br>The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception. <br>The default value is **0**.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2110,19 +2197,19 @@ Creates a temporary directory. This API uses a promise to return the result. ...@@ -2110,19 +2197,19 @@ Creates a temporary directory. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------- | | --------------------- | ---------- |
| Promise&lt;string&gt; | Promise used to return the unique directory generated.| | Promise&lt;string&gt; | Promise used to return the unique directory generated.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2144,14 +2231,14 @@ Creates a temporary directory. This API uses an asynchronous callback to return ...@@ -2144,14 +2231,14 @@ Creates a temporary directory. This API uses an asynchronous callback to return
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------------------- | | -------- | --------------------------- | ---- | --------------------------- |
| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked when a temporary directory is created asynchronously. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked when a temporary directory is created asynchronously. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2175,19 +2262,19 @@ Synchronously creates a temporary directory. ...@@ -2175,19 +2262,19 @@ Synchronously creates a temporary directory.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------------------- | | ------ | ------ | ---- | --------------------------- |
| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------- | | ------ | ---------- |
| string | Unique path generated.| | string | Unique path generated.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2212,13 +2299,13 @@ Creates a stream based on the file path. This API uses a promise to return the r ...@@ -2212,13 +2299,13 @@ Creates a stream based on the file path. This API uses a promise to return the r
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | --------- | | --------------------------------- | --------- |
| Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.| | Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2250,7 +2337,7 @@ Creates a stream based on the file path. This API uses an asynchronous callback ...@@ -2250,7 +2337,7 @@ Creates a stream based on the file path. This API uses an asynchronous callback
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2282,13 +2369,13 @@ Synchronously creates a stream based on the file path. ...@@ -2282,13 +2369,13 @@ Synchronously creates a stream based on the file path.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------ | --------- | | ------------------ | --------- |
| [Stream](#stream) | Stream opened.| | [Stream](#stream) | Stream opened.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2302,26 +2389,26 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem ...@@ -2302,26 +2389,26 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem
fdopenStream(fd: number, mode: string): Promise&lt;Stream&gt; fdopenStream(fd: number, mode: string): Promise&lt;Stream&gt;
Opens a stream based on the FD. This API uses a promise to return the result. Opens a stream based on the file descriptor. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| mode | string | Yes | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| | mode | string | Yes | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | --------- | | --------------------------------- | --------- |
| Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.| | Promise&lt;[Stream](#stream)&gt; | Promise used to return the result.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2340,21 +2427,21 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem ...@@ -2340,21 +2427,21 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem
fdopenStream(fd: number, mode: string, callback: AsyncCallback&lt;Stream&gt;): void fdopenStream(fd: number, mode: string, callback: AsyncCallback&lt;Stream&gt;): void
Opens a stream based on the FD. This API uses an asynchronous callback to return the result. Opens a stream based on the file descriptor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- | | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| mode | string | Yes | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| | mode | string | Yes | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
| callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes | Callback invoked when the stream is open asynchronously. | | callback | AsyncCallback&lt;[Stream](#stream)&gt; | Yes | Callback invoked when the stream is opened. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2375,26 +2462,26 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem ...@@ -2375,26 +2462,26 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem
fdopenStreamSync(fd: number, mode: string): Stream fdopenStreamSync(fd: number, mode: string): Stream
Synchronously opens a stream based on the FD. Synchronously opens a stream based on the file descriptor.
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| fd | number | Yes | FD of the file. | | fd | number | Yes | FD of the file. |
| mode | string | Yes | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| | mode | string | Yes | - **r**: Open a file for reading. The file must exist.<br>- **r+**: Open a file for both reading and writing. The file must exist.<br>- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.<br>- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).<br>- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------ | --------- | | ------------------ | --------- |
| [Stream](#stream) | Stream opened.| | [Stream](#stream) | Stream opened.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2417,21 +2504,21 @@ Creates a **Watcher** object to observe file or directory changes. ...@@ -2417,21 +2504,21 @@ Creates a **Watcher** object to observe file or directory changes.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| path | string | Yes | Application sandbox path of the file or directory to observe. | | path | string | Yes | Application sandbox path of the file or directory to observe. |
| events | number | Yes | Events to observe. Multiple events can be separated by a bitwise OR operator (&#124;)|.<br>- **0x1: IN_ACCESS**: A file is accessed.<br>- **0x2: IN_MODIFY**: The file content is modified.<br>- **0x4: IN_ATTRIB**: Metadata is changed.<br>- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.<br>- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.<br>- **0x20: IN_OPEN**: A file or directory is opened.<br>- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.<br>- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.<br>- **0x100: IN_CREATE**: A file or directory is created in the observed directory.<br>- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.<br>- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.<br>- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.<br>- **0xfff: IN_ALL_EVENTS**: All events.| | events | number | Yes | Events to observe. Multiple events can be separated by a bitwise OR operator (&#124;)|.<br>- **0x1: IN_ACCESS**: A file is accessed.<br>- **0x2: IN_MODIFY**: The file content is modified.<br>- **0x4: IN_ATTRIB**: Metadata is changed.<br>- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.<br>- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.<br>- **0x20: IN_OPEN**: A file or directory is opened.<br>- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.<br>- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.<br>- **0x100: IN_CREATE**: A file or directory is created in the observed directory.<br>- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.<br>- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.<br>- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.<br>- **0xfff: IN_ALL_EVENTS**: All events.|
| listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. | | listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------ | --------- | | ------------------ | --------- |
| [Watcher](#watcher10) | **Watcher** object created.| | [Watcher](#watcher10) | **Watcher** object created.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2463,9 +2550,9 @@ Called when an observed event occurs. ...@@ -2463,9 +2550,9 @@ Called when an observed event occurs.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| event | WatchEvent | Yes | Event for the callback to invoke. | | event | WatchEvent | Yes | Event for the callback to invoke. |
## WatchEvent<sup>10+</sup> ## WatchEvent<sup>10+</sup>
...@@ -2510,13 +2597,13 @@ Checks whether this file is a block special file. A block special file supports ...@@ -2510,13 +2597,13 @@ Checks whether this file is a block special file. A block special file supports
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------- | | ------- | ---------------- |
| boolean | Whether the file is a block special file.| | boolean | Whether the file is a block special file.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2535,13 +2622,13 @@ Checks whether this file is a character special file. A character special file s ...@@ -2535,13 +2622,13 @@ Checks whether this file is a character special file. A character special file s
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------------- | | ------- | ----------------- |
| boolean | Whether the file is a character special file.| | boolean | Whether the file is a character special file.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2560,13 +2647,13 @@ Checks whether this file is a directory. ...@@ -2560,13 +2647,13 @@ Checks whether this file is a directory.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------- | | ------- | ------------- |
| boolean | Whether the file is a directory.| | boolean | Whether the file is a directory.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2585,13 +2672,13 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int ...@@ -2585,13 +2672,13 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------------------- | | ------- | --------------------- |
| boolean | Whether the file is a FIFO.| | boolean | Whether the file is a FIFO.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2610,13 +2697,13 @@ Checks whether this file is a regular file. ...@@ -2610,13 +2697,13 @@ Checks whether this file is a regular file.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------------- | | ------- | --------------- |
| boolean | Whether the file is a regular file.| | boolean | Whether the file is a regular file.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2635,13 +2722,13 @@ Checks whether this file is a socket. ...@@ -2635,13 +2722,13 @@ Checks whether this file is a socket.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | -------------- | | ------- | -------------- |
| boolean | Whether the file is a socket.| | boolean | Whether the file is a socket.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2660,13 +2747,13 @@ Checks whether this file is a symbolic link. ...@@ -2660,13 +2747,13 @@ Checks whether this file is a symbolic link.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------------- | | ------- | --------------- |
| boolean | Whether the file is a symbolic link.| | boolean | Whether the file is a symbolic link.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2689,13 +2776,13 @@ Closes the stream. This API uses a promise to return the result. ...@@ -2689,13 +2776,13 @@ Closes the stream. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ------------- | | ------------------- | ------------- |
| Promise&lt;void&gt; | Promise used to return the stream close result.| | Promise&lt;void&gt; | Promise used to return the stream close result.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2719,13 +2806,13 @@ Closes the stream. This API uses an asynchronous callback to return the result. ...@@ -2719,13 +2806,13 @@ Closes the stream. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------- | | -------- | ------------------------- | ---- | ------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the stream is closed asynchronously.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked immediately after the stream is closed.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2736,7 +2823,7 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem ...@@ -2736,7 +2823,7 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem
if (err) { if (err) {
console.info("close stream failed with error message: " + err.message + ", error code: " + err.code); console.info("close stream failed with error message: " + err.message + ", error code: " + err.code);
} else { } else {
console.info("close stream success"): console.info("close stream success");
} }
}); });
``` ```
...@@ -2751,7 +2838,7 @@ Synchronously closes the stream. ...@@ -2751,7 +2838,7 @@ Synchronously closes the stream.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2771,13 +2858,13 @@ Flushes the stream. This API uses a promise to return the result. ...@@ -2771,13 +2858,13 @@ Flushes the stream. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ------------- | | ------------------- | ------------- |
| Promise&lt;void&gt; | Promise used to return the stream flushing result.| | Promise&lt;void&gt; | Promise used to return the stream flushing result.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2801,13 +2888,13 @@ Flushes the stream. This API uses an asynchronous callback to return the result. ...@@ -2801,13 +2888,13 @@ Flushes the stream. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | -------------- | | -------- | ------------------------- | ---- | -------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the stream is asynchronously flushed.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the stream is asynchronously flushed.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2833,7 +2920,7 @@ Synchronously flushes the stream. ...@@ -2833,7 +2920,7 @@ Synchronously flushes the stream.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2853,20 +2940,20 @@ Writes data into the stream. This API uses a promise to return the result. ...@@ -2853,20 +2940,20 @@ Writes data into the stream. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------------------------------- | ---- | ---------------------------------------- | | ------- | ------------------------------- | ---- | ---------------------------------------- |
| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. |
| options | Object | No | The options are as follows:<br>- **length** (number): length of the data to write. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| | options | Object | No | The options are as follows:<br>- **length** (number): length of the data to write. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------- | | --------------------- | -------- |
| Promise&lt;number&gt; | Promise used to return the length of the data written.| | Promise&lt;number&gt; | Promise used to return the length of the data written.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2890,15 +2977,15 @@ Writes data into the stream. This API uses an asynchronous callback to return th ...@@ -2890,15 +2977,15 @@ Writes data into the stream. This API uses an asynchronous callback to return th
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. |
| options | Object | No | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| | options | Object | No | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when the data is written asynchronously. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when the data is written asynchronously. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2926,20 +3013,20 @@ Synchronously writes data into the stream. ...@@ -2926,20 +3013,20 @@ Synchronously writes data into the stream.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------------------------------- | ---- | ---------------------------------------- | | ------- | ------------------------------- | ---- | ---------------------------------------- |
| buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. |
| options | Object | No | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.| | options | Object | No | The options are as follows:<br>- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.<br>- **encoding** (string): format of the data to be encoded when the data is a string. The default value is **'utf-8'**, which is the only value supported.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------- | | ------ | -------- |
| number | Length of the data written in the file.| | number | Length of the data written in the file.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2959,20 +3046,20 @@ Reads data from the stream. This API uses a promise to return the result. ...@@ -2959,20 +3046,20 @@ Reads data from the stream. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------- | ---- | ---------------------------------------- | | ------- | ----------- | ---- | ---------------------------------------- |
| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. |
| options | Object | No | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): position of the data to read in the file. By default, data is read from the current position.| | options | Object | No | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): position of the data to read in the file. By default, data is read from the current position.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ------ | | ---------------------------------- | ------ |
| Promise&lt;number&gt; | Promise used to return the data read.| | Promise&lt;number&gt; | Promise used to return the data read.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -2998,15 +3085,15 @@ Reads data from the stream. This API uses an asynchronous callback to return the ...@@ -2998,15 +3085,15 @@ Reads data from the stream. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- | | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. |
| options | Object | No | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.| | options | Object | No | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when data is read asynchronously from the stream. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked when data is read asynchronously from the stream. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3034,20 +3121,20 @@ Synchronously reads data from the stream. ...@@ -3034,20 +3121,20 @@ Synchronously reads data from the stream.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------- | ---- | ---------------------------------------- | | ------- | ----------- | ---- | ---------------------------------------- |
| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. |
| options | Object | No | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): position of the data to read in the file. By default, data is read from the current position.<br> | | options | Object | No | The options are as follows:<br>- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.<br>- **offset** (number): position of the data to read in the file. By default, data is read from the current position.<br> |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------- | | ------ | -------- |
| number | Length of the data read.| | number | Length of the data read.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3079,19 +3166,19 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A ...@@ -3079,19 +3166,19 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------- | ---- | ---------------------------------------- | | ------- | ----------- | ---- | ---------------------------------------- |
| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ------ | | ---------------------------------- | ------ |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3114,14 +3201,14 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A ...@@ -3114,14 +3201,14 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------- | ---- | ---------------------------------------- | | ------- | ----------- | ---- | ---------------------------------------- |
| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file is locked. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the file is locked. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3146,13 +3233,13 @@ Applies an exclusive lock or a shared lock on this file in non-blocking mode. ...@@ -3146,13 +3233,13 @@ Applies an exclusive lock or a shared lock on this file in non-blocking mode.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------- | ---- | ---------------------------------------- | | ------- | ----------- | ---- | ---------------------------------------- |
| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | | exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. |
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3172,7 +3259,7 @@ Unlocks this file synchronously. ...@@ -3172,7 +3259,7 @@ Unlocks this file synchronously.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3199,7 +3286,7 @@ Starts listening. ...@@ -3199,7 +3286,7 @@ Starts listening.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3222,7 +3309,7 @@ Stops listening. ...@@ -3222,7 +3309,7 @@ Stops listening.
**Error codes** **Error codes**
For details about error codes, see "Basic File I/O Error Codes" in [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
...@@ -3266,3 +3353,14 @@ Defines the file filtering configuration, which can be used by **listFile()**. ...@@ -3266,3 +3353,14 @@ Defines the file filtering configuration, which can be used by **listFile()**.
| fileSizeOver | number | Locate files that are greater than or equal to the specified size. | | fileSizeOver | number | Locate files that are greater than or equal to the specified size. |
| lastModifiedAfter | number | Locate files whose last modification time is the same or later than the specified time. | | lastModifiedAfter | number | Locate files whose last modification time is the same or later than the specified time. |
| excludeMedia | boolean | Whether to exclude the files already in **Media**. | | excludeMedia | boolean | Whether to exclude the files already in **Media**. |
## ConflictFiles
**System capability**: SystemCapability.FileManagement.File.FileIO
Defines information about the conflicting files. It is used the **copyDir()** and **moveDir()**.
| Name | Type | Description |
| ----------- | --------------- | ------------------ |
| srcFile | string | Path of the source file. |
| destFile | string | Path of the destination file.|
# @ohos.file.hash (File Hash Processing) # @ohos.file.hash (File Hash Processing)
The **fileHash** module implements hash processing on files. The **FileHash** module implements hash processing on files.
> **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. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
...@@ -17,7 +16,7 @@ import Hash from '@ohos.file.hash'; ...@@ -17,7 +16,7 @@ import Hash from '@ohos.file.hash';
Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows: Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows:
**Stage Model** Stage Model
```js ```js
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -30,7 +29,7 @@ export default class EntryAbility extends UIAbility { ...@@ -30,7 +29,7 @@ export default class EntryAbility extends UIAbility {
} }
``` ```
**FA Model** FA Model
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
...@@ -64,6 +63,15 @@ Calculates a hash value for a file. This API uses a promise to return the result ...@@ -64,6 +63,15 @@ Calculates a hash value for a file. This API uses a promise to return the result
| --------------------- | -------------------------- | | --------------------- | -------------------------- |
| Promise&lt;string&gt; | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| | Promise&lt;string&gt; | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900020 | Invalid argument |
| 13900042 | Unknown error |
**Example** **Example**
```js ```js
...@@ -89,9 +97,19 @@ Calculates a hash value for a file. This API uses an asynchronous callback to re ...@@ -89,9 +97,19 @@ Calculates a hash value for a file. This API uses an asynchronous callback to re
| --------- | --------------------------- | ---- | ------------------------------------------------------------ | | --------- | --------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the file in the application sandbox. | | path | string | Yes | Path of the file in the application sandbox. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.| | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900020 | Invalid argument |
| 13900042 | Unknown error |
**Example** **Example**
```js ```js
let filePath = pathDir + "/test.txt"; let filePath = pathDir + "/test.txt";
Hash.hash(filePath, "sha256", (err, str) => { Hash.hash(filePath, "sha256", (err, str) => {
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
> 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 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 ## Modules to Import
```js ```js
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
``` ```
......
...@@ -4,8 +4,7 @@ The **securityLabel** module provides APIs for managing data security levels of ...@@ -4,8 +4,7 @@ The **securityLabel** module provides APIs for managing data security levels of
> **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. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
...@@ -60,9 +59,24 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t ...@@ -60,9 +59,24 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------- | | ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900001 | Operation not permitted |
| 13900007 | Arg list too long |
| 13900015 | File exists |
| 13900020 | Invalid argument |
| 13900025 | No space left on device |
| 13900037 | No data available |
| 13900041 | Quota exceeded |
| 13900042 | Unknown error |
**Example** **Example**
...@@ -91,6 +105,21 @@ Sets a security label for a file in asynchronous mode. This API uses an asynchro ...@@ -91,6 +105,21 @@ Sets a security label for a file in asynchronous mode. This API uses an asynchro
| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| | type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900001 | Operation not permitted |
| 13900007 | Arg list too long |
| 13900015 | File exists |
| 13900020 | Invalid argument |
| 13900025 | No space left on device |
| 13900037 | No data available |
| 13900041 | Quota exceeded |
| 13900042 | Unknown error |
**Example** **Example**
```js ```js
...@@ -119,6 +148,21 @@ Sets a security label for a file in synchronous mode. ...@@ -119,6 +148,21 @@ Sets a security label for a file in synchronous mode.
| path | string | Yes | Path of the target file. | | path | string | Yes | Path of the target file. |
| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| | type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900001 | Operation not permitted |
| 13900007 | Arg list too long |
| 13900015 | File exists |
| 13900020 | Invalid argument |
| 13900025 | No space left on device |
| 13900037 | No data available |
| 13900041 | Quota exceeded |
| 13900042 | Unknown error |
**Example** **Example**
```js ```js
...@@ -136,15 +180,30 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi ...@@ -136,15 +180,30 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------- | | ------ | ------ | ---- | -------- |
| path | string | Yes | Path of the target file.| | path | string | Yes | Path of the target file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------ | | --------------------- | ------------ |
| Promise&lt;string&gt; | Security label obtained.| | Promise&lt;string&gt; | Security label obtained.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900001 | Operation not permitted |
| 13900007 | Arg list too long |
| 13900015 | File exists |
| 13900020 | Invalid argument |
| 13900025 | No space left on device |
| 13900037 | No data available |
| 13900041 | Quota exceeded |
| 13900042 | Unknown error |
**Example** **Example**
...@@ -167,10 +226,25 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb ...@@ -167,10 +226,25 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------- | | -------- | --------------------------- | ---- | -------------------------- |
| path | string | Yes | Path of the target file. | | path | string | Yes | Path of the target file. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the security label obtained.| | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the security label obtained.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900001 | Operation not permitted |
| 13900007 | Arg list too long |
| 13900015 | File exists |
| 13900020 | Invalid argument |
| 13900025 | No space left on device |
| 13900037 | No data available |
| 13900041 | Quota exceeded |
| 13900042 | Unknown error |
**Example** **Example**
...@@ -184,6 +258,7 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb ...@@ -184,6 +258,7 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb
} }
}); });
``` ```
## securityLabel.getSecurityLabelSync ## securityLabel.getSecurityLabelSync
getSecurityLabelSync(path:string):string getSecurityLabelSync(path:string):string
...@@ -204,6 +279,21 @@ Obtains the security label of a file in synchronous mode. ...@@ -204,6 +279,21 @@ Obtains the security label of a file in synchronous mode.
| ------ | ------------ | | ------ | ------------ |
| string | Security label obtained.| | string | Security label obtained.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
| ID| Error Message|
| -------- | -------- |
| 13900001 | Operation not permitted |
| 13900007 | Arg list too long |
| 13900015 | File exists |
| 13900020 | Invalid argument |
| 13900025 | No space left on device |
| 13900037 | No data available |
| 13900041 | Quota exceeded |
| 13900042 | Unknown error |
**Example** **Example**
```js ```js
......
...@@ -4,14 +4,14 @@ The **statfs** module provides APIs for obtaining file system information, inclu ...@@ -4,14 +4,14 @@ The **statfs** module provides APIs for obtaining file system information, inclu
> **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. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
```js ```js
import statvfs from '@ohos.file.statvfs'; import statvfs from '@ohos.file.statvfs';
``` ```
## statvfs.getFreeSize ## statvfs.getFreeSize
getFreeSize(path:string):Promise&lt;number&gt; getFreeSize(path:string):Promise&lt;number&gt;
...@@ -32,6 +32,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -32,6 +32,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
| --------------------- | -------------- | | --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.| | Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
```js ```js
...@@ -58,6 +62,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -58,6 +62,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
```js ```js
...@@ -91,6 +99,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -91,6 +99,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m
| --------------------- | ------------ | | --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.| | Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
```js ```js
...@@ -117,6 +129,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -117,6 +129,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
**Error codes**
For details about the error codes, see [Basic File IO Error Codes](../errorcodes/errorcode-filemanagement.md#basic-file-io-error-codes).
**Example** **Example**
```js ```js
......
...@@ -4,8 +4,8 @@ The **storageStatistics** module provides APIs for obtaining storage space infor ...@@ -4,8 +4,8 @@ The **storageStatistics** module provides APIs for obtaining storage space infor
> **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. > 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 of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
```js ```js
...@@ -24,7 +24,6 @@ Obtains the total size (in bytes) of the specified volume in an external storage ...@@ -24,7 +24,6 @@ Obtains the total size (in bytes) of the specified volume in an external storage
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
...@@ -37,6 +36,19 @@ Obtains the total size (in bytes) of the specified volume in an external storage ...@@ -37,6 +36,19 @@ Obtains the total size (in bytes) of the specified volume in an external storage
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;number&gt; | Promise used to return the total volume size obtained.| | Promise&lt;number&gt; | Promise used to return the total volume size obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -60,7 +72,6 @@ Obtains the total size (in bytes) of the specified volume in an external storage ...@@ -60,7 +72,6 @@ Obtains the total size (in bytes) of the specified volume in an external storage
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
...@@ -68,6 +79,19 @@ Obtains the total size (in bytes) of the specified volume in an external storage ...@@ -68,6 +79,19 @@ Obtains the total size (in bytes) of the specified volume in an external storage
| volumeUuid | string | Yes | UUID of the volume. | | volumeUuid | string | Yes | UUID of the volume. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total volume size obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total volume size obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -90,7 +114,6 @@ Obtains the available space (in bytes) of the specified volume in an external st ...@@ -90,7 +114,6 @@ Obtains the available space (in bytes) of the specified volume in an external st
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
...@@ -103,6 +126,19 @@ Obtains the available space (in bytes) of the specified volume in an external st ...@@ -103,6 +126,19 @@ Obtains the available space (in bytes) of the specified volume in an external st
| --------------------- | ------------------ | | --------------------- | ------------------ |
| Promise&lt;number&gt; | Promise used to return the available volume space obtained.| | Promise&lt;number&gt; | Promise used to return the available volume space obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -127,7 +163,6 @@ Obtains the available space (in bytes) of the specified volume in an external st ...@@ -127,7 +163,6 @@ Obtains the available space (in bytes) of the specified volume in an external st
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
...@@ -135,6 +170,19 @@ Obtains the available space (in bytes) of the specified volume in an external st ...@@ -135,6 +170,19 @@ Obtains the available space (in bytes) of the specified volume in an external st
| volumeUuid | string | Yes | UUID of the volume. | | volumeUuid | string | Yes | UUID of the volume. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the available volume space obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the available volume space obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -157,7 +205,6 @@ Obtains the space (in bytes) of an application. This API uses a promise to retur ...@@ -157,7 +205,6 @@ Obtains the space (in bytes) of an application. This API uses a promise to retur
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
...@@ -170,6 +217,19 @@ Obtains the space (in bytes) of an application. This API uses a promise to retur ...@@ -170,6 +217,19 @@ Obtains the space (in bytes) of an application. This API uses a promise to retur
| ------------------------------------------ | -------------------------- | | ------------------------------------------ | -------------------------- |
| Promise&lt;[Bundlestats](#bundlestats9)&gt; | Promise used to return the application space obtained.| | Promise&lt;[Bundlestats](#bundlestats9)&gt; | Promise used to return the application space obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -193,7 +253,6 @@ Obtains the space (in bytes) of an application. This API uses an asynchronous ca ...@@ -193,7 +253,6 @@ Obtains the space (in bytes) of an application. This API uses an asynchronous ca
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
...@@ -201,6 +260,19 @@ Obtains the space (in bytes) of an application. This API uses an asynchronous ca ...@@ -201,6 +260,19 @@ Obtains the space (in bytes) of an application. This API uses an asynchronous ca
| packageName | string | Yes | Bundle name of the application.| | packageName | string | Yes | Bundle name of the application.|
| callback | AsyncCallback&lt;[Bundlestats](#bundlestats9)&gt; | Yes | Callback invoked to return the application space obtained.| | callback | AsyncCallback&lt;[Bundlestats](#bundlestats9)&gt; | Yes | Callback invoked to return the application space obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -225,6 +297,16 @@ Obtains the space (in bytes) of this third-party application. This API uses a pr ...@@ -225,6 +297,16 @@ Obtains the space (in bytes) of this third-party application. This API uses a pr
| ------------------------------------------ | -------------------------- | | ------------------------------------------ | -------------------------- |
| Promise&lt;[Bundlestats](#bundlestats9)&gt; | Promise used to return the application space obtained. | | Promise&lt;[Bundlestats](#bundlestats9)&gt; | Promise used to return the application space obtained. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -246,6 +328,16 @@ Obtains the space (in bytes) of this third-party application. This API uses an a ...@@ -246,6 +328,16 @@ Obtains the space (in bytes) of this third-party application. This API uses an a
| -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ |
| callback | AsyncCallback&lt;[BundleStats](#bundlestats9)&gt; | Yes | Callback invoked to return the application space obtained. | | callback | AsyncCallback&lt;[BundleStats](#bundlestats9)&gt; | Yes | Callback invoked to return the application space obtained. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -265,7 +357,6 @@ Obtains the space (in bytes) of this third-party application. This API uses an a ...@@ -265,7 +357,6 @@ Obtains the space (in bytes) of this third-party application. This API uses an a
| cacheSize | number | Yes| No| Cache size of the application, in bytes. | | cacheSize | number | Yes| No| Cache size of the application, in bytes. |
| dataSize | number | Yes| No| Total data size of the application, in bytes.| | dataSize | number | Yes| No| Total data size of the application, in bytes.|
## storageStatistics.getTotalSize<sup>9+</sup> ## storageStatistics.getTotalSize<sup>9+</sup>
getTotalSize(): Promise&lt;number&gt; getTotalSize(): Promise&lt;number&gt;
...@@ -284,6 +375,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses a promi ...@@ -284,6 +375,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses a promi
| --------------------- | ------------------ | | --------------------- | ------------------ |
| Promise&lt;number&gt; | Promise used to return the built-in storage size obtained. | | Promise&lt;number&gt; | Promise used to return the built-in storage size obtained. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -309,6 +412,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn ...@@ -309,6 +412,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn
| -------- | ------------------------------------ | ---- | ------------------------ | | -------- | ------------------------------------ | ---- | ------------------------ |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the built-in storage size obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the built-in storage size obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -318,7 +433,6 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn ...@@ -318,7 +433,6 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn
}); });
``` ```
## storageStatistics.getFreeSize<sup>9+</sup> ## storageStatistics.getFreeSize<sup>9+</sup>
getFreeSize(): Promise&lt;number&gt; getFreeSize(): Promise&lt;number&gt;
...@@ -337,6 +451,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses a ...@@ -337,6 +451,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses a
| --------------------- | ------------------ | | --------------------- | ------------------ |
| Promise&lt;number&gt; | Promise used to return the available space of the built-in storage obtained.| | Promise&lt;number&gt; | Promise used to return the available space of the built-in storage obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -344,7 +470,6 @@ Obtains the available space (in bytes) of the built-in storage. This API uses a ...@@ -344,7 +470,6 @@ Obtains the available space (in bytes) of the built-in storage. This API uses a
console.info("getFreeSize successfully:"+ JSON.stringify(number)); console.info("getFreeSize successfully:"+ JSON.stringify(number));
``` ```
## storageStatistics.getFreeSize<sup>9+</sup> ## storageStatistics.getFreeSize<sup>9+</sup>
getFreeSize(callback: AsyncCallback&lt;number&gt;): void getFreeSize(callback: AsyncCallback&lt;number&gt;): void
...@@ -363,6 +488,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses an ...@@ -363,6 +488,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses an
| -------- | ------------------------------------ | ---- | ------------------------- | | -------- | ------------------------------------ | ---- | ------------------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the available space of the built-in storage obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the available space of the built-in storage obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -384,13 +521,24 @@ Obtains the system data space, in bytes. This API uses a promise to return the r ...@@ -384,13 +521,24 @@ Obtains the system data space, in bytes. This API uses a promise to return the r
**System API**: This is a system API. **System API**: This is a system API.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;number&gt; | Promise used to return the system data space obtained.| | Promise&lt;number&gt; | Promise used to return the system data space obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -419,6 +567,18 @@ Obtains the system data space, in bytes. This API uses an asynchronous callback ...@@ -419,6 +567,18 @@ Obtains the system data space, in bytes. This API uses an asynchronous callback
| ---------- | ------------------------------------ | ---- | -------------------------- | | ---------- | ------------------------------------ | ---- | -------------------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the system data space obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the system data space obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -446,6 +606,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses a promise ...@@ -446,6 +606,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses a promise
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;[StorageStats](#storagestats9)&gt; | Promise used to return the information obtained.| | Promise&lt;[StorageStats](#storagestats9)&gt; | Promise used to return the information obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -474,6 +646,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses an asynchr ...@@ -474,6 +646,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses an asynchr
| ---------- | ------------------------------------ | ---- | -------------------------- | | ---------- | ------------------------------------ | ---- | -------------------------- |
| callback | AsyncCallback&lt;[StorageStats](#storagestats9)&gt; | Yes | Callback invoked to return the information obtained.| | callback | AsyncCallback&lt;[StorageStats](#storagestats9)&gt; | Yes | Callback invoked to return the information obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -482,6 +666,9 @@ Obtains the storage statistics (in bytes) of this user. This API uses an asynchr ...@@ -482,6 +666,9 @@ Obtains the storage statistics (in bytes) of this user. This API uses an asynchr
console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats));
}); });
``` ```
## storageStatistics.getUserStorageStats<sup>9+</sup>
getUserStorageStats(userId: number): Promise&lt;StorageStats&gt; getUserStorageStats(userId: number): Promise&lt;StorageStats&gt;
Obtains the storage statistics (in bytes) of the specified user. This API uses a promise to return the result. Obtains the storage statistics (in bytes) of the specified user. This API uses a promise to return the result.
...@@ -504,6 +691,19 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a ...@@ -504,6 +691,19 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;[StorageStats](#storagestats9)&gt; | Promise used to return the information obtained.| | Promise&lt;[StorageStats](#storagestats9)&gt; | Promise used to return the information obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600009 | User if out of range. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -534,6 +734,19 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a ...@@ -534,6 +734,19 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a
| userId | number | Yes | User ID.| | userId | number | Yes | User ID.|
| callback | AsyncCallback&lt;[StorageStats](#storagestats9)&gt; | Yes | Callback invoked to return the information obtained.| | callback | AsyncCallback&lt;[StorageStats](#storagestats9)&gt; | Yes | Callback invoked to return the information obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600009 | User if out of range. |
| 13900032 | Unknown error. |
**Example** **Example**
```js ```js
...@@ -544,7 +757,6 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a ...@@ -544,7 +757,6 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a
}); });
``` ```
## StorageStats<sup>9+</sup> ## StorageStats<sup>9+</sup>
**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics
......
...@@ -6,7 +6,6 @@ The **volumeManager** module provides APIs for volume and disk management, inclu ...@@ -6,7 +6,6 @@ The **volumeManager** module provides APIs for volume and disk management, inclu
> >
> - 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 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.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
...@@ -26,9 +25,21 @@ Obtains information about all volumes of this external storage device. This API ...@@ -26,9 +25,21 @@ Obtains information about all volumes of this external storage device. This API
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | -------------------------- | | ---------------------------------- | -------------------------- |
| Promise&lt;[Volume](#volume)[]&gt; | Promise used to return information about all available volumes.| | Promise&lt;[Volume](#volume)[]&gt; | Promise used to return information about all available volumes.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -52,9 +63,21 @@ Obtains information about all volumes of this external storage device. This API ...@@ -52,9 +63,21 @@ Obtains information about all volumes of this external storage device. This API
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------------------------ | | -------- | ------------------------------------------------- | ---- | ------------------------------------ |
| callback | AsyncCallback&lt;[Volume](#volume)[]&gt; | Yes | Callback invoked to return information about all available volumes.| | callback | AsyncCallback&lt;[Volume](#volume)[]&gt; | Yes | Callback invoked to return information about all available volumes.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -65,7 +88,6 @@ Obtains information about all volumes of this external storage device. This API ...@@ -65,7 +88,6 @@ Obtains information about all volumes of this external storage device. This API
}); });
``` ```
## volumemanager.mount ## volumemanager.mount
mount(volumeId: string): Promise&lt;void&gt; mount(volumeId: string): Promise&lt;void&gt;
...@@ -78,15 +100,31 @@ Asynchronously mounts a volume. This API uses a promise to return the result. Cu ...@@ -78,15 +100,31 @@ Asynchronously mounts a volume. This API uses a promise to return the result. Cu
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| -------- | ------ | ---- | ---- | | -------- | ------ | ---- | ---- |
| volumeId | string | Yes | Volume ID.| | volumeId | string | Yes | Volume ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------- | ---------- | | ---------------------- | ---------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600003 | Failed to mount. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -111,10 +149,26 @@ Asynchronously mounts a volume. This API uses an asynchronous callback to return ...@@ -111,10 +149,26 @@ Asynchronously mounts a volume. This API uses an asynchronous callback to return
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | -------------------- | | -------- | ------------------------------------- | ---- | -------------------- |
| volumeId | string | Yes | Volume ID. | | volumeId | string | Yes | Volume ID. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600003 | Failed to mount. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -137,15 +191,31 @@ Asynchronously unmounts a volume. This API uses a promise to return the result. ...@@ -137,15 +191,31 @@ Asynchronously unmounts a volume. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| -------- | ------ | ---- | ---- | | -------- | ------ | ---- | ---- |
| volumeId | string | Yes | Volume ID.| | volumeId | string | Yes | Volume ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------- | ---------- | | ---------------------- | ---------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600004 | Failed to unmount. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -170,10 +240,26 @@ Asynchronously unmounts a volume. This API uses an asynchronous callback to retu ...@@ -170,10 +240,26 @@ Asynchronously unmounts a volume. This API uses an asynchronous callback to retu
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | -------------------- | | -------- | ------------------------------------- | ---- | -------------------- |
| volumeId | string | Yes | Volume ID. | | volumeId | string | Yes | Volume ID. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600004 | Failed to unmount. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -196,15 +282,28 @@ Obtains information about a volume based on the universally unique identifier (U ...@@ -196,15 +282,28 @@ Obtains information about a volume based on the universally unique identifier (U
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| -------- | ------ | ---- | ---- | | -------- | ------ | ---- | ---- |
| uuid | string | Yes | UUID of the volume.| | uuid | string | Yes | UUID of the volume.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | -------------------------- | | ---------------------------------- | -------------------------- |
| Promise&lt;[Volume](#volume)&gt; | Promise used to return the volume information obtained.| | Promise&lt;[Volume](#volume)&gt; | Promise used to return the volume information obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -229,10 +328,23 @@ Obtains information about a volume based on the UUID. This API uses an asynchron ...@@ -229,10 +328,23 @@ Obtains information about a volume based on the UUID. This API uses an asynchron
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | -------------------- | | -------- | ------------------------------------------------ | ---- | -------------------- |
| uuid | string | Yes | UUID of the volume. | | uuid | string | Yes | UUID of the volume. |
| callback | AsyncCallback&lt;[Volume](#volume)&gt; | Yes | Callback invoked to return the volume information obtained.| | callback | AsyncCallback&lt;[Volume](#volume)&gt; | Yes | Callback invoked to return the volume information obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -255,15 +367,28 @@ Obtains information about a volume based on the volume ID. This API uses a promi ...@@ -255,15 +367,28 @@ Obtains information about a volume based on the volume ID. This API uses a promi
**Parameters** **Parameters**
| Name | Type | Mandatory | Description| | Name | Type | Mandatory | Description|
| -------- | ------ | ---- | ---- | | -------- | ------ | ---- | ---- |
| volumeId | string | Yes | Volume ID.| | volumeId | string | Yes | Volume ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | -------------------------- | | ---------------------------------- | -------------------------- |
| Promise&lt;[Volume](#volume)&gt; | Promise used to return the volume information obtained.| | Promise&lt;[Volume](#volume)&gt; | Promise used to return the volume information obtained.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -288,10 +413,23 @@ Obtains information about a volume based on the volume ID. This API uses an asyn ...@@ -288,10 +413,23 @@ Obtains information about a volume based on the volume ID. This API uses an asyn
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ----------------------------- | | -------- | ------------------------- | ---- | ----------------------------- |
| volumeId | string | Yes | Volume ID. | | volumeId | string | Yes | Volume ID. |
| callback | AsyncCallback&lt;[Volume](#volume)&gt; | Yes | Callback invoked to return the volume information obtained. | | callback | AsyncCallback&lt;[Volume](#volume)&gt; | Yes | Callback invoked to return the volume information obtained. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -314,16 +452,31 @@ Sets volume description. This API uses a promise to return the result. ...@@ -314,16 +452,31 @@ Sets volume description. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| --------- | ------ | ---- | ---- | | --------- | ------ | ---- | ---- |
| uuid | string | Yes | UUID of the volume.| | uuid | string | Yes | UUID of the volume.|
| description | string | Yes | Volume description to set.| | description | string | Yes | Volume description to set.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------- | -------------------------- | | ---------------------- | -------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. | | Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -349,11 +502,26 @@ Sets volume description. This API uses an asynchronous callback to return the re ...@@ -349,11 +502,26 @@ Sets volume description. This API uses an asynchronous callback to return the re
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | --------------------------------------- | ---- | ---------------- | | ---------- | --------------------------------------- | ---- | ---------------- |
| uuid | string | Yes | UUID of the volume. | | uuid | string | Yes | UUID of the volume. |
| description | string | Yes | Volume description to set. | | description | string | Yes | Volume description to set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -377,16 +545,31 @@ Formats a volume. This API uses a promise to return the result. Currently, only ...@@ -377,16 +545,31 @@ Formats a volume. This API uses a promise to return the result. Currently, only
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| ----------- | ------ | ---- | ---- | | ----------- | ------ | ---- | ---- |
| volumeId | string | Yes | Volume ID.| | volumeId | string | Yes | Volume ID.|
| fsType | string | Yes | File system type, which can be VFAT or exFAT.| | fsType | string | Yes | File system type, which can be VFAT or exFAT.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------- | ---------- | | ---------------------- | ---------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -412,11 +595,26 @@ Formats a volume. This API uses an asynchronous callback to return the result. C ...@@ -412,11 +595,26 @@ Formats a volume. This API uses an asynchronous callback to return the result. C
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ----------------------------- | | -------- | ------------------------- | ---- | ----------------------------- |
| volumeId | string | Yes | Volume ID. | | volumeId | string | Yes | Volume ID. |
| fsType | string | Yes | File system type, which can be VFAT or exFAT.| | fsType | string | Yes | File system type, which can be VFAT or exFAT.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600002 | Not supported filesystem. |
| 13600005 | Incorrect volume state. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -440,16 +638,29 @@ Partitions a disk. This API uses a promise to return the result. The system supp ...@@ -440,16 +638,29 @@ Partitions a disk. This API uses a promise to return the result. The system supp
**Parameters** **Parameters**
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| ----------- | ------ | ---- | ---- | | ----------- | ------ | ---- | ---- |
| diskId | string | Yes | ID of the disk to partition.| | diskId | string | Yes | ID of the disk to partition.|
| type | number | Yes | Partition type. | | type | number | Yes | Partition type. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ----------------------- | | --------------------- | ----------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
...@@ -475,11 +686,24 @@ Asynchronously partitions a disk. This API uses a callback to return the result. ...@@ -475,11 +686,24 @@ Asynchronously partitions a disk. This API uses a callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------------- | | -------- | --------------------------------------- | ---- | ---------------- |
| diskId | string | Yes | ID of the disk to partition. | | diskId | string | Yes | ID of the disk to partition. |
| type | number | Yes | Partition type. | | type | number | Yes | Partition type. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value. |
**Error codes**
For details about the error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
| ID| Error Message|
| -------- | -------- |
| 201 | Permission verification failed. |
| 202 | The caller is not a system application. |
| 401 | The input parameter is invalid. |
| 13600001 | IPC error. |
| 13600008 | No such object. |
| 13900032 | Unknown error. |
**Example** **Example**
......
# @ohos.fileshare (File Sharing) # @ohos.fileshare (File Sharing)
The **fileShare** module provides APIs for granting the access permissions on a user file to another application by the Uniform Resource Identifier (URI). Then, the authorized application can access the file by using the APIs provided by [@ohos.file.fs](js-apis-file-fs.md). The **fileshare** module provides APIs for granting the access permissions on a user file to another application by the Uniform Resource Identifier (URI). Then, the authorized application can access the file by using the APIs provided by [@ohos.file.fs](js-apis-file-fs.md).
> **NOTE** > **NOTE**
> >
...@@ -31,7 +31,7 @@ Grants permissions on a user file by the URI to an application. This API uses an ...@@ -31,7 +31,7 @@ Grants permissions on a user file by the URI to an application. This API uses an
| uri | string | Yes | URI of a user file.| | uri | string | Yes | URI of a user file.|
| bundleName | string | Yes | Bundle name of the application to be grated with the permissions.| | bundleName | string | Yes | Bundle name of the application to be grated with the permissions.|
| mode | number | Yes | Permissions to grant. For details, see [wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags).<br>**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file. <br>**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.| | mode | number | Yes | Permissions to grant. For details, see [wantConstant.Flags](js-apis-app-ability-wantConstant.md#wantconstantflags).<br>**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file. <br>**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes** **Error codes**
...@@ -44,7 +44,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod ...@@ -44,7 +44,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod
| 401 | The input parameter is invalid | | 401 | The input parameter is invalid |
| 143000001 | IPC error | | 143000001 | IPC error |
**Example** **Example**
```js ```js
...@@ -66,7 +65,6 @@ try { ...@@ -66,7 +65,6 @@ try {
} }
``` ```
## fileShare.grantUriPermission ## fileShare.grantUriPermission
grantUriPermission(uri: string, bundleName: string, mode: number): Promise&lt;void&gt; grantUriPermission(uri: string, bundleName: string, mode: number): Promise&lt;void&gt;
...@@ -89,10 +87,9 @@ Grants permissions on a user file by the URI to an application. This API uses a ...@@ -89,10 +87,9 @@ Grants permissions on a user file by the URI to an application. This API uses a
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------- | ---------- | | ---------------------------- | ---------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
...@@ -105,7 +102,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod ...@@ -105,7 +102,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod
| 401 | The input parameter is invalid | | 401 | The input parameter is invalid |
| 143000001 | IPC error | | 143000001 | IPC error |
**Example** **Example**
```js ```js
......
...@@ -865,8 +865,8 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback ...@@ -865,8 +865,8 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback
| uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. |
| method | string | Yes | Name of the API to call. | | method | string | Yes | Name of the API to call. |
| arg | string | Yes | Parameter to pass in. | | arg | string | Yes | Parameter to pass in. |
| extras | [PacMap](js-apis-inner-application-pacMap.md) | Yes | Key-value pair parameter. | | extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Yes | Key-value pair parameter. |
| callback | AsyncCallback\<[PacMap](js-apis-inner-application-pacMap.md)> | Yes| Callback used to return the result. | | callback | AsyncCallback\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | Yes| Callback used to return the result. |
**Example** **Example**
...@@ -901,13 +901,13 @@ Calls an extended API of the DataAbility. This API uses a promise to return the ...@@ -901,13 +901,13 @@ Calls an extended API of the DataAbility. This API uses a promise to return the
| uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. |
| method | string | Yes | Name of the API to call. | | method | string | Yes | Name of the API to call. |
| arg | string | Yes | Parameter to pass in. | | arg | string | Yes | Parameter to pass in. |
| extras | [PacMap](js-apis-inner-application-pacMap.md) | Yes | Key-value pair parameter. | | extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Yes | Key-value pair parameter. |
**Return value** **Return value**
| Type| Description| | Type| Description|
|------ | ------- | |------ | ------- |
|Promise\<[PacMap](js-apis-inner-application-pacMap.md)> | Promise used to return the result.| |Promise\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | Promise used to return the result.|
**Example** **Example**
...@@ -998,3 +998,13 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi ...@@ -998,3 +998,13 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi
}); });
``` ```
## PacMap
[key: string]: number | string | boolean | Array\<string | number | boolean> | null;
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
| Name| Type| Mandatory| Description|
| ------ | ------ | ------ | ------ |
| [key: string] | number \| string \| boolean \| Array\<string \| number \| boolean\> \| null | Yes| Data stored in key-value pairs.|
\ No newline at end of file
...@@ -72,6 +72,6 @@ import Want from '@ohos.app.ability.Want'; ...@@ -72,6 +72,6 @@ import Want from '@ohos.app.ability.Want';
// ... // ...
``` ```
- For more details and examples, see [Want](../../application-models/want-overview.md). - For more details and examples, see [Application Model](../../application-models/application-model-composition.md).
<!--no_check--> <!--no_check-->
...@@ -122,6 +122,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -122,6 +122,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700036 | Failed to install the HSP because lacks appropriate permissions. | | 17700036 | Failed to install the HSP because lacks appropriate permissions. |
| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
| 17700041 | Failed to install because enterprise device management disallow install. | | 17700041 | Failed to install because enterprise device management disallow install. |
| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
**Example** **Example**
...@@ -185,6 +189,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -185,6 +189,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700036 | Failed to install the HSP because lacks appropriate permissions. | | 17700036 | Failed to install the HSP because lacks appropriate permissions. |
| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
| 17700041 | Failed to install because enterprise device management disallow install. | | 17700041 | Failed to install because enterprise device management disallow install. |
| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
**Example** **Example**
...@@ -226,7 +234,7 @@ Installs a bundle. This API uses a promise to return the result. ...@@ -226,7 +234,7 @@ Installs a bundle. This API uses a promise to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| hapFilePaths | Array\<string\> | Yes | Paths where the HAP files of the bundle are stored, which are the data directories. If only one directory is passed, the HAP files in the directory must belong to the same bundle and have the same signature.| | hapFilePaths | Array\<string\> | Yes | Paths where the HAP files of the bundle are stored, which are the data directories. If only one directory is passed, the HAP files in the directory must belong to the same bundle and have the same signature.|
| installParam | [InstallParam](#installparam) | No | Parameters required for the installation. | | installParam | [InstallParam](#installparam) | No | Parameters required for the installation. For details about their default values, see [InstallParam](#installparam). |
**Return value** **Return value**
...@@ -252,6 +260,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -252,6 +260,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700036 | Failed to install the HSP because lacks appropriate permissions. | | 17700036 | Failed to install the HSP because lacks appropriate permissions. |
| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
| 17700041 | Failed to install because enterprise device management disallow install. | | 17700041 | Failed to install because enterprise device management disallow install. |
| 17700042 | Failed to install the HAP because of incorrect URI in the data proxy. |
| 17700043 | Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core). |
| 17700044 | Failed to install the HAP because the isolationMode configured is not supported. |
| 17700047 | Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode. |
**Example** **Example**
...@@ -310,6 +322,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -310,6 +322,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700004 | The specified user ID is not found. | | 17700004 | The specified user ID is not found. |
| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. |
| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. |
| 17700045 | Failed to uninstall because enterprise device management disallow uninstall. |
**Example** **Example**
...@@ -367,6 +380,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -367,6 +380,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| 17700001 | The specified bundle name is not found. | | 17700001 | The specified bundle name is not found. |
| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. |
| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. |
| 17700045 | Failed to uninstall because enterprise device management disallow uninstall. |
**Example** **Example**
...@@ -407,7 +421,7 @@ Uninstalls a bundle. This API uses a promise to return the result. ...@@ -407,7 +421,7 @@ Uninstalls a bundle. This API uses a promise to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Name of the target bundle. | | bundleName | string | Yes | Name of the target bundle. |
| installParam | [InstallParam](#installparam) | No | Parameters required for the uninstall. | | installParam | [InstallParam](#installparam) | No | Parameters required for the uninstall. For details about their default values, see [InstallParam](#installparam). |
**Return value** **Return value**
...@@ -422,9 +436,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -422,9 +436,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message | | ID| Error Message |
| -------- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ |
| 17700001 | The specified bundle name is not found. | | 17700001 | The specified bundle name is not found. |
| 17700004 | The specified userId is not existed. | | 17700004 | The specified user ID is not found. |
| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. | | 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. |
| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. |
| 17700045 | Failed to uninstall because enterprise device management disallow uninstall. |
**Example** **Example**
```ts ```ts
...@@ -577,7 +592,7 @@ Rolls back a bundle to the initial installation state. This API uses a promise t ...@@ -577,7 +592,7 @@ Rolls back a bundle to the initial installation state. This API uses a promise t
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Name of the target bundle. | | bundleName | string | Yes | Name of the target bundle. |
| installParam | [InstallParam](#installparam) | No | Parameters required for the recovery. | | installParam | [InstallParam](#installparam) | No | Parameters required for the recovery. For details about their default values, see [InstallParam](#installparam). |
**Return value** **Return value**
...@@ -755,12 +770,12 @@ Defines the parameters that need to be specified for bundle installation, uninst ...@@ -755,12 +770,12 @@ Defines the parameters that need to be specified for bundle installation, uninst
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------------------------ | ------------------------------ | ------------------ | ------------------ | | ------------------------------ | ------------------------------ | ------------------ | ------------------ |
| userId | number | No | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId) to obtain the user of the current process.| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. You can call [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId) to obtain the user ID of the current process.|
| installFlag | number | No | Installation flag. The value **0** means initial installation and **1** means overwrite installation.| | installFlag | number | No | Installation flag. The value **0** means initial installation and **1** means overwrite installation. The default value is **0**.|
| isKeepData | boolean | No | Whether to retain the data directory during bundle uninstall.| | isKeepData | boolean | No | Whether to retain the data directory during bundle uninstall. The default value is **false**.|
| hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. | | hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. By default, no value is passed. |
| crowdtestDeadline| number | No |End date of crowdtesting.| | crowdtestDeadline| number | No |End date of crowdtesting. The default value is **-1**.|
| sharedBundleDirPaths<sup>10+</sup> | Array\<String> | No|Paths of the shared bundle files.| | sharedBundleDirPaths<sup>10+</sup> | Array\<String> | No|Paths of the shared bundle files. By default, no value is passed.|
## UninstallParam<sup>10+</sup> ## UninstallParam<sup>10+</sup>
...@@ -773,4 +788,4 @@ Defines the parameters required for the uninstallation of a shared bundle. ...@@ -773,4 +788,4 @@ Defines the parameters required for the uninstallation of a shared bundle.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | ------ | ---- | ------------------------------------------------------------ | | ----------- | ------ | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Name of the shared bundle. | | bundleName | string | Yes | Name of the shared bundle. |
| versionCode | number | No | Version number of the shared bundle. If this parameter is not set, all shared bundles of the specified name are uninstalled.| | versionCode | number | No | Version number of the shared bundle. By default, no value is passed, and all shared bundles of the specified name are uninstalled.|
...@@ -767,7 +767,7 @@ Defines the **TagInfo** object, which provides information about the tag technol ...@@ -767,7 +767,7 @@ Defines the **TagInfo** object, which provides information about the tag technol
| uid<sup>9+</sup> | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| | uid<sup>9+</sup> | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| technology<sup>9+</sup> | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.| | technology<sup>9+</sup> | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.|
| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [technology](#taginfo).| | supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [technology](#taginfo).|
| extrasData<sup>9+</sup> | [PacMap](js-apis-inner-application-pacMap.md)[] | Yes| No| Extended attribute value of the tag technology.<br>**System API**: This is a system API.| | extrasData<sup>9+</sup> | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.<br>**System API**: This is a system API.|
| tagRfDiscId<sup>9+</sup> | number | Yes| No| ID allocated when the tag is discovered.<br>**System API**: This is a system API.| | tagRfDiscId<sup>9+</sup> | number | Yes| No| ID allocated when the tag is discovered.<br>**System API**: This is a system API.|
| remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.<br>**System API**: This is a system API.| | remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.<br>**System API**: This is a system API.|
......
...@@ -52,11 +52,11 @@ try { ...@@ -52,11 +52,11 @@ try {
overlay.setOverlayEnabled(moduleName, isEnabled) overlay.setOverlayEnabled(moduleName, isEnabled)
.then(() => { .then(() => {
console.info('setOverlayEnabled success'); console.info('setOverlayEnabled success');
}).catch((error) => { }).catch((err) => {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
}); });
} catch (error) { } catch (err) {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
} }
``` ```
...@@ -92,15 +92,15 @@ var moduleName = "feature"; ...@@ -92,15 +92,15 @@ var moduleName = "feature";
var isEnabled = false; var isEnabled = false;
try { try {
overlay.setOverlayEnabled(moduleName, isEnabled, (error, data) => { overlay.setOverlayEnabled(moduleName, isEnabled, (err, data) => {
if (error) { if (err) {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
return; return;
} }
console.info('setOverlayEnabled success'); console.info('setOverlayEnabled success');
}); });
} catch (error) { } catch (err) {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
} }
``` ```
...@@ -145,18 +145,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -145,18 +145,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
```ts ```ts
var bundleName = "com.example.myapplication_xxxxx"; var bundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature" var moduleName = "feature";
var isEnabled = false; var isEnabled = false;
try { try {
overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled) overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled)
.then((data) => { .then((data) => {
console.info('setOverlayEnabledByBundleName successfully'); console.info('setOverlayEnabledByBundleName successfully');
}).catch((error) => { }).catch((err) => {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
}); });
} catch (error) { } catch (err) {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
} }
``` ```
...@@ -196,19 +196,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -196,19 +196,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
```ts ```ts
var bundleName = "com.example.myapplication_xxxxx"; var bundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature" var moduleName = "feature";
var isEnabled = false; var isEnabled = false;
try { try {
overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (error, data) => { overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (err, data) => {
if (error) { if (err) {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
return; return;
} }
console.info('setOverlayEnabledByBundleName successfully'); console.info('setOverlayEnabledByBundleName successfully');
}); });
} catch (error) { } catch (err) {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
} }
``` ```
...@@ -245,14 +245,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -245,14 +245,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
var moduleName = "feature" var moduleName = "feature";
(async() => { (async() => {
try { try {
let overlayModuleInfo = await overlay.getOverlayModuleInfo(moduleName); let overlayModuleInfo = await overlay.getOverlayModuleInfo(moduleName);
console.log('overlayModuleInfo is ' + JSON.stringify(overlayModuleInfo)); console.log('overlayModuleInfo is ' + JSON.stringify(overlayModuleInfo));
} catch(err) { } catch(err) {
console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
})(); })();
``` ```
...@@ -279,23 +279,23 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -279,23 +279,23 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message | | ID| Error Message |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700002 | The specified module name is not found. | | 17700002 | The specified module name is not found. |
| 17700032 | he specified bundle does not contain any overlay module. | | 17700032 | The specified bundle does not contain any overlay module. |
| 17700033 | The specified module is not an overlay module. | | 17700033 | The specified module is not an overlay module. |
**Example** **Example**
```ts ```ts
var moduleName = "feature" var moduleName = "feature";
try { try {
overlay.getOverlayModuleInfo(moduleName, (error, data) => { overlay.getOverlayModuleInfo(moduleName, (err, data) => {
if (error) { if (err) {
console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return; return;
} }
console.log('overlayModuleInfo is ' + JSON.stringify(data)); console.log('overlayModuleInfo is ' + JSON.stringify(data));
}); });
} catch (error) { } catch (err) {
console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
``` ```
...@@ -331,14 +331,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -331,14 +331,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
var targetModuleName = "feature" var targetModuleName = "feature";
(async() => { (async() => {
try { try {
let overlayModuleInfos = await overlay.getTargetOverlayModuleInfos(targetModuleName); let overlayModuleInfos = await overlay.getTargetOverlayModuleInfos(targetModuleName);
console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos));
} catch(err) { } catch(err) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
})(); })();
``` ```
...@@ -370,17 +370,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -370,17 +370,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
var targetModuleName = "feature" var targetModuleName = "feature";
try { try {
overlay.getTargetOverlayModuleInfos(targetModuleName, (error, data) => { overlay.getTargetOverlayModuleInfos(targetModuleName, (err, data) => {
if (error) { if (err) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return; return;
} }
console.log('overlayModuleInfo is ' + JSON.stringify(data)); console.log('overlayModuleInfo is ' + JSON.stringify(data));
}); });
} catch (error) { } catch (err) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
``` ```
...@@ -401,7 +401,7 @@ Obtains the information about a module with the overlay feature in another appli ...@@ -401,7 +401,7 @@ Obtains the information about a module with the overlay feature in another appli
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- | | ----------- | ------ | ---- | --------------------------------------- |
| bundleName | string | Yes | Bundle name of the application. | | bundleName | string | Yes | Bundle name of the application. |
| moduleName | string | No | HAP name of the module with the overlay feature. If this parameter is not specified, the API obtains the information of all modules with the overlay feature in that application. | | moduleName | string | No | HAP name of the module with the overlay feature. By default, no value is passed, and the API obtains the information of all modules with the overlay feature in that application. |
**Return value** **Return value**
...@@ -424,14 +424,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -424,14 +424,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
```ts ```ts
var bundleName = "com.example.myapplication_xxxxx"; var bundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature" var moduleName = "feature";
(async() => { (async() => {
try { try {
let overlayModuleInfos = await overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName); let overlayModuleInfos = await overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName);
console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos));
} catch(err) { } catch(err) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
})(); })();
``` ```
...@@ -471,18 +471,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -471,18 +471,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
```ts ```ts
var bundleName = "com.example.myapplication_xxxxx"; var bundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature" var moduleName = "feature";
try { try {
overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (error, data) => { overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (err, data) => {
if (error) { if (err) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return; return;
} }
console.log('overlayModuleInfo is ' + JSON.stringify(data)); console.log('overlayModuleInfo is ' + JSON.stringify(data));
}); });
} catch (error) { } catch (err) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
``` ```
...@@ -512,9 +512,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -512,9 +512,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message | | ID| Error Message |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found. | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. |
| 17700032 | The specified bundle does not contain any overlay module. | | 17700032 | The specified bundle does not contain any overlay module. |
| 17700033 | The specified module is not an overlay module. |
**Example** **Example**
...@@ -522,15 +520,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -522,15 +520,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
var bundleName = "com.example.myapplication_xxxxx"; var bundleName = "com.example.myapplication_xxxxx";
try { try {
overlay.getOverlayModuleInfoByBundleName(bundleName, (error, data) => { overlay.getOverlayModuleInfoByBundleName(bundleName, (err, data) => {
if (error) { if (err) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return; return;
} }
console.log('overlayModuleInfo is ' + JSON.stringify(data)); console.log('overlayModuleInfo is ' + JSON.stringify(data));
}); });
} catch (error) { } catch (err) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
``` ```
...@@ -551,7 +549,7 @@ Obtains the information about modules with the overlay feature in another applic ...@@ -551,7 +549,7 @@ Obtains the information about modules with the overlay feature in another applic
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- | | ----------- | ------ | ---- | --------------------------------------- |
| targetBundleName | string | Yes | Bundle name of the application. | | targetBundleName | string | Yes | Bundle name of the application. |
| moduleName | string | No | HAP name of the target module, which is **targetModuleName** specified by modules with the overlay feature. If this parameter is not specified, the API obtains the information associated with all modules in that application. | | moduleName | string | No | HAP name of the target module, which is **targetModuleName** specified by modules with the overlay feature. By default, no value is passed, and the API obtains the information associated with all modules in that application. |
**Return value** **Return value**
...@@ -574,21 +572,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -574,21 +572,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
```ts ```ts
var targetBundleName = "com.example.myapplication_xxxxx"; var targetBundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature" var moduleName = "feature";
(async() => { (async() => {
try { try {
let overlayModuleInfos = await overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName); let overlayModuleInfos = await overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName);
console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos));
} catch(err) { } catch(err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
})(); })();
``` ```
## overlay.getTargetOverlayModuleInfosByBundleName ## overlay.getTargetOverlayModuleInfosByBundleName
getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback\<Array<OverlayModuleInfo>>): void; getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback&lt;Array&lt;OverlayModuleInfo&gt;&gt;): void;
Obtains the information about modules with the overlay feature in another application based on the target module name. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. Obtains the information about modules with the overlay feature in another application based on the target module name. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned.
...@@ -621,24 +619,24 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -621,24 +619,24 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
```ts ```ts
var targetBundleName = "com.example.myapplication_xxxxx"; var targetBundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature" var moduleName = "feature";
try { try {
overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (error, data) => { overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (err, data) => {
if (error) { if (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return; return;
} }
console.log('overlayModuleInfo is ' + JSON.stringify(data)); console.log('overlayModuleInfo is ' + JSON.stringify(data));
}); });
} catch (error) { } catch (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
``` ```
## overlay.getTargetOverlayModuleInfosByBundleName ## overlay.getTargetOverlayModuleInfosByBundleName
getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback\<Array<OverlayModuleInfo>>): void; getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback&lt;Array&lt;OverlayModuleInfo&gt;&gt;): void;
Obtains the information about all modules with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. Obtains the information about all modules with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned.
...@@ -662,8 +660,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -662,8 +660,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| ID| Error Message | | ID| Error Message |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found. | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. |
| 17700034 | The specified module is an overlay module. |
| 17700035 | The specified bundle is an overlay bundle. | | 17700035 | The specified bundle is an overlay bundle. |
**Example** **Example**
...@@ -672,15 +668,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ...@@ -672,15 +668,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
var targetBundleName = "com.example.myapplication_xxxxx"; var targetBundleName = "com.example.myapplication_xxxxx";
try { try {
overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (error, data) => { overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (err, data) => {
if (error) { if (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return; return;
} }
console.log('overlayModuleInfo is ' + JSON.stringify(data)); console.log('overlayModuleInfo is ' + JSON.stringify(data));
}); });
} catch (error) { } catch (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
} }
``` ```
......
...@@ -51,10 +51,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -51,10 +51,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9900001 | Caller information verification failed for a transient task. | | 9900001 | Caller information verification failed. |
| 9900002 | Transient task verification failed. | | 9900002 | Background task verification failed. |
**Example** **Example**
...@@ -76,7 +76,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -76,7 +76,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
``` ```
## backgroundTaskManager.getRemainingDelayTime:callback ## backgroundTaskManager.getRemainingDelayTime
getRemainingDelayTime(requestId: number, callback: AsyncCallback&lt;number&gt;): void getRemainingDelayTime(requestId: number, callback: AsyncCallback&lt;number&gt;): void
...@@ -99,10 +99,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -99,10 +99,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9900001 | Caller information verification failed for a transient task. | | 9900001 | Caller information verification failed. |
| 9900002 | Transient task verification failed. | | 9900002 | Background task verification failed. |
**Example** **Example**
...@@ -125,7 +125,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -125,7 +125,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
``` ```
## backgroundTaskManager.getRemainingDelayTime:promise ## backgroundTaskManager.getRemainingDelayTime
getRemainingDelayTime(requestId: number): Promise&lt;number&gt; getRemainingDelayTime(requestId: number): Promise&lt;number&gt;
...@@ -155,10 +155,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -155,10 +155,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9900001 | Caller information verification failed for a transient task. | | 9900001 | Caller information verification failed. |
| 9900002 | Transient task verification failed. | | 9900002 | Background task verification failed. |
**Example** **Example**
...@@ -200,10 +200,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -200,10 +200,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9900001 | Caller information verification failed for a transient task. | | 9900001 | Caller information verification failed. |
| 9900002 | Transient task verification failed. | | 9900002 | Background task verification failed. |
**Example** **Example**
...@@ -219,7 +219,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -219,7 +219,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
``` ```
## backgroundTaskManager.startBackgroundRunning:callback ## backgroundTaskManager.startBackgroundRunning
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void
...@@ -246,9 +246,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -246,9 +246,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9800005 | Continuous task verification failed. | | 9800005 | Background task verification failed. |
| 9800006 | Notification verification failed. | | 9800006 | Notification verification failed. |
| 9800007 | Task storage failed. | | 9800007 | Task storage failed. |
...@@ -297,7 +297,7 @@ export default class EntryAbility extends UIAbility { ...@@ -297,7 +297,7 @@ export default class EntryAbility extends UIAbility {
}; };
``` ```
## backgroundTaskManager.startBackgroundRunning:promise ## backgroundTaskManager.startBackgroundRunning
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt; startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;
...@@ -329,9 +329,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -329,9 +329,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9800005 | Continuous task verification failed. | | 9800005 | Background task verification failed. |
| 9800006 | Notification verification failed. | | 9800006 | Notification verification failed. |
| 9800007 | Task storage failed. | | 9800007 | Task storage failed. |
...@@ -376,7 +376,7 @@ export default class EntryAbility extends UIAbility { ...@@ -376,7 +376,7 @@ export default class EntryAbility extends UIAbility {
}; };
``` ```
## backgroundTaskManager.stopBackgroundRunning:callback ## backgroundTaskManager.stopBackgroundRunning
stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void
...@@ -399,9 +399,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -399,9 +399,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9800005 | Continuous task verification failed. | | 9800005 | Background task verification failed. |
| 9800006 | Notification verification failed. | | 9800006 | Notification verification failed. |
| 9800007 | Task storage failed. | | 9800007 | Task storage failed. |
...@@ -430,7 +430,7 @@ export default class EntryAbility extends UIAbility { ...@@ -430,7 +430,7 @@ export default class EntryAbility extends UIAbility {
}; };
``` ```
## backgroundTaskManager.stopBackgroundRunning:promise ## backgroundTaskManager.stopBackgroundRunning
stopBackgroundRunning(context: Context): Promise&lt;void&gt; stopBackgroundRunning(context: Context): Promise&lt;void&gt;
...@@ -460,9 +460,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -460,9 +460,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 9800005 | Continuous task verification failed. | | 9800005 | Background task verification failed. |
| 9800006 | Notification verification failed. | | 9800006 | Notification verification failed. |
| 9800007 | Task storage failed. | | 9800007 | Task storage failed. |
...@@ -513,9 +513,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -513,9 +513,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 18700001 | Caller information verification failed when applying for efficiency resources. | | 18700001 | Caller information verification failed. |
**Example** **Example**
...@@ -556,9 +556,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ...@@ -556,9 +556,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
| ---- | --------------------- | | ---- | --------------------- |
| 9800001 | Memory operation failed. | | 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. | | 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | | | 9800003 | Inner transact failed. | |
| 9800004 | System service operation failed. | | 9800004 | System service operation failed. |
| 18700001 | Caller information verification failed when applying for efficiency resources. | | 18700001 | Caller information verification failed. |
**Example** **Example**
......
...@@ -1549,10 +1549,10 @@ Provides the usage duration information of an application. ...@@ -1549,10 +1549,10 @@ Provides the usage duration information of an application.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------------------ | ------ | ---- | ---------------------------------------- | | ------------------------ | ------ | ---- | ---------------------------------------- |
| bundleName | string | Yes | Bundle name of the application. | | bundleName | string | No | Bundle name of the application. |
| abilityPrevAccessTime | number | Yes | Last time when the application was used. | | abilityPrevAccessTime | number | No | Last time when the application was used. |
| abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. | | abilityInFgTotalTime | number | No | Total time that the application runs in the foreground. |
| id | number | No | User ID.| | id | number | Yes | User ID.|
| abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.| | abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.|
| abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.| | abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.|
| fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.| | fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.|
...@@ -1570,9 +1570,9 @@ Provides information about an application event. ...@@ -1570,9 +1570,9 @@ Provides information about an application event.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------------------- | ------ | ---- | ---------------------------------------- | | --------------------- | ------ | ---- | ---------------------------------------- |
| bundleName | string | Yes | Bundle name of the application. | | bundleName | string | No | Bundle name of the application. |
| eventId | number | Yes | Application event type. | | eventId | number | No | Application event type. |
| eventOccurredTime | number | Yes | Timestamp when the application event occurs. | | eventOccurredTime | number | No | Timestamp when the application event occurs. |
| appGroup | number | No | Usage priority group of the application.| | appGroup | number | No | Usage priority group of the application.|
| indexOfLink | string | No | Shortcut ID.| | indexOfLink | string | No | Shortcut ID.|
| nameOfClass | string | No | Class name.| | nameOfClass | string | No | Class name.|
...@@ -1587,7 +1587,7 @@ Provides the usage duration information of an application. ...@@ -1587,7 +1587,7 @@ Provides the usage duration information of an application.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------------------------ | ---------------------------------------- | ---- | -------------- | | ------------------------------ | ---------------------------------------- | ---- | -------------- |
| [key: string]: BundleStatsInfo | [key: string]: [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| | [key: string] | [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.|
## DeviceEventStats ## DeviceEventStats
......
...@@ -89,7 +89,7 @@ Subscribes to data changes of the compass sensor. If this API is called multiple ...@@ -89,7 +89,7 @@ Subscribes to data changes of the compass sensor. If this API is called multiple
```js ```js
sensor.subscribeCompass({ sensor.subscribeCompass({
success: function(ret) { success: function(ret) {
console.log('get data direction:' + ret.direction); console.log('Get data direction:' + ret.direction);
}, },
fail: function(data, code) { fail: function(data, code) {
console.error('Subscription failed. Code: ' + code + '; Data: ' + data); console.error('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -133,7 +133,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip ...@@ -133,7 +133,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip
```js ```js
sensor.subscribeProximity({ sensor.subscribeProximity({
success: function(ret) { success: function(ret) {
console.log('get data distance:' + ret.distance); console.log('Get data distance:' + ret.distance);
}, },
fail: function(data, code) { fail: function(data, code) {
console.error('Subscription failed. Code: ' + code + '; Data: ' + data); console.error('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -177,7 +177,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu ...@@ -177,7 +177,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu
```js ```js
sensor.subscribeLight({ sensor.subscribeLight({
success: function(ret) { success: function(ret) {
console.log('get data intensity:' + ret.intensity); console.log('Get data intensity:' + ret.intensity);
}, },
fail: function(data, code) { fail: function(data, code) {
console.error('Subscription failed. Code: ' + code + '; Data: ' + data); console.error('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -223,7 +223,7 @@ Subscribes to data changes of the step counter sensor. If this API is called mul ...@@ -223,7 +223,7 @@ Subscribes to data changes of the step counter sensor. If this API is called mul
```js ```js
sensor.subscribeStepCounter({ sensor.subscribeStepCounter({
success: function(ret) { success: function(ret) {
console.log('get step value:' + ret.steps); console.log('Get step value:' + ret.steps);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data); console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -270,7 +270,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip ...@@ -270,7 +270,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip
```js ```js
sensor.subscribeBarometer({ sensor.subscribeBarometer({
success: function(ret) { success: function(ret) {
console.log('get data value:' + ret.pressure); console.log('Get data value:' + ret.pressure);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data); console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -318,7 +318,7 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi ...@@ -318,7 +318,7 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi
```js ```js
sensor.subscribeHeartRate({ sensor.subscribeHeartRate({
success: function(ret) { success: function(ret) {
console.log('get heartrate value:' + ret.heartRate); console.log('Get heartrate value:' + ret.heartRate);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data); console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -365,7 +365,7 @@ Subscribes to changes of the wearing state of a wearable device. If this API is ...@@ -365,7 +365,7 @@ Subscribes to changes of the wearing state of a wearable device. If this API is
```js ```js
sensor.subscribeOnBodyState({ sensor.subscribeOnBodyState({
success: function(ret) { success: function(ret) {
console.log('get on-body state value:' + ret.value); console.log('Get on-body state value:' + ret.value);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data); console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -409,7 +409,7 @@ Obtains the wearing state of a wearable device. ...@@ -409,7 +409,7 @@ Obtains the wearing state of a wearable device.
```js ```js
sensor.getOnBodyState({ sensor.getOnBodyState({
success: function(ret) { success: function(ret) {
console.log('on body state: ' + ret.value); console.log('On body state: ' + ret.value);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data); console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
...@@ -710,7 +710,7 @@ Defines the wearing state. ...@@ -710,7 +710,7 @@ Defines the wearing state.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ------------------------ | | -------- | ------------------------------------------- | ---- | ------------------------ |
| success | [OnBodyStateResponse](#onbodystateresponse) | No | Callback upon a successful API call.| | success | [OnBodyStateResponse](#onbodystateresponse) | Yes | Callback upon a successful API call.|
| fail | Function | No | Callback upon an API call failure.| | fail | Function | No | Callback upon an API call failure.|
| complete | Function | No | Called when the API call is complete.| | complete | Function | No | Called when the API call is complete.|
......
...@@ -4,8 +4,8 @@ The **userFileManager** module provides user data management capabilities, inclu ...@@ -4,8 +4,8 @@ The **userFileManager** module provides user data management capabilities, inclu
> **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. > - 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 ## Modules to Import
...@@ -49,11 +49,8 @@ let mgr = userFileManager.getUserFileMgr(context); ...@@ -49,11 +49,8 @@ let mgr = userFileManager.getUserFileMgr(context);
getPhotoAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void; getPhotoAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void;
Obtains image and video assets. This API uses an asynchronous callback to return the result. Obtains image and video assets. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO **Required permissions**: ohos.permission.READ_IMAGEVIDEO
...@@ -92,7 +89,6 @@ async function example() { ...@@ -92,7 +89,6 @@ async function example() {
} }
``` ```
### getPhotoAssets ### getPhotoAssets
getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;; getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
...@@ -141,6 +137,7 @@ async function example() { ...@@ -141,6 +137,7 @@ async function example() {
} }
} }
``` ```
### createPhotoAsset ### createPhotoAsset
createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback&lt;FileAsset&gt;): void; createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback&lt;FileAsset&gt;): void;
...@@ -261,7 +258,6 @@ async function example() { ...@@ -261,7 +258,6 @@ async function example() {
getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback&lt;FetchResult&lt;Album&gt;&gt;): void; getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback&lt;FetchResult&lt;Album&gt;&gt;): void;
Obtains image and video albums. This API uses an asynchronous callback to return the result. Obtains image and video albums. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -352,7 +348,6 @@ async function example() { ...@@ -352,7 +348,6 @@ async function example() {
getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback&lt;FetchResult&lt;PrivateAlbum&gt;&gt;): void; getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback&lt;FetchResult&lt;PrivateAlbum&gt;&gt;): void;
Obtains the system album. This API uses an asynchronous callback to return the result. Obtains the system album. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -424,7 +419,6 @@ async function example() { ...@@ -424,7 +419,6 @@ async function example() {
getAudioAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void; getAudioAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void;
Obtains audio assets. This API uses an asynchronous callback to return the result. Obtains audio assets. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -469,7 +463,6 @@ async function example() { ...@@ -469,7 +463,6 @@ async function example() {
getAudioAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;; getAudioAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
Obtains audio assets. This API uses a promise to return the result. Obtains audio assets. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -515,6 +508,7 @@ async function example() { ...@@ -515,6 +508,7 @@ async function example() {
} }
} }
``` ```
### delete ### delete
delete(uri: string, callback: AsyncCallback&lt;void&gt;): void; delete(uri: string, callback: AsyncCallback&lt;void&gt;): void;
...@@ -564,6 +558,7 @@ async function example() { ...@@ -564,6 +558,7 @@ async function example() {
}); });
} }
``` ```
### delete ### delete
delete(uri: string): Promise&lt;void&gt;; delete(uri: string): Promise&lt;void&gt;;
...@@ -1093,7 +1088,6 @@ Opens this file asset. This API uses an asynchronous callback to return the resu ...@@ -1093,7 +1088,6 @@ Opens this file asset. This API uses an asynchronous callback to return the resu
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
...@@ -1923,6 +1917,7 @@ async function example() { ...@@ -1923,6 +1917,7 @@ async function example() {
}); });
} }
``` ```
### getPhotoAssets ### getPhotoAssets
getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;; getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
...@@ -2106,6 +2101,7 @@ async function example() { ...@@ -2106,6 +2101,7 @@ async function example() {
} }
``` ```
### getPhotoAssets ### getPhotoAssets
getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;; getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
...@@ -2147,6 +2143,7 @@ async function example() { ...@@ -2147,6 +2143,7 @@ async function example() {
console.info('fetchResult.count = ', count); console.info('fetchResult.count = ', count);
} }
``` ```
### delete ### delete
delete(uri: string, callback: AsyncCallback&lt;void&gt;): void; delete(uri: string, callback: AsyncCallback&lt;void&gt;): void;
...@@ -2190,6 +2187,7 @@ async function example() { ...@@ -2190,6 +2187,7 @@ async function example() {
}); });
} }
``` ```
### delete ### delete
delete(uri: string): Promise&lt;void&gt;; delete(uri: string): Promise&lt;void&gt;;
...@@ -2280,6 +2278,7 @@ async function example() { ...@@ -2280,6 +2278,7 @@ async function example() {
}); });
} }
``` ```
### recover ### recover
recover(uri: string): Promise&lt;void&gt;; recover(uri: string): Promise&lt;void&gt;;
...@@ -2366,7 +2365,6 @@ Defines information about a registered device. ...@@ -2366,7 +2365,6 @@ Defines information about a registered device.
| networkId | string | Yes | No | Network ID of the registered device.| | networkId | string | Yes | No | Network ID of the registered device.|
| isOnline | boolean | Yes | No | Whether the registered device is online. | | isOnline | boolean | Yes | No | Whether the registered device is online. |
## FileType ## FileType
Enumerates media file types. Enumerates media file types.
...@@ -2390,8 +2388,6 @@ Enumerates the system album types. ...@@ -2390,8 +2388,6 @@ Enumerates the system album types.
| TYPE_FAVORITE | 0 | Favorites.| | TYPE_FAVORITE | 0 | Favorites.|
| TYPE_TRASH | 1 | Recycle bin.| | TYPE_TRASH | 1 | Recycle bin.|
## AudioKey ## AudioKey
Defines the key information about an audio file. Defines the key information about an audio file.
...@@ -2445,7 +2441,6 @@ Defines the key album information. ...@@ -2445,7 +2441,6 @@ Defines the key album information.
| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | | DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. |
| DATE_MODIFIED | date_modified | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| | DATE_MODIFIED | date_modified | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.|
## FetchOptions ## FetchOptions
Defines the options for fetching media files. Defines the options for fetching media files.
......
...@@ -586,11 +586,11 @@ The version of shared bundle is dependent on other applications. ...@@ -586,11 +586,11 @@ The version of shared bundle is dependent on other applications.
**Description** **Description**
Other applications depend on the shared library, causing the uninstallation to fail. Other applications depend on the shared library, causing the uninstall to fail.
**Possible Causes** **Possible Causes**
1. The version specified during the uninstallation is the latest version of the shared library, and the shared library is depended on by other applications. 1. The version specified during the uninstall is the latest version of the shared library, and the shared library is depended on by other applications.
2. No version is not specified during the uninstallation, meaning that all versions of the shared library will be uninstalled, and the shared library is depended on by other applications. 2. No version is not specified during the uninstall, meaning that all versions of the shared library will be uninstalled, and the shared library is depended on by other applications.
**Solution** **Solution**
1. Check whether the shared library to uninstall is depended on by other applications. 1. Check whether the shared library to uninstall is depended on by other applications.
...@@ -607,7 +607,7 @@ The specified shared bundle does not exist. ...@@ -607,7 +607,7 @@ The specified shared bundle does not exist.
The shared library to uninstall does not exist. The shared library to uninstall does not exist.
**Possible Causes** **Possible Causes**
1. The version specified during the uninstallation is different from the version of the shared library installed. 1. The version specified during the uninstall is different from the version of the shared library installed.
2. The shared library to uninstall is not installed. 2. The shared library to uninstall is not installed.
**Solution** **Solution**
...@@ -649,3 +649,118 @@ During application uninstall, the bundle name of an inter-application shared lib ...@@ -649,3 +649,118 @@ During application uninstall, the bundle name of an inter-application shared lib
**Solution** **Solution**
1. Use the **-s** parameter to specify the application to be uninstalled as a shared library application. 1. Use the **-s** parameter to specify the application to be uninstalled as a shared library application.
2. Use the **bundleName** and **versionCode** parameters in **UninstallParam** to specify the bundle name and version of the shared library to be uninstalled. 2. Use the **bundleName** and **versionCode** parameters in **UninstallParam** to specify the bundle name and version of the shared library to be uninstalled.
## 17700041 Application Installation Is Not Allowed by Enterprise Device Management
**Error Message**
Failed to install because enterprise device management disallow install.
**Description**
The installation of this application is prohibited by enterprise device management.
**Possible Causes**
The enterprise device management does not allow the installation of this application.
**Solution**
Check whether the application installation is prohibited by the enterprise device management.
## 17700042 Incorrect URI in the Data Proxy
**Error Message**
Failed to install the HAP because of incorrect URI in the data proxy.
**Description**
During application installation, the URI of the data proxy is incorrectly configured.
**Possible Causes**
1. The bundle name in the URI is different from that of the current application.
2. The URI is duplicate.
**Solution**
1. Change the bundle name in the URI to that of the current application.
2. Change duplicate URIs. Ensure that the URI of each data proxy is unique.
## 17700043 Incorrect Permission Configuration in the Data Proxy
**Error Message**
Failed to install the HAP because of low APL in the non-system data proxy (required APL: system_basic or system_core).
**Description**
During application installation, the permission level of the data proxy of a non-system application is too low. The permission level should be **system_basic** or **system_core**.
**Possible Causes**
1. No permission is configured for the data proxy of a non-system application.
1. The permission level of the data proxy of a non-system application is too low.
**Solution**
1. Configure the read and write permissions in the data proxy.
2. Change the read and write permissions in the data proxy and ensure that the permission level is **system_basic** or **system_core**.
## 17700044 Field isolationMode in the HAP Conflicts with the Device Isolation Mode
**Error Message**
Failed to install the HAP because the isolationMode configured is not supported.
**Description**
During application installation, the value of **isolationMode** in the HAP conflicts with the isolation mode of the device.
**Possible Causes**
1. The device supports the isolation mode (the value of **supportIsolationMode** is **true**), whereas the value of **isolationMode** in the HAP is **nonisolationOnly**.
2. The device does not support the isolation mode (the value of **supportIsolationMode** is **false**), whereas the value of **isolationMode** in the HAP is **isolationOnly**.
**Solution**
Set the **isolationMode** field in the HAP based on the isolation mode of the device.
## 17700045 Application Uninstall Is Not Allowed by Enterprise Device Management
**Error Message**
Failed to uninstall because enterprise device management disallow uninstall.
**Description**
The uninstall of this application is prohibited by enterprise device management.
**Possible Causes**
The enterprise device management does not allow the uninstall of this application.
**Solution**
Check whether the application uninstall is prohibited by the enterprise device management.
## 17700047 Application Version To Be Updated Is Not Later Than the Current Version
**Error Message**
Failed to install the HAP because the VersionCode to be updated is not greater than the current VersionCode.
**Description**
The version of the application to be updated is not later than the current version.
**Possible Causes**
1. The version number of the application to be updated is earlier than or equal to that of the current version number.
2. When **installFlag** is set to **NORMAL**, the version number of the application to be updated must be later than the installed version number.
**Solution**
1. Set the version number of the application to be later than the current version number.
2. If you want to update the application without changing the version number, set **installFlag** to **REPLACE_EXISTING**.
...@@ -4,9 +4,14 @@ ...@@ -4,9 +4,14 @@
> >
> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md). > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md).
The error codes of the file management subsystem consist of the following:<br>- Basic file I/O error codes<br>- User data management error codes<br>- User file access error codes<br>- Spatial statistics error codes The error codes of the file management subsystem include the following:
## Basic File I/O Error Codes - [Basic File IO Error Codes](#basic-file-io-error-codes)
- [User Data Management Error Codes](#user-data-management-error-code)
- [User File Access Error Codes](#user-file-access-error-codes)
- [Space Statistics Error Codes](#space-statistics-error-codes)
## Basic File IO Error Codes
### 13900001 Operation Not Permitted ### 13900001 Operation Not Permitted
...@@ -49,6 +54,7 @@ The process does not exist. ...@@ -49,6 +54,7 @@ The process does not exist.
**Solution** **Solution**
1. Check whether the process is killed unexpectedly. 1. Check whether the process is killed unexpectedly.
2. Check whether the service related to the process has started. 2. Check whether the service related to the process has started.
### 13900004 System Call Interrupted ### 13900004 System Call Interrupted
...@@ -64,6 +70,7 @@ The system call is interrupted by another thread. ...@@ -64,6 +70,7 @@ The system call is interrupted by another thread.
**Solution** **Solution**
1. Check the multi-thread code logic. 1. Check the multi-thread code logic.
2. Invoke the system call again. 2. Invoke the system call again.
### 13900005 I/O Error ### 13900005 I/O Error
...@@ -161,7 +168,9 @@ Out of memory ...@@ -161,7 +168,9 @@ Out of memory
A memory overflow occurs. A memory overflow occurs.
**Solution** **Solution**
1. Check the memory overhead. 1. Check the memory overhead.
2. Control the memory overhead. 2. Control the memory overhead.
### 13900012 Permission Denied ### 13900012 Permission Denied
...@@ -172,13 +181,14 @@ Permission denied ...@@ -172,13 +181,14 @@ Permission denied
**Possible Causes** **Possible Causes**
1. You do not have the permission to operate the file. 1. You do not have the permission to operate the file.
2. The file sandbox path is incorrect. 2. The file sandbox path is incorrect.
**Solution** **Solution**
1. Check that you have the permission to operate the file.
1. Check that the required permission is available.
2. Check that the file sandbox path is correct. 2. Check that the file sandbox path is correct.
### 13900013 Incorrect Address ### 13900013 Incorrect Address
...@@ -375,7 +385,7 @@ Seek is used in pipe or FIFO. ...@@ -375,7 +385,7 @@ Seek is used in pipe or FIFO.
**Solution** **Solution**
Check the use of seek. Check the use of **seek()**.
### 13900027 Read-Only File System ### 13900027 Read-Only File System
...@@ -460,6 +470,7 @@ The specified directory is not empty. ...@@ -460,6 +470,7 @@ The specified directory is not empty.
**Solution** **Solution**
1. Check the directory. 1. Check the directory.
2. Ensure that the directory is empty. 2. Ensure that the directory is empty.
### 13900033 Too Many Symbol Links ### 13900033 Too Many Symbol Links
...@@ -516,7 +527,7 @@ The device pointed to by the file descriptor is not a character stream device. ...@@ -516,7 +527,7 @@ The device pointed to by the file descriptor is not a character stream device.
**Solution** **Solution**
Check whether the file descriptor points to a stream device. Check whether the file descriptor points to a stream.
### 13900037 No Data Available ### 13900037 No Data Available
...@@ -599,7 +610,9 @@ Unknown error ...@@ -599,7 +610,9 @@ Unknown error
The error is unidentified. The error is unidentified.
**Solution** **Solution**
1. Call the API again. 1. Call the API again.
2. Restart the service. 2. Restart the service.
## User Data Management Error Codes ## User Data Management Error Codes
...@@ -636,7 +649,7 @@ Use the obtained URI. ...@@ -636,7 +649,7 @@ Use the obtained URI.
**Error Message** **Error Message**
Invalid file extension Invalid file name extension
**Possible Causes** **Possible Causes**
...@@ -660,7 +673,7 @@ The file is moved to the Recycle Bin. ...@@ -660,7 +673,7 @@ The file is moved to the Recycle Bin.
Check whether the file is in the Recycle Bin. Check whether the file is in the Recycle Bin.
## Spatial Statistics Error Codes ## Space Statistics Error Codes
### 13600001 IPC Failed ### 13600001 IPC Failed
...@@ -680,7 +693,7 @@ Check whether the service is started. ...@@ -680,7 +693,7 @@ Check whether the service is started.
**Error Message** **Error Message**
Not supported file system Not supported filesystem
**Possible Causes** **Possible Causes**
...@@ -767,11 +780,15 @@ Check whether the specified directory or node exists. ...@@ -767,11 +780,15 @@ Check whether the specified directory or node exists.
No such object No such object
**Possible Causes** **Possible Causes**
1. The specified volume ID is incorrect. 1. The specified volume ID is incorrect.
2. The specified bundle name is incorrect. 2. The specified bundle name is incorrect.
**Solution** **Solution**
1. Check whether the specified volume exists. 1. Check whether the specified volume exists.
2. Check whether the specified bundle name exists. 2. Check whether the specified bundle name exists.
### 13600009 Invalid User ID ### 13600009 Invalid User ID
...@@ -799,6 +816,7 @@ IPC error ...@@ -799,6 +816,7 @@ IPC error
**Possible Causes** **Possible Causes**
1. The server service does not exist. 1. The server service does not exist.
2. The extension mechanism is abnormal. 2. The extension mechanism is abnormal.
**Solution** **Solution**
...@@ -854,7 +872,9 @@ Check the data returned by the server. ...@@ -854,7 +872,9 @@ Check the data returned by the server.
Fail to register notification Fail to register notification
**Possible Causes** **Possible Causes**
1. The server service does not exist. 1. The server service does not exist.
2. The extension mechanism is abnormal. 2. The extension mechanism is abnormal.
**Solution** **Solution**
...@@ -868,7 +888,9 @@ Check that the server service exists. ...@@ -868,7 +888,9 @@ Check that the server service exists.
Fail to remove notification Fail to remove notification
**Possible Causes** **Possible Causes**
1. The server service does not exist. 1. The server service does not exist.
2. The extension mechanism is abnormal. 2. The extension mechanism is abnormal.
**Solution** **Solution**
...@@ -896,47 +918,11 @@ Check whether the specified Notify agent is registered. ...@@ -896,47 +918,11 @@ Check whether the specified Notify agent is registered.
Fail to notify agent Fail to notify agent
**Possible Causes** **Possible Causes**
1. The service does not exist. 1. The service does not exist.
2. The extension mechanism is abnormal. 2. The extension mechanism is abnormal.
**Solution** **Solution**
Check whether the client is normal. Check whether the client is normal.
## Error Code Adaptation
The APIs provided by the file management subsystem support exception handling.
Sample code for exception handling in a synchronous API:
```js
import fs from '@ohos.file.fs'
try {
let file = fs.openSync(path, fs.OpenMode.READ_ONLY);
} catch (err) {
console.error("openSync errCode:" + err.code + ", errMessage:" + err.message);
}
```
Sample code for exception handling in an asynchronous API (promise):
```js
import fs from '@ohos.file.fs'
try {
let file = await fs.open(path, fs.OpenMode.READ_ONLY);
} catch (err) {
console.error("open promise errCode:" + err.code + ", errMessage:" + err.message);
}
```
Sample code for exception handling in an asynchronous API (callback):
```js
import fs from '@ohos.file.fs'
try {
fs.open(path, fs.OpenMode.READ_ONLY, function(e, file){ // Asynchronous thread (such as the system call) errors are obtained via a callback.
if (e) {
console.error("open in async errCode:" + e.code + ", errMessage:" + e.message);
}
});
} catch (err) {// Main thread errors (such as invalid parameters) are obtained by try catch.
console.error("open callback errCode:" + err.code + ", errMessage:" + err.message);
}
```
# Application Development # Application Development
- [Application Development Overview](application-dev-guide.md) - [Application Development Overview](application-dev-guide.md)
- Quick Start - Quick Start
- Getting Started - Getting Started
...@@ -19,6 +20,16 @@ ...@@ -19,6 +20,16 @@
- [Multi-HAP Usage Rules](quick-start/multi-hap-rules.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) - [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 Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md)
- [Application Package Update Process](quick-start/application-package-update.md)
- Shared Package
- [Shared Package Overview](quick-start/shared-guide.md)
- [HAR](quick-start/har-package.md)
- HSP
- [In-Application HSP Development](quick-start/in-app-hsp.md)
- [Inter-Application HSP Development (for System Applications Only)](quick-start/cross-app-hsp.md)
- Quick Fix
- [Quick Fix Overview](quick-start/quickfix-principles.md)
- [CLI-based Quick Fix Development](quick-start/quickfix-debug.md)
- Application Configuration Files in Stage Model - Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md) - [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](quick-start/app-configuration-file.md) - [app.json5 Configuration File](quick-start/app-configuration-file.md)
...@@ -31,15 +42,40 @@ ...@@ -31,15 +42,40 @@
- [Resource Categories and Access](quick-start/resource-categories-and-access.md) - [Resource Categories and Access](quick-start/resource-categories-and-access.md)
- Learning ArkTS - Learning ArkTS
- [Getting Started with ArkTS](quick-start/arkts-get-started.md) - [Getting Started with ArkTS](quick-start/arkts-get-started.md)
- ArkTS Syntax (Declarative UI) - Basic Syntax
- [Basic UI Description](quick-start/arkts-basic-ui-description.md) - [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md)
- [Declarative UI Description](quick-start/arkts-declarative-ui-description.md)
- Custom Component
- [Creating a Custom Component](quick-start/arkts-create-custom-components.md)
- [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md)
- [\@Builder: Custom Builder Function](quick-start/arkts-builder.md)
- [\@BuilderParam: @Builder Function Reference](quick-start/arkts-builderparam.md)
- [\@Styles: Definition of Resusable Styles](quick-start/arkts-style.md)
- [\@Extend: Extension of Built-in Components](quick-start/arkts-extend.md)
- [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md)
- State Management - State Management
- [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md) - [State Management Overview](quick-start/arkts-state-management-overview.md)
- [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md) - Component State Management
- [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md) - [\@State: State Owned by Component](quick-start/arkts-state.md)
- [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md) - [\@Prop: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md)
- [Rendering Control](quick-start/arkts-rendering-control.md) - [\@Link: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md)
- [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md) - [\@Provide and \@Consume: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md)
- [\@Observed and \@ObjectLink: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md)
- Application State Management
- [Application State Management Overview](quick-start/arkts-application-state-management-overview.md)
- [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md)
- [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md)
- [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md)
- [Environment: Device Environment Query](quick-start/arkts-environment.md)
- Other State Management Features
- [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md)
- [\@Watch: Getting Notified of State Variable Changes](quick-start/arkts-watch.md)
- [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md)
- Rendering Control
- [Rendering Control Overview](quick-start/arkts-rendering-control-overview.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md)
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md)
- Development - Development
- Application Models - Application Models
- Application Model Overview - Application Model Overview
...@@ -59,11 +95,35 @@ ...@@ -59,11 +95,35 @@
- ExtensionAbility Component - ExtensionAbility Component
- [ExtensionAbility Component Overview](application-models/extensionability-overview.md) - [ExtensionAbility Component Overview](application-models/extensionability-overview.md)
- [ServiceExtensionAbility](application-models/serviceextensionability.md) - [ServiceExtensionAbility](application-models/serviceextensionability.md)
- [DataShareExtensionAbility (for System Applications Only)](application-models/datashareextensionability.md)
- [FormExtensionAbility (Widget)](application-models/widget-development-stage.md)
- [AccessibilityExtensionAbility](application-models/accessibilityextensionability.md) - [AccessibilityExtensionAbility](application-models/accessibilityextensionability.md)
- [EnterpriseAdminExtensionAbility](application-models/enterprise-extensionAbility.md)
- [InputMethodExtensionAbility](application-models/inputmethodextentionability.md) - [InputMethodExtensionAbility](application-models/inputmethodextentionability.md)
- [WindowExtensionAbility](application-models/windowextensionability.md) - [WindowExtensionAbility](application-models/windowextensionability.md)
- Service Widget Development in Stage Model
- [Service Widget Overview](application-models/service-widget-overview.md)
- Developing an ArkTS Widget
- [ArkTS Widget Working Principles](application-models/arkts-ui-widget-working-principles.md)
- [ArkTS Widget Related Modules](application-models/arkts-ui-widget-modules.md)
- ArkTS Widget Development
- [Creating an ArkTS Widget](application-models/arkts-ui-widget-creation.md)
- [Configuring Widget Configuration Files](application-models/arkts-ui-widget-configuration.md)
- [Widget Lifecycle Management](application-models/arkts-ui-widget-lifecycle.md)
- Widget Page Development
- [Widget Page Capability Overview](application-models/arkts-ui-widget-page-overview.md)
- [Using Animations in the Widget](application-models/arkts-ui-widget-page-animation.md)
- [Applying Custom Drawing in the Widget](application-models/arkts-ui-widget-page-custom-drawing.md)
- Widget Event Development
- [Widget Event Capability Overview](application-models/arkts-ui-widget-event-overview.md)
- [Redirecting to a Specified Page Through the Router Event](application-models/arkts-ui-widget-event-router.md)
- [Updating Widget Content Through FormExtensionAbility](application-models/arkts-ui-widget-event-formextensionability.md)
- [Updating Widget Content Through UIAbility](application-models/arkts-ui-widget-event-uiability.md)
- Widget Data Interaction
- [Widget Data Interaction Overview](application-models/arkts-ui-widget-interaction-overview.md)
- [Configuring a Widget to Update Periodically](application-models/arkts-ui-widget-update-by-time.md)
- [Updating Local and Online Images in the Widget](application-models/arkts-ui-widget-image-update.md)
- [Updating Widget Content by State](application-models/arkts-ui-widget-update-by-status.md)
- [Updating Widget Content by Widget Host (for System Applications Only)](application-models/arkts-ui-widget-content-update.md)
- [Developing a JS Widget](application-models/js-ui-widget-development.md)
- [AbilityStage Component Container](application-models/abilitystage.md) - [AbilityStage Component Container](application-models/abilitystage.md)
- [Context](application-models/application-context-stage.md) - [Context](application-models/application-context-stage.md)
- Want - Want
...@@ -78,22 +138,29 @@ ...@@ -78,22 +138,29 @@
- [Continuation Overview](application-models/inter-device-interaction-hop-overview.md) - [Continuation Overview](application-models/inter-device-interaction-hop-overview.md)
- [Cross-Device Migration (for System Applications Only)](application-models/hop-cross-device-migration.md) - [Cross-Device Migration (for System Applications Only)](application-models/hop-cross-device-migration.md)
- [Multi-device Collaboration (for System Applications Only)](application-models/hop-multi-device-collaboration.md) - [Multi-device Collaboration (for System Applications Only)](application-models/hop-multi-device-collaboration.md)
- IPC - [Subscribing to System Environment Variable Changes](application-models/subscribe-system-environment-variable-changes.md)
- [Process Model](application-models/process-model-stage.md) - Process Model
- [Process Model Overview](application-models/process-model-stage.md)
- Common Events - Common Events
- [Introduction to Common Events](application-models/common-event-overview.md) - [Introduction to Common Events](application-models/common-event-overview.md)
- [Subscribing to Common Events](application-models/common-event-subscription.md) - Common Event Subscription
- [Publishing Common Events](application-models/common-event-publish.md) - [Common Event Subscription Overview](application-models/common-event-subscription-overview.md)
- [Subscribing to Common Events in Dynamic Mode](application-models/common-event-subscription.md)
- [Subscribing to Common Events in Static Mode (for System Applications Only)](application-models/common-event-static-subscription.md)
- [Unsubscribing from Common Events](application-models/common-event-unsubscription.md) - [Unsubscribing from Common Events](application-models/common-event-unsubscription.md)
- [Publishing Common Events](application-models/common-event-publish.md)
- [Removing Sticky Common Events](application-models/common-event-remove-sticky.md)
- [Background Services](application-models/background-services.md) - [Background Services](application-models/background-services.md)
- Inter-Thread Communication - Thread Model
- [Thread Model](application-models/thread-model-stage.md) - [Thread Model Overview](application-models/thread-model-stage.md)
- [Using Emitter for Inter-Thread Communication](application-models/itc-with-emitter.md) - [Using Emitter for Inter-Thread Communication](application-models/itc-with-emitter.md)
- [Using Worker for Inter-Thread Communication](application-models/itc-with-worker.md) - [Using Worker for Inter-Thread Communication](application-models/itc-with-worker.md)
- Mission Management - Mission Management
- [Mission Management Scenarios](application-models/mission-management-overview.md) - [Mission Management Scenarios](application-models/mission-management-overview.md)
- [Mission Management and Launch Type](application-models/mission-management-launch-type.md) - [Mission and Launch Type](application-models/mission-management-launch-type.md)
- [Page Stack and MissionList](application-models/page-mission-stack.md) - [Page Stack and MissionList](application-models/page-mission-stack.md)
- [Setting the Icon and Name of a Mission Snapshot](application-models/mission-set-icon-name-for-task-snapshot.md)
- [Application Configuration File (Stage Model)](application-models/config-file-stage.md)
- FA Model Development - FA Model Development
- [FA Model Development Overview](application-models/fa-model-development-overview.md) - [FA Model Development Overview](application-models/fa-model-development-overview.md)
- FA Mode Application Components - FA Mode Application Components
...@@ -129,14 +196,16 @@ ...@@ -129,14 +196,16 @@
- [Widget Development](application-models/widget-development-fa.md) - [Widget Development](application-models/widget-development-fa.md)
- [Context](application-models/application-context-fa.md) - [Context](application-models/application-context-fa.md)
- [Want](application-models/want-fa.md) - [Want](application-models/want-fa.md)
- IPC - [Component Startup Rules (FA Model)](application-models/component-startup-rules-fa.md)
- [Process Model](application-models/process-model-fa.md) - Process Model
- [Process Model Overview](application-models/process-model-fa.md)
- [Common Events](application-models/common-event-fa.md) - [Common Events](application-models/common-event-fa.md)
- [Background Services](application-models/rpc.md) - [Background Services](application-models/rpc.md)
- Inter-Thread Communication - Thread Model
- [Thread Model](application-models/thread-model-fa.md) - [Thread Model Overview](application-models/thread-model-fa.md)
- [Inter-Thread Communication](application-models/itc-fa-overview.md) - [Inter-Thread Communication](application-models/itc-fa-overview.md)
- [Mission Management](application-models/mission-management-fa.md) - [Mission Management](application-models/mission-management-fa.md)
- [Application Configuration File (FA Model)](application-models/config-file-fa.md)
- Development of Component Interaction Between the FA Model and Stage Model - Development of Component Interaction Between the FA Model and Stage Model
- [Component Interaction Between the FA Model and Stage Model](application-models/fa-stage-interaction-overview.md) - [Component Interaction Between the FA Model and Stage Model](application-models/fa-stage-interaction-overview.md)
- [Starting a UIAbility from the FA Model](application-models/start-uiability-from-fa.md) - [Starting a UIAbility from the FA Model](application-models/start-uiability-from-fa.md)
...@@ -172,32 +241,64 @@ ...@@ -172,32 +241,64 @@
- [Storage Switching](application-models/storage-switch.md) - [Storage Switching](application-models/storage-switch.md)
- UI Development - UI Development
- [ArkUI Overview](ui/arkui-overview.md) - [ArkUI Overview](ui/arkui-overview.md)
- ArkTS-based Declarative Development Paradigm - UI Development (ArkTS-based Declarative Development Paradigm)
- [Overview](ui/ui-ts-overview.md) - [UI Development (ArkTS-based Declarative Development Paradigm) Overview](ui/arkts-ui-development-overview.md)
- [Declarative UI Development Guidelines](ui/ui-ts-developing-intro.md) - Layout Development
- Declarative UI Development Examples - [Layout Overview](ui/arkts-layout-development-overview.md)
- [Creating a Simple Page](ui/ui-ts-creating-simple-page.md) - Building a Layout
- Building a Comprehensive Example - [Linear Layout](ui/arkts-layout-development-linear.md)
- [Building a Food Data Model](ui/ui-ts-building-data-model.md) - [Stack Layout](ui/arkts-layout-development-stack-layout.md)
- [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md) - [Flex Layout](ui/arkts-layout-development-flex-layout.md)
- [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md) - [Relative Layout](ui/arkts-layout-development-relative-layout.md)
- [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md) - [Responsive Grid Layout](ui/arkts-layout-development-grid-layout.md)
- Adding a Splash Screen Animation - [Media Query](ui/arkts-layout-development-media-query.md)
- [Using the Drawing Feature](ui/ui-ts-drawing-feature.md) - [Creating a List](ui/arkts-layout-development-create-list.md)
- [Using the Animation Feature](ui/ui-ts-animation-feature.md) - [Creating a Grid](ui/arkts-layout-development-create-grid.md)
- [Common Components](ui/ui-ts-components-intro.md) - [Creating a Swiper](ui/arkts-layout-development-create-looping.md)
- Common Layout Development - [Improving Layout Performance](ui/arkts-layout-development-performance-boost.md)
- Adaptive Layouts - Adding a Component
- [Linear Layout](ui/ui-ts-layout-linear.md) - Adding a Common Component
- [Statck Layout](ui/ui-ts-layout-stack.md) - [Button](ui/arkts-common-components-button.md)
- [Flex Layout](ui/ui-ts-layout-flex.md) - [Radio Button](ui/arkts-common-components-radio-button.md)
- [Grid Layout](ui/ui-ts-layout-grid.md) - [Toggle](ui/arkts-common-components-switch.md)
- Responsive Layouts - [Progress Indicator](ui/arkts-common-components-progress-indicator.md)
- [Grid Layout](ui/ui-ts-layout-grid-container-new.md) - [Text Display](ui/arkts-common-components-text-display.md)
- [Media Query](ui/ui-ts-layout-mediaquery.md) - [Text Input](ui/arkts-common-components-text-input.md)
- [Custom Component Lifecycle Callbacks](ui/ui-ts-custom-component-lifecycle-callbacks.md) - [Custom Dialog Box](ui/arkts-common-components-custom-dialog.md)
- [Web Component Development](ui/ui-ts-components-web.md) - [Video Playback](ui/arkts-common-components-video-player.md)
- [Recommendations for Improving Performance](ui/ui-ts-performance-improvement-recommendation.md) - [XComponent](ui/arkts-common-components-xcomponent.md)
- Adding a Bubble and Menu
- [Bubble](ui/arkts-popup-and-menu-components-popup.md)
- [Menu](ui/arkts-popup-and-menu-components-menu.md)
- Setting Page Routing and Component Navigation
- [Page Routing](ui/arkts-routing.md)
- Component Navigation
- [Navigation](ui/arkts-navigation-navigation.md)
- [Tabs](ui/arkts-navigation-tabs.md)
- Using Graphics
- [Displaying Images](ui/arkts-graphics-display.md)
- [Drawing Geometric Shapes](ui/arkts-geometric-shape-drawing.md)
- [Drawing Custom Graphics on the Canvas](ui/arkts-drawing-customization-on-canvas.md)
- Using Animation
- [Animation Overview](ui/arkts-animation-overview.md)
- Animation Within a Page
- [Layout Update Animation](ui/arkts-layout-update-animation.md)
- [Transition Animation Within a Component](ui/arkts-transition-animation-within-component.md)
- [Spring Curve Animation](ui/arkts-spring-animation.md)
- Animation Between Pages
- [Zoom Animation](ui/arkts-zoom-animation.md)
- [Page Transition Animation](ui/arkts-page-transition-animation.md)
- Using Interaction Events
- [Interaction Event Overview](ui/arkts-event-overview.md)
- Universal Events
- [Touchscreen Event](ui/arkts-common-events-touch-screen-event.md)
- [Keyboard and Mouse Event](ui/arkts-common-events-device-input-event.md)
- [Focus Event](ui/arkts-common-events-focus-event.md)
- Gesture Events
- [Gesture Binding](ui/arkts-gesture-events-binding.md)
- [Single Gesture](ui/arkts-gesture-events-single-gesture.md)
- [Combined Gestures](ui/arkts-gesture-events-combined-gestures.md)
- [Recommendations for Improving Performance](ui/arkts-performance-improvement-recommendation.md)
- UI Development with JavaScript-compatible Web-like Development Paradigm - UI Development with JavaScript-compatible Web-like Development Paradigm
- [Overview](ui/ui-js-overview.md) - [Overview](ui/ui-js-overview.md)
- Framework - Framework
...@@ -270,10 +371,27 @@ ...@@ -270,10 +371,27 @@
- [Animation Effect](ui/ui-js-animate-dynamic-effects.md) - [Animation Effect](ui/ui-js-animate-dynamic-effects.md)
- [Animation Frame](ui/ui-js-animate-frame.md) - [Animation Frame](ui/ui-js-animate-frame.md)
- [Custom Components](ui/ui-js-custom-components.md) - [Custom Components](ui/ui-js-custom-components.md)
- Web
- [Web Component Overview](web/web-component-overview.md)
- [Loading Pages by Using the Web Component](web/web-page-loading-with-web-components.md)
- Setting Basic Attributes and Events
- [Setting the Dark Mode](web/web-set-dark-mode.md)
- [Uploading Files](web/web-file-upload.md)
- [Opening Pages in a New Window](web/web-open-in-new-window.md)
- [Managing Location Permissions](web/web-geolocation-permission.md)
- Using Frontend Page JavaScript Code on the Application
- [Invoking Frontend Page Functions on the Application](web/web-in-app-frontend-page-function-invoking.md)
- [Invoking Application Functions on the Frontend Page](web/web-in-page-app-function-invoking.md)
- [Establishing a Data Channel Between the Application and the Frontend Page](web/web-app-page-data-channel.md)
- [Managing Page Redirection and Browsing History Navigation](web/web-redirection-and-browsing-history-mgmt.md)
- [Managing Cookies and Data Storage](web/web-cookie-and-data-storage-mgmt.md)
- [Customizing Page Request Responses](web/web-resource-interception-request-mgmt.md)
- [Debugging Frontend Pages by Using DevTools](web/web-debugging-with-devtools.md)
- Notification - Notification
- [Notification Overview](notification/notification-overview.md) - [Notification Overview](notification/notification-overview.md)
- [Notification Subscription (for System Applications Only)](notification/notification-subscription.md) - [Notification Subscription (for System Applications Only)](notification/notification-subscription.md)
- [Enabling Notification](notification/notification-enable.md) - [Enabling Notification](notification/notification-enable.md)
- [Notification Badge](notification/notification-badge.md)
- Publishing a Notification - Publishing a Notification
- [Publishing a Basic Notification](notification/text-notification.md) - [Publishing a Basic Notification](notification/text-notification.md)
- [Publishing a Progress Notification](notification/progress-bar-notification.md) - [Publishing a Progress Notification](notification/progress-bar-notification.md)
...@@ -287,30 +405,64 @@ ...@@ -287,30 +405,64 @@
- [WebGL Overview](webgl/webgl-overview.md) - [WebGL Overview](webgl/webgl-overview.md)
- [WebGL Development](webgl/webgl-guidelines.md) - [WebGL Development](webgl/webgl-guidelines.md)
- Media - Media
- [Media Application Overview](media/media-application-overview.md)
- Audio and Video - Audio and Video
- [Audio Overview](media/audio-overview.md) - [Audio and Video Overview](media/av-overview.md)
- [Audio Rendering Development](media/audio-renderer.md) - [AVPlayer and AVRecorder](media/avplayer-avrecorder-overview.md)
- [Audio Stream Management Development](media/audio-stream-manager.md) - Audio Playback
- [Audio Capture Development](media/audio-capturer.md) - [Audio Playback Overview](media/audio-playback-overview.md)
- [OpenSL ES Audio Playback Development](media/opensles-playback.md) - [Using AVPlayer for Audio Playback](media/using-avplayer-for-playback.md)
- [OpenSL ES Audio Recording Development](media/opensles-capture.md) - [Using AudioRenderer for Audio Playback](media/using-audiorenderer-for-playback.md)
- [Audio Interruption Mode Development](media/audio-interruptmode.md) - [Using OpenSL ES for Audio Playback](media/using-opensl-es-for-playback.md)
- [Volume Management Development](media/audio-volume-manager.md) - [Using TonePlayer for Audio Playback (for System Applications Only)](media/using-toneplayer-for-playback.md)
- [Audio Routing and Device Management Development](media/audio-routing-manager.md) - [Audio Playback Concurrency Policy](media/audio-playback-concurrency.md)
- [AVPlayer Development (Recommended)](media/avplayer-playback.md) - [Volume Management](media/volume-management.md)
- [AVRecorder Development (Recommended)](media/avrecorder.md) - [Audio Playback Stream Management](media/audio-playback-stream-management.md)
- [Audio Playback Development (To Be Deprecated Soon)](media/audio-playback.md) - [Audio Output Device Management](media/audio-output-device-management.md)
- [Audio Recording Development (To Be Deprecated Soon)](media/audio-recorder.md) - [Distributed Audio Playback (for System Applications Only)](media/distributed-audio-playback.md)
- [Video Playback Development (To Be Deprecated Soon)](media/video-playback.md) - Audio Recording
- [Video Recording Development (To Be Deprecated Soon)](media/video-recorder.md) - [Audio Recording Overview](media/audio-recording-overview.md)
- AVSession - [Using AVRecorder for Audio Recording](media/using-avrecorder-for-recording.md)
- [Using AudioCapturer for Audio Recording](media/using-audiocapturer-for-recording.md)
- [Using OpenSL ES for Audio Recording](media/using-opensl-es-for-recording.md)
- [Microphone Management](media/mic-management.md)
- [Audio Recording Stream Management](media/audio-recording-stream-management.md)
- [Audio Input Device Management](media/audio-input-device-management.md)
- Audio Call
- [Audio Call Overview](media/audio-call-overview.md)
- [Developing Audio Call](media/audio-call-development.md)
- [Video Playback](media/video-playback.md)
- [Video Recording](media/video-recording.md)
- AVSession (for System Applications Only)
- [AVSession Overview](media/avsession-overview.md) - [AVSession Overview](media/avsession-overview.md)
- [AVSession Development](media/avsession-guidelines.md) - Local AVSession
- [Local AVSession Overview](media/local-avsession-overview.md)
- [AVSession Provider](media/using-avsession-developer.md)
- [AVSession Controller](media/using-avsession-controller.md)
- Distributed AVSession
- [Distributed AVSession Overview](media/distributed-avsession-overview.md)
- [Using Distributed AVSession](media/using-distributed-avsession.md)
- Camera (for System Applications Only)
- [Camera Overview](media/camera-overview.md)
- Camera Development
- [Camera Development Preparations](media/camera-preparation.md)
- [Device Input Management](media/camera-device-input.md)
- [Session Management](media/camera-session-management.md)
- [Camera Preview](media/camera-preview.md)
- [Camera Photographing](media/camera-shooting.md)
- [Camera Recording](media/camera-recording.md)
- [Camera Metadata](media/camera-metadata.md)
- Best Practices
- [Camera Photographing Sample](media/camera-shooting-case.md)
- [Camera Recording Sample](media/camera-recording-case.md)
- Image - Image
- [Image Development](media/image.md) - [Image Overview](media/image-overview.md)
- Camera - [Image Decoding](media/image-decoding.md)
- [Camera Development](media/camera.md) - Image Processing
- [Distributed Camera Development](media/remote-camera.md) - [Image Transformation](media/image-transformation.md)
- [Pixel Map Operation](media/image-pixelmap-operation.md)
- [Image Encoding](media/image-encoding.md)
- [Image Tool](media/image-tool.md)
- Security - Security
- Access Control - Access Control
- [Access Control Overview](security/accesstoken-overview.md) - [Access Control Overview](security/accesstoken-overview.md)
...@@ -323,6 +475,7 @@ ...@@ -323,6 +475,7 @@
- Key Management - Key Management
- [HUKS Overview](security/huks-overview.md) - [HUKS Overview](security/huks-overview.md)
- [HUKS Development](security/huks-guidelines.md) - [HUKS Development](security/huks-guidelines.md)
- [HUKS Cipher Algorithm Specifications](security/huks-appendix.md)
- Crypto Framework - Crypto Framework
- [Crypto Framework Overview](security/cryptoFramework-overview.md) - [Crypto Framework Overview](security/cryptoFramework-overview.md)
- [Crypto Framework Development](security/cryptoFramework-guidelines.md) - [Crypto Framework Development](security/cryptoFramework-guidelines.md)
...@@ -339,10 +492,10 @@ ...@@ -339,10 +492,10 @@
- [HTTP Data Request](connectivity/http-request.md) - [HTTP Data Request](connectivity/http-request.md)
- [WebSocket Connection](connectivity/websocket-connection.md) - [WebSocket Connection](connectivity/websocket-connection.md)
- [Socket Connection](connectivity/socket-connection.md) - [Socket Connection](connectivity/socket-connection.md)
- [Network Policy Management](connectivity/net-policy-management.md)
- [Network Sharing](connectivity/net-sharing.md) - [Network Sharing](connectivity/net-sharing.md)
- [Ethernet Connection](connectivity/net-ethernet.md) - [Ethernet Connection](connectivity/net-ethernet.md)
- [Network Connection Management](connectivity/net-connection-manager.md) - [Network Connection Management](connectivity/net-connection-manager.md)
- [MDNS Management](connectivity/net-mdns.md)
- IPC & RPC - IPC & RPC
- [IPC & RPC Overview](connectivity/ipc-rpc-overview.md) - [IPC & RPC Overview](connectivity/ipc-rpc-overview.md)
- [IPC & RPC Development](connectivity/ipc-rpc-development-guideline.md) - [IPC & RPC Development](connectivity/ipc-rpc-development-guideline.md)
...@@ -352,30 +505,48 @@ ...@@ -352,30 +505,48 @@
- [Call Service Development](telephony/telephony-call.md) - [Call Service Development](telephony/telephony-call.md)
- [SMS Service Development](telephony/telephony-sms.md) - [SMS Service Development](telephony/telephony-sms.md)
- Data Management - Data Management
- Distributed Data Service - [Data Management Overview](database/data-mgmt-overview.md)
- [Distributed Data Service Overview](database/database-mdds-overview.md) - Application Data Persistence
- [Distributed Data Service Development](database/database-mdds-guidelines.md) - [Overview of Application Data Persistence](database/app-data-persistence-overview.md)
- Relational Database - [Persisting Preferences Data](database/data-persistence-by-preferences.md)
- [RDB Overview](database/database-relational-overview.md) - [Persisting KV Store Data](database/data-persistence-by-kv-store.md)
- [RDB Development](database/database-relational-guidelines.md) - [Persisting RDB Store Data](database/data-persistence-by-rdb-store.md)
- Preferences - Distributed Application Data Synchronization
- [Preferences Overview](database/database-preference-overview.md) - [Distributed Application Data Synchronization Overview](database/sync-app-data-across-devices-overview.md)
- [Preferences Development](database/database-preference-guidelines.md) - [Cross-Device Synchronization of KV Stores](database/data-sync-of-kv-store.md)
- Distributed Data Object - [Cross-Device Synchronization of RDB Stores](database/data-sync-of-rdb-store.md)
- [Distributed Data Object Overview](database/database-distributedobject-overview.md) - [Cross-Device Synchronization of Distributed Data Objects](database/data-sync-of-distributed-data-object.md)
- [Distributed Data Object Development](database/database-distributedobject-guidelines.md) - Data Reliability and Security
- Data Share - [Data Reliability and Security Overview](database/data-reliability-security-overview.md)
- [DataShare Overview](database/database-datashare-overview.md) - [Database Backup and Restoration](database/data-backup-and-restore.md)
- [DataShare Development](database/database-datashare-guidelines.md) - [Database Encryption](database/data-encryption.md)
- [Access Control by Device and Data Level](database/access-control-by-device-and-data-level.md)
- Cross-Application Data Sharing (for System Applications Only)
- [Cross-Application Data Sharing Overview](database/share-device-data-across-apps-overview.md)
- [Sharing Data Using DataShareExtensionAbility](database/share-data-by-datashareextensionability.md)
- [Sharing Data in Silent Access](database/share-data-by-silent-access.md)
- File Management - File Management
- MediaLibrary - [File Management Overview](file-management/file-management-overview.md)
- [MediaLibrary Development Overview](file-management/medialibrary-overview.md) - Application File
- [Media Asset Management](file-management/medialibrary-resource-guidelines.md) - [Application File Overview](file-management/app-file-overview.md)
- [File Path Management](file-management/medialibrary-filepath-guidelines.md) - [Application Sandbox Directory](file-management/app-sandbox-directory.md)
- [Album Management](file-management/medialibrary-album-guidelines.md) - Application File Access and Management
- File Access Framework - [Accessing Application Files](file-management/app-file-access.md)
- [File Access Framework Overview](file-management/file-access-framework-overview.md) - [Uploading and Downloading Application Files](file-management/app-file-upload-download.md)
- [FilePicker Guide](file-management/filepicker-guidelines.md) - [Obtaining Application and File System Space Statistics](file-management/app-fs-space-statistics.md)
- [Sending Files to an Application Sandbox](file-management/send-file-to-app-sandbox.md)
- [Sharing an Application File](file-management/share-app-file.md)
- User File
- [User File Overview](file-management/user-file-overview.md)
- Selecting and Saving User Files (FilePicker)
- [Selecting User Files](file-management/select-user-file.md)
- [Saving User Files](file-management/save-user-file.md)
- [Developing a FileManager Application (Available Only for System Applications)](file-management/dev-user-file-manager.md)
- [Managing External Storage Devices (Available Only for System Applications)](file-management/manage-external-storage.md)
- Distributed File System
- [Distributed File System Overview](file-management/distributed-fs-overview.md)
- [Setting the Security Level of a Distributed File](file-management/set-security-label.md)
- [Accessing Files Across Devices](file-management/file-access-across-devices.md)
- Background Task Management - Background Task Management
- Background Task - Background Task
- [Background Task Management Overview](task-management/background-task-overview.md) - [Background Task Management Overview](task-management/background-task-overview.md)
...@@ -414,9 +585,13 @@ ...@@ -414,9 +585,13 @@
- [Development of Application Event Logging](dfx/hiappevent-guidelines.md) - [Development of Application Event Logging](dfx/hiappevent-guidelines.md)
- [Development of Performance Tracing](dfx/hitracemeter-guidelines.md) - [Development of Performance Tracing](dfx/hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md) - [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md)
- [HiLog Development (Native)](dfx/hilog-guidelines.md)
- Error Management - Error Management
- [Development of Error Manager](dfx/errormanager-guidelines.md) - [Development of Error Manager](dfx/errormanager-guidelines.md)
- [Development of Application Recovery](dfx/apprecovery-guidelines.md) - [Development of Application Recovery](dfx/apprecovery-guidelines.md)
- Log Analysis
- [Application Freeze (appfreeze) Log Analysis](dfx/appfreeze-guidelines.md)
- [cppcrash Log Analysis](dfx/cppcrash-guidelines.md)
- Internationalization - Internationalization
- [Internationalization Overview](internationalization/international-overview.md) - [Internationalization Overview](internationalization/international-overview.md)
- [Internationalization Development (intl)](internationalization/intl-guidelines.md) - [Internationalization Development (intl)](internationalization/intl-guidelines.md)
...@@ -441,8 +616,10 @@ ...@@ -441,8 +616,10 @@
- Packing and Unpacking Tools - Packing and Unpacking Tools
- [Packing Tools](tools/packing-tool.md) - [Packing Tools](tools/packing-tool.md)
- [Unpacking Tools](tools/unpacking-tool.md) - [Unpacking Tools](tools/unpacking-tool.md)
- [Common Event Manager](tools/anm-tool.md)
- [Advanced Notification Manager](tools/cem-tool.md) - [Advanced Notification Manager](tools/cem-tool.md)
- [Common Event Manager](tools/anm-tool.md)
- [restool](tools/restool.md)
- [LLDB Usage Guide](tools/lldb-tool.md)
- Hands-On Tutorials - Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md)
- [Codelabs](https://gitee.com/openharmony/codelabs) - [Codelabs](https://gitee.com/openharmony/codelabs)
...@@ -462,6 +639,7 @@ ...@@ -462,6 +639,7 @@
- [Mouse Event](reference/arkui-ts/ts-universal-mouse-key.md) - [Mouse Event](reference/arkui-ts/ts-universal-mouse-key.md)
- [Component Area Change Event](reference/arkui-ts/ts-universal-component-area-change-event.md) - [Component Area Change Event](reference/arkui-ts/ts-universal-component-area-change-event.md)
- [Visible Area Change Event](reference/arkui-ts/ts-universal-component-visible-area-change-event.md) - [Visible Area Change Event](reference/arkui-ts/ts-universal-component-visible-area-change-event.md)
- [Custom Keyboard Shortcuts](reference/arkui-ts/ts-universal-events-keyboardshortcut.md)
- Universal Attributes - Universal Attributes
- [Size](reference/arkui-ts/ts-universal-attributes-size.md) - [Size](reference/arkui-ts/ts-universal-attributes-size.md)
- [Location](reference/arkui-ts/ts-universal-attributes-location.md) - [Location](reference/arkui-ts/ts-universal-attributes-location.md)
...@@ -478,7 +656,6 @@ ...@@ -478,7 +656,6 @@
- [Transformation](reference/arkui-ts/ts-universal-attributes-transformation.md) - [Transformation](reference/arkui-ts/ts-universal-attributes-transformation.md)
- [Image Effect Configuration](reference/arkui-ts/ts-universal-attributes-image-effect.md) - [Image Effect Configuration](reference/arkui-ts/ts-universal-attributes-image-effect.md)
- [Shape Clipping](reference/arkui-ts/ts-universal-attributes-sharp-clipping.md) - [Shape Clipping](reference/arkui-ts/ts-universal-attributes-sharp-clipping.md)
- [Text Style](reference/arkui-ts/ts-universal-attributes-text-style.md)
- [Grid](reference/arkui-ts/ts-universal-attributes-grid.md) - [Grid](reference/arkui-ts/ts-universal-attributes-grid.md)
- [Gradient Color](reference/arkui-ts/ts-universal-attributes-gradient-color.md) - [Gradient Color](reference/arkui-ts/ts-universal-attributes-gradient-color.md)
- [Popup Control](reference/arkui-ts/ts-universal-attributes-popup.md) - [Popup Control](reference/arkui-ts/ts-universal-attributes-popup.md)
...@@ -492,6 +669,11 @@ ...@@ -492,6 +669,11 @@
- [Hit Test Control](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md) - [Hit Test Control](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md)
- [Background Blur](reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md) - [Background Blur](reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md)
- [restoreId](reference/arkui-ts/ts-universal-attributes-restoreId.md) - [restoreId](reference/arkui-ts/ts-universal-attributes-restoreId.md)
- [Foreground Color](reference/arkui-ts/ts-universal-attributes-foreground-color.md)
- [Spherical Effect](reference/arkui-ts/ts-universal-attributes-sphericalEffect.md)
- [Light Up Effect](reference/arkui-ts/ts-universal-attributes-lightUpEffect.md)
- [Pixel Stretch Effect](reference/arkui-ts/ts-universal-attributes-pixelStretchEffect.md)
- [Text Style](reference/arkui-ts/ts-universal-attributes-text-style.md)
- Gesture Processing - Gesture Processing
- [Gesture Binding Methods](reference/arkui-ts/ts-gesture-settings.md) - [Gesture Binding Methods](reference/arkui-ts/ts-gesture-settings.md)
- Basic Gestures - Basic Gestures
...@@ -503,6 +685,7 @@ ...@@ -503,6 +685,7 @@
- [SwipeGesture](reference/arkui-ts/ts-basic-gestures-swipegesture.md) - [SwipeGesture](reference/arkui-ts/ts-basic-gestures-swipegesture.md)
- [Combined Gestures](reference/arkui-ts/ts-combined-gestures.md) - [Combined Gestures](reference/arkui-ts/ts-combined-gestures.md)
- Basic Components - Basic Components
- [AlphabetIndexer](reference/arkui-ts/ts-container-alphabet-indexer.md)
- [Blank](reference/arkui-ts/ts-basic-components-blank.md) - [Blank](reference/arkui-ts/ts-basic-components-blank.md)
- [Button](reference/arkui-ts/ts-basic-components-button.md) - [Button](reference/arkui-ts/ts-basic-components-button.md)
- [Checkbox](reference/arkui-ts/ts-basic-components-checkbox.md) - [Checkbox](reference/arkui-ts/ts-basic-components-checkbox.md)
...@@ -514,6 +697,7 @@ ...@@ -514,6 +697,7 @@
- [Gauge](reference/arkui-ts/ts-basic-components-gauge.md) - [Gauge](reference/arkui-ts/ts-basic-components-gauge.md)
- [Image](reference/arkui-ts/ts-basic-components-image.md) - [Image](reference/arkui-ts/ts-basic-components-image.md)
- [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md) - [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md)
- [ImageSpan](reference/arkui-ts/ts-basic-components-imagespan.md)
- [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md) - [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md)
- [Marquee](reference/arkui-ts/ts-basic-components-marquee.md) - [Marquee](reference/arkui-ts/ts-basic-components-marquee.md)
- [Menu](reference/arkui-ts/ts-basic-components-menu.md) - [Menu](reference/arkui-ts/ts-basic-components-menu.md)
...@@ -549,7 +733,6 @@ ...@@ -549,7 +733,6 @@
- [XComponent](reference/arkui-ts/ts-basic-components-xcomponent.md) - [XComponent](reference/arkui-ts/ts-basic-components-xcomponent.md)
- Container Components - Container Components
- [AbilityComponent](reference/arkui-ts/ts-container-ability-component.md) - [AbilityComponent](reference/arkui-ts/ts-container-ability-component.md)
- [AlphabetIndexer](reference/arkui-ts/ts-container-alphabet-indexer.md)
- [Badge](reference/arkui-ts/ts-container-badge.md) - [Badge](reference/arkui-ts/ts-container-badge.md)
- [Column](reference/arkui-ts/ts-container-column.md) - [Column](reference/arkui-ts/ts-container-column.md)
- [ColumnSplit](reference/arkui-ts/ts-container-columnsplit.md) - [ColumnSplit](reference/arkui-ts/ts-container-columnsplit.md)
...@@ -613,6 +796,7 @@ ...@@ -613,6 +796,7 @@
- [Time Picker Dialog Box](reference/arkui-ts/ts-methods-timepicker-dialog.md) - [Time Picker Dialog Box](reference/arkui-ts/ts-methods-timepicker-dialog.md)
- [Text Picker Dialog Box](reference/arkui-ts/ts-methods-textpicker-dialog.md) - [Text Picker Dialog Box](reference/arkui-ts/ts-methods-textpicker-dialog.md)
- [Menu](reference/arkui-ts/ts-methods-menu.md) - [Menu](reference/arkui-ts/ts-methods-menu.md)
- [Custom Component Lifecycle](reference/arkui-ts/ts-custom-component-lifecycle.md)
- [State Management with Application-level Variables](reference/arkui-ts/ts-state-management.md) - [State Management with Application-level Variables](reference/arkui-ts/ts-state-management.md)
- [Pixel Units](reference/arkui-ts/ts-pixel-units.md) - [Pixel Units](reference/arkui-ts/ts-pixel-units.md)
- [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md) - [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md)
...@@ -722,39 +906,39 @@ ...@@ -722,39 +906,39 @@
- [Data Type Attributes](reference/arkui-js/js-appendix-types.md) - [Data Type Attributes](reference/arkui-js/js-appendix-types.md)
- JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite) - JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite)
- Framework Overview - Framework Overview
- [File Organization](js-framework-file.md) - [File Organization](reference/arkui-js-lite/js-framework-file.md)
- ["js" Tag](js-framework-js-tag.md) - ["js" Tag](reference/arkui-js-lite/js-framework-js-tag.md)
- [app.js](js-framework-js-file.md) - [app.js](reference/arkui-js-lite/js-framework-js-file.md)
- Syntax - Syntax
- [HML](js-framework-syntax-hml.md) - [HML](reference/arkui-js-lite/js-framework-syntax-hml.md)
- [CSS](js-framework-syntax-css.md) - [CSS](reference/arkui-js-lite/js-framework-syntax-css.md)
- [JavaScript](js-framework-syntax-js.md) - [JavaScript](reference/arkui-js-lite/js-framework-syntax-js.md)
- Universal Component Information - Universal Component Information
- [Universal Events](js-common-events.md) - [Universal Events](reference/arkui-js-lite/js-common-events.md)
- [Universal Attributes](js-common-attributes.md) - [Universal Attributes](reference/arkui-js-lite/js-common-attributes.md)
- [Universal Styles](js-common-styles.md) - [Universal Styles](reference/arkui-js-lite/js-common-styles.md)
- [Animation Styles](js-components-common-animation.md) - [Animation Styles](reference/arkui-js-lite/js-components-common-animation.md)
- Container Components - Container Components
- [div](js-components-container-div.md) - [div](reference/arkui-js-lite/js-components-container-div.md)
- [list](js-components-container-list.md) - [list](reference/arkui-js-lite/js-components-container-list.md)
- [list-item](js-components-container-list-item.md) - [list-item](reference/arkui-js-lite/js-components-container-list-item.md)
- [stack](js-components-container-stack.md) - [stack](reference/arkui-js-lite/js-components-container-stack.md)
- [swiper](js-components-container-swiper.md) - [swiper](reference/arkui-js-lite/js-components-container-swiper.md)
- Basic Components - Basic Components
- [chart](js-components-basic-chart.md) - [chart](reference/arkui-js-lite/js-components-basic-chart.md)
- [image](js-components-basic-image.md) - [image](reference/arkui-js-lite/js-components-basic-image.md)
- [image-animator](js-components-basic-image-animator.md) - [image-animator](reference/arkui-js-lite/js-components-basic-image-animator.md)
- [input](js-components-basic-input.md) - [input](reference/arkui-js-lite/js-components-basic-input.md)
- [marquee](js-components-basic-marquee.md) - [marquee](reference/arkui-js-lite/js-components-basic-marquee.md)
- [picker-view](js-components-basic-picker-view.md) - [picker-view](reference/arkui-js-lite/js-components-basic-picker-view.md)
- [progress](js-components-basic-progress.md) - [progress](reference/arkui-js-lite/js-components-basic-progress.md)
- [qrcode](js-components-basic-qrcode.md) - [qrcode](reference/arkui-js-lite/js-components-basic-qrcode.md)
- [slider](js-components-basic-slider.md) - [slider](reference/arkui-js-lite/js-components-basic-slider.md)
- [switch](js-components-basic-switch.md) - [switch](reference/arkui-js-lite/js-components-basic-switch.md)
- [text](js-components-basic-text.md) - [text](reference/arkui-js-lite/js-components-basic-text.md)
- Canvas Components - Canvas Components
- [canvas](js-components-canvas-canvas.md) - [canvas](reference/arkui-js-lite/js-components-canvas-canvas.md)
- [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) - [CanvasRenderingContext2D](reference/arkui-js-lite/js-components-canvas-canvasrenderingcontext2d.md)
- JS Service Widget UI Components - JS Service Widget UI Components
- JS Service Widget UI Framework - JS Service Widget UI Framework
- [File Organization](reference/js-service-widget-ui/js-service-widget-file.md) - [File Organization](reference/js-service-widget-ui/js-service-widget-file.md)
...@@ -812,8 +996,6 @@ ...@@ -812,8 +996,6 @@
- [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](reference/apis/js-apis-app-form-formExtensionAbility.md) - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](reference/apis/js-apis-app-form-formExtensionAbility.md)
- [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](reference/apis/js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](reference/apis/js-apis-application-dataShareExtensionAbility.md)
- [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](reference/apis/js-apis-application-staticSubscriberExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](reference/apis/js-apis-application-staticSubscriberExtensionAbility.md)
- Stage Model (To Be Deprecated Soon)
- [@ohos.application.EnvironmentCallback (EnvironmentCallback)](reference/apis/js-apis-application-environmentCallback.md)
- FA Model - FA Model
- [@ohos.ability.ability (Ability)](reference/apis/js-apis-ability-ability.md) - [@ohos.ability.ability (Ability)](reference/apis/js-apis-ability-ability.md)
- [@ohos.ability.featureAbility (FeatureAbility)](reference/apis/js-apis-ability-featureAbility.md) - [@ohos.ability.featureAbility (FeatureAbility)](reference/apis/js-apis-ability-featureAbility.md)
...@@ -825,16 +1007,20 @@ ...@@ -825,16 +1007,20 @@
- [@ohos.app.ability.appRecovery (appRecovery)](reference/apis/js-apis-app-ability-appRecovery.md) - [@ohos.app.ability.appRecovery (appRecovery)](reference/apis/js-apis-app-ability-appRecovery.md)
- [@ohos.app.ability.Configuration (Configuration)](reference/apis/js-apis-app-ability-configuration.md) - [@ohos.app.ability.Configuration (Configuration)](reference/apis/js-apis-app-ability-configuration.md)
- [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](reference/apis/js-apis-app-ability-configurationConstant.md) - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](reference/apis/js-apis-app-ability-configurationConstant.md)
- [@ohos.app.ability.dataUriUtils (DataUriUtils)](reference/apis/js-apis-app-ability-dataUriUtils.md)
- [@ohos.app.ability.dialogRequest (dialogRequest)](reference/apis/js-apis-app-ability-dialogRequest.md)
- [@ohos.app.ability.errorManager (ErrorManager)](reference/apis/js-apis-app-ability-errorManager.md) - [@ohos.app.ability.errorManager (ErrorManager)](reference/apis/js-apis-app-ability-errorManager.md)
- [@ohos.app.ability.missionManager (missionManager)](reference/apis/js-apis-app-ability-missionManager.md) - [@ohos.app.ability.missionManager (missionManager)](reference/apis/js-apis-app-ability-missionManager.md)
- [@ohos.app.ability.quickFixManager (quickFixManager)](reference/apis/js-apis-app-ability-quickFixManager.md) - [@ohos.app.ability.quickFixManager (quickFixManager)](reference/apis/js-apis-app-ability-quickFixManager.md)
- [@ohos.app.ability.Want (Want)](reference/apis/js-apis-app-ability-want.md) - [@ohos.app.ability.Want (Want)](reference/apis/js-apis-app-ability-want.md)
- [@ohos.app.ability.wantAgent (WantAgent)](reference/apis/js-apis-app-ability-wantAgent.md) - [@ohos.app.ability.wantAgent (WantAgent)](reference/apis/js-apis-app-ability-wantAgent.md)
- [@ohos.app.ability.wantConstant (wantConstant)](reference/apis/js-apis-app-ability-wantConstant.md) - [@ohos.app.ability.wantConstant (wantConstant)](reference/apis/js-apis-app-ability-wantConstant.md)
- [@ohos.app.businessAbilityRouter (Business Ability Router)](reference/apis/js-apis-businessAbilityRouter.md)
- [@ohos.app.form.formBindingData (formBindingData)](reference/apis/js-apis-app-form-formBindingData.md) - [@ohos.app.form.formBindingData (formBindingData)](reference/apis/js-apis-app-form-formBindingData.md)
- [@ohos.app.form.formHost (FormHost)](reference/apis/js-apis-app-form-formHost.md) - [@ohos.app.form.formHost (FormHost)](reference/apis/js-apis-app-form-formHost.md)
- [@ohos.app.form.formInfo (FormInfo)](reference/apis/js-apis-app-form-formInfo.md) - [@ohos.app.form.formInfo (FormInfo)](reference/apis/js-apis-app-form-formInfo.md)
- [@ohos.app.form.formProvider (FormProvider)](reference/apis/js-apis-app-form-formProvider.md) - [@ohos.app.form.formProvider (FormProvider)](reference/apis/js-apis-app-form-formProvider.md)
- [@ohos.application.uriPermissionManager (URI Permission Management)](reference/apis/js-apis-uripermissionmanager.md)
- Both Models (To Be Deprecated Soon) - Both Models (To Be Deprecated Soon)
- [@ohos.ability.dataUriUtils (DataUriUtils)](reference/apis/js-apis-ability-dataUriUtils.md) - [@ohos.ability.dataUriUtils (DataUriUtils)](reference/apis/js-apis-ability-dataUriUtils.md)
- [@ohos.ability.errorCode (ErrorCode)](reference/apis/js-apis-ability-errorCode.md) - [@ohos.ability.errorCode (ErrorCode)](reference/apis/js-apis-ability-errorCode.md)
...@@ -906,10 +1092,12 @@ ...@@ -906,10 +1092,12 @@
- [continuationExtraParams](reference/apis/js-apis-continuation-continuationExtraParams.md) - [continuationExtraParams](reference/apis/js-apis-continuation-continuationExtraParams.md)
- [continuationResult](reference/apis/js-apis-continuation-continuationResult.md) - [continuationResult](reference/apis/js-apis-continuation-continuationResult.md)
- Common Event and Notification - Common Event and Notification
- [System Common Events](reference/apis/commonEventManager-definitions.md)
- [@ohos.commonEventManager (Common Event) (Recommended)](reference/apis/js-apis-commonEventManager.md) - [@ohos.commonEventManager (Common Event) (Recommended)](reference/apis/js-apis-commonEventManager.md)
- [@ohos.events.emitter (Emitter)](reference/apis/js-apis-emitter.md) - [@ohos.events.emitter (Emitter)](reference/apis/js-apis-emitter.md)
- [@ohos.notificationManager (NotificationManager) (Recommended)](reference/apis/js-apis-notificationManager.md) - [@ohos.notificationManager (NotificationManager) (Recommended)](reference/apis/js-apis-notificationManager.md)
- [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](reference/apis/js-apis-notificationSubscribe.md) - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](reference/apis/js-apis-notificationSubscribe.md)
- [System Common Events (To Be Deprecated Soon)](reference/apis/commonEvent-definitions.md)
- [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](reference/apis/js-apis-commonEvent.md) - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](reference/apis/js-apis-commonEvent.md)
- [@ohos.notification (Notification) (To Be Deprecated Soon)](reference/apis/js-apis-notification.md) - [@ohos.notification (Notification) (To Be Deprecated Soon)](reference/apis/js-apis-notification.md)
- application - application
...@@ -928,6 +1116,10 @@ ...@@ -928,6 +1116,10 @@
- [NotificationSlot](reference/apis/js-apis-inner-notification-notificationSlot.md) - [NotificationSlot](reference/apis/js-apis-inner-notification-notificationSlot.md)
- [NotificationTemplate](reference/apis/js-apis-inner-notification-notificationTemplate.md) - [NotificationTemplate](reference/apis/js-apis-inner-notification-notificationTemplate.md)
- [NotificationUserInput](reference/apis/js-apis-inner-notification-notificationUserInput.md) - [NotificationUserInput](reference/apis/js-apis-inner-notification-notificationUserInput.md)
- Common Events
- [Common Events of the Bundle Management Subsystem](reference/apis/common_event/commonEvent-bundleManager.md)
- [Common Events of the Notification Service](reference/apis/common_event/commonEvent-ans.md)
- [Common Events of the Telephony Subsystem](reference/apis/common_event/commonEvent-telephony.md)
- Bundle Management - Bundle Management
- [@ohos.bundle.appControl(appControl)](reference/apis/js-apis-appControl.md) - [@ohos.bundle.appControl(appControl)](reference/apis/js-apis-appControl.md)
- [@ohos.bundle.bundleManager (bundleManager)](reference/apis/js-apis-bundleManager.md) - [@ohos.bundle.bundleManager (bundleManager)](reference/apis/js-apis-bundleManager.md)
...@@ -937,29 +1129,38 @@ ...@@ -937,29 +1129,38 @@
- [@ohos.bundle.freeInstall (freeInstall)](reference/apis/js-apis-freeInstall.md) - [@ohos.bundle.freeInstall (freeInstall)](reference/apis/js-apis-freeInstall.md)
- [@ohos.bundle.installer (installer)](reference/apis/js-apis-installer.md) - [@ohos.bundle.installer (installer)](reference/apis/js-apis-installer.md)
- [@ohos.bundle.launcherBundleManager (launcherBundleManager)](reference/apis/js-apis-launcherBundleManager.md) - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](reference/apis/js-apis-launcherBundleManager.md)
- [@ohos.bundle.overlay (overlay)](reference/apis/js-apis-overlay.md)
- [@ohos.zlib (Zip)](reference/apis/js-apis-zlib.md) - [@ohos.zlib (Zip)](reference/apis/js-apis-zlib.md)
- bundleManager - bundleManager
- [abilityInfo](reference/apis/js-apis-bundleManager-abilityInfo.md) - [abilityInfo](reference/apis/js-apis-bundleManager-abilityInfo.md)
- [applicationInfo](reference/apis/js-apis-bundleManager-applicationInfo.md) - [applicationInfo](reference/apis/js-apis-bundleManager-applicationInfo.md)
- [AppProvisionInfo](reference/apis/js-apis-bundleManager-AppProvisionInfo.md)
- [bundleInfo](reference/apis/js-apis-bundleManager-bundleInfo.md) - [bundleInfo](reference/apis/js-apis-bundleManager-bundleInfo.md)
- [BundlePackInfo](reference/apis/js-apis-bundleManager-BundlePackInfo.md) - [BundlePackInfo](reference/apis/js-apis-bundleManager-BundlePackInfo.md)
- [BusinessAbilityInfo](reference/apis/js-apis-bundleManager-businessAbilityInfo.md)
- [dispatchInfo](reference/apis/js-apis-bundleManager-dispatchInfo.md) - [dispatchInfo](reference/apis/js-apis-bundleManager-dispatchInfo.md)
- [elementName](reference/apis/js-apis-bundleManager-elementName.md) - [elementName](reference/apis/js-apis-bundleManager-elementName.md)
- [extensionAbilityInfo](reference/apis/js-apis-bundleManager-extensionAbilityInfo.md) - [extensionAbilityInfo](reference/apis/js-apis-bundleManager-extensionAbilityInfo.md)
- [hapModuleInfo](reference/apis/js-apis-bundleManager-hapModuleInfo.md) - [hapModuleInfo](reference/apis/js-apis-bundleManager-hapModuleInfo.md)
- [launcherAbilityInfo](reference/apis/js-apis-bundleManager-launcherAbilityInfo.md) - [launcherAbilityInfo](reference/apis/js-apis-bundleManager-launcherAbilityInfo.md)
- [metadata](reference/apis/js-apis-bundleManager-metadata.md) - [metadata](reference/apis/js-apis-bundleManager-metadata.md)
- [OverlayModuleInfo](reference/apis/js-apis-bundleManager-overlayModuleInfo.md)
- [permissionDef](reference/apis/js-apis-bundleManager-permissionDef.md) - [permissionDef](reference/apis/js-apis-bundleManager-permissionDef.md)
- [remoteAbilityInfo](reference/apis/js-apis-bundleManager-remoteAbilityInfo.md) - [remoteAbilityInfo](reference/apis/js-apis-bundleManager-remoteAbilityInfo.md)
- [SharedBundleInfo](reference/apis/js-apis-bundleManager-sharedBundleInfo.md)
- [shortcutInfo](reference/apis/js-apis-bundleManager-shortcutInfo.md) - [shortcutInfo](reference/apis/js-apis-bundleManager-shortcutInfo.md)
- UI Page - UI Page
- [@ohos.animator (Animator)](reference/apis/js-apis-animator.md) - [@ohos.animator (Animator)](reference/apis/js-apis-animator.md)
- [@ohos.arkui.componentSnapshot (Component Snapshot)](reference/apis/js-apis-arkui-componentSnapshot.md)
- [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](reference/apis/js-apis-arkui-drawableDescriptor.md)
- [@ohos.curves (Interpolation Calculation)](reference/apis/js-apis-curve.md) - [@ohos.curves (Interpolation Calculation)](reference/apis/js-apis-curve.md)
- [@ohos.matrix4 (Matrix Transformation)](reference/apis/js-apis-matrix4.md) - [@ohos.matrix4 (Matrix Transformation)](reference/apis/js-apis-matrix4.md)
- [@ohos.mediaquery (Media Query)](reference/apis/js-apis-mediaquery.md) - [@ohos.mediaquery (Media Query)](reference/apis/js-apis-mediaquery.md)
- [@ohos.pluginComponent (PluginComponentManager)](reference/apis/js-apis-plugincomponent.md) - [@ohos.pluginComponent (PluginComponentManager)](reference/apis/js-apis-plugincomponent.md)
- [@ohos.promptAction (Prompt)](reference/apis/js-apis-promptAction.md) - [@ohos.promptAction (Prompt)](reference/apis/js-apis-promptAction.md)
- [@ohos.router (Page Routing)](reference/apis/js-apis-router.md) - [@ohos.router (Page Routing)](reference/apis/js-apis-router.md)
- [@ohos.measure (Text Measurement)](reference/apis/js-apis-measure.md)
- [@ohos.uiAppearance (UI Appearance)](reference/apis/js-apis-uiappearance.md)
- Graphics - Graphics
- [@ohos.animation.windowAnimationManager (Window Animation Management)](reference/apis/js-apis-windowAnimationManager.md) - [@ohos.animation.windowAnimationManager (Window Animation Management)](reference/apis/js-apis-windowAnimationManager.md)
- [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](reference/apis/js-apis-application-windowExtensionAbility.md) - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](reference/apis/js-apis-application-windowExtensionAbility.md)
...@@ -989,6 +1190,8 @@ ...@@ -989,6 +1190,8 @@
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](reference/apis/js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.workScheduler (Work Scheduler)](reference/apis/js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md)
- application
- [WorkSchedulerExtensionContext](reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md)
- Security - Security
- [@ohos.abilityAccessCtrl (Ability Access Control)](reference/apis/js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl (Ability Access Control)](reference/apis/js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager (Privacy Management)](reference/apis/js-apis-privacyManager.md) - [@ohos.privacyManager (Privacy Management)](reference/apis/js-apis-privacyManager.md)
...@@ -997,7 +1200,6 @@ ...@@ -997,7 +1200,6 @@
- [@ohos.security.huks (HUKS)](reference/apis/js-apis-huks.md) - [@ohos.security.huks (HUKS)](reference/apis/js-apis-huks.md)
- [@ohos.userIAM.faceAuth (Facial Authentication)](reference/apis/js-apis-useriam-faceauth.md) - [@ohos.userIAM.faceAuth (Facial Authentication)](reference/apis/js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth (User Authentication)](reference/apis/js-apis-useriam-userauth.md) - [@ohos.userIAM.userAuth (User Authentication)](reference/apis/js-apis-useriam-userauth.md)
- [@system.cipher (Cipher Algorithm)](reference/apis/js-apis-system-cipher.md)
- security - security
- [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md) - [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md)
- Data Management - Data Management
...@@ -1010,20 +1212,22 @@ ...@@ -1010,20 +1212,22 @@
- [@ohos.data.preferences (Preferences)](reference/apis/js-apis-data-preferences.md) - [@ohos.data.preferences (Preferences)](reference/apis/js-apis-data-preferences.md)
- [@ohos.data.relationalStore (RDB Store)](reference/apis/js-apis-data-relationalStore.md) - [@ohos.data.relationalStore (RDB Store)](reference/apis/js-apis-data-relationalStore.md)
- [@ohos.data.ValuesBucket](reference/apis/js-apis-data-valuesBucket.md) - [@ohos.data.ValuesBucket](reference/apis/js-apis-data-valuesBucket.md)
- data/rdb
- [resultSet (Result Set)](reference/apis/js-apis-data-resultset.md)
- File Management - File Management
- [@ohos.file.backup (Backup and Restoration)](reference/apis/js-apis-file-backup.md)
- [@ohos.file.cloudSyncManager (Device-Cloud Synchronization Management)](reference/apis/js-apis-file-cloudsyncmanager.md)
- [@ohos.file.environment (Directory Environment Capability)](reference/apis/js-apis-file-environment.md) - [@ohos.file.environment (Directory Environment Capability)](reference/apis/js-apis-file-environment.md)
- [@ohos.file.fileAccess (User File Access and Management)](reference/apis/js-apis-fileAccess.md) - [@ohos.file.fileAccess (User File Access and Management)](reference/apis/js-apis-fileAccess.md)
- [@ohos.file.fileExtensionInfo (User File Extension Information)](reference/apis/js-apis-fileExtensionInfo.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](reference/apis/js-apis-fileExtensionInfo.md)
- [@ohos.file.fileuri (File URI)](reference/apis/js-apis-file-fileuri.md)
- [@ohos.file.fs (File Management)](reference/apis/js-apis-file-fs.md) - [@ohos.file.fs (File Management)](reference/apis/js-apis-file-fs.md)
- [@ohos.file.hash (File Hash Processing)](reference/apis/js-apis-file-hash.md) - [@ohos.file.hash (File Hash Processing)](reference/apis/js-apis-file-hash.md)
- [@ohos.file.picker (File Picker)](reference/apis/js-apis-file-picker.md)
- [@ohos.file.securityLabel (Data Label)](reference/apis/js-apis-file-securityLabel.md) - [@ohos.file.securityLabel (Data Label)](reference/apis/js-apis-file-securityLabel.md)
- [@ohos.file.statvfs (File System Space Statistics)](reference/apis/js-apis-file-statvfs.md) - [@ohos.file.statvfs (File System Space Statistics)](reference/apis/js-apis-file-statvfs.md)
- [@ohos.storageStatistics (Application Storage Statistics)](reference/apis/js-apis-file-storage-statistics.md) - [@ohos.file.storageStatistics (Application Storage Statistics)](reference/apis/js-apis-file-storage-statistics.md)
- [@ohos.volumeManager (Volume Management)](reference/apis/js-apis-file-volumemanager.md) - [@ohos.file.volumeManager (Volume Management)](reference/apis/js-apis-file-volumemanager.md)
- [@ohos.filemanagement.userFileManager (User Data Management)](reference/apis/js-apis-userFileManager.md) - [@ohos.filemanagement.userFileManager (User Data Management)](reference/apis/js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](reference/apis/js-apis-medialibrary.md) - [@ohos.fileShare (File Sharing)](reference/apis/js-apis-fileShare.md)
- Telephony Service - Telephony Service
- [@ohos.contact (Contacts)](reference/apis/js-apis-contact.md) - [@ohos.contact (Contacts)](reference/apis/js-apis-contact.md)
- [@ohos.telephony.call (Call)](reference/apis/js-apis-call.md) - [@ohos.telephony.call (Call)](reference/apis/js-apis-call.md)
...@@ -1036,12 +1240,14 @@ ...@@ -1036,12 +1240,14 @@
- [@ohos.net.connection (Network Connection Management)](reference/apis/js-apis-net-connection.md) - [@ohos.net.connection (Network Connection Management)](reference/apis/js-apis-net-connection.md)
- [@ohos.net.ethernet (Ethernet Connection Management)](reference/apis/js-apis-net-ethernet.md) - [@ohos.net.ethernet (Ethernet Connection Management)](reference/apis/js-apis-net-ethernet.md)
- [@ohos.net.http (Data Request)](reference/apis/js-apis-http.md) - [@ohos.net.http (Data Request)](reference/apis/js-apis-http.md)
- [@ohos.net.mdns (mDNS Management)](reference/apis/js-apis-net-mdns.md)
- [@ohos.net.sharing (Network Sharing)](reference/apis/js-apis-net-sharing.md) - [@ohos.net.sharing (Network Sharing)](reference/apis/js-apis-net-sharing.md)
- [@ohos.net.socket (Socket Connection)](reference/apis/js-apis-socket.md) - [@ohos.net.socket (Socket Connection)](reference/apis/js-apis-socket.md)
- [@ohos.net.webSocket (WebSocket Connection)](reference/apis/js-apis-webSocket.md) - [@ohos.net.webSocket (WebSocket Connection)](reference/apis/js-apis-webSocket.md)
- [@ohos.request (Upload and Download)](reference/apis/js-apis-request.md) - [@ohos.request (Upload and Download)](reference/apis/js-apis-request.md)
- Connectivity - Connectivity
- [@ohos.bluetooth (Bluetooth)](reference/apis/js-apis-bluetooth.md) - [@ohos.bluetooth (Bluetooth)](reference/apis/js-apis-bluetooth.md)
- [@ohos.bluetoothManager (Bluetooth) (Recommended)](reference/apis/js-apis-bluetoothManager.md)
- [@ohos.connectedTag (Active Tags)](reference/apis/js-apis-connectedTag.md) - [@ohos.connectedTag (Active Tags)](reference/apis/js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](reference/apis/js-apis-cardEmulation.md) - [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](reference/apis/js-apis-cardEmulation.md)
- [@ohos.nfc.controller (Standard NFC)](reference/apis/js-apis-nfcController.md) - [@ohos.nfc.controller (Standard NFC)](reference/apis/js-apis-nfcController.md)
...@@ -1087,6 +1293,7 @@ ...@@ -1087,6 +1293,7 @@
- [@ohos.batteryInfo (Battery Information)](reference/apis/js-apis-battery-info.md) - [@ohos.batteryInfo (Battery Information)](reference/apis/js-apis-battery-info.md)
- [@ohos.batteryStatistics (Battery Statistics)](reference/apis/js-apis-batteryStatistics.md) - [@ohos.batteryStatistics (Battery Statistics)](reference/apis/js-apis-batteryStatistics.md)
- [@ohos.brightness (Screen Brightness)](reference/apis/js-apis-brightness.md) - [@ohos.brightness (Screen Brightness)](reference/apis/js-apis-brightness.md)
- [@ohos.charger (Charging Type)](reference/apis/js-apis-charger.md)
- [@ohos.deviceInfo (Device Information)](reference/apis/js-apis-device-info.md) - [@ohos.deviceInfo (Device Information)](reference/apis/js-apis-device-info.md)
- [@ohos.distributedHardware.deviceManager (Device Management)](reference/apis/js-apis-device-manager.md) - [@ohos.distributedHardware.deviceManager (Device Management)](reference/apis/js-apis-device-manager.md)
- [@ohos.geoLocationManager (Geolocation Manager)](reference/apis/js-apis-geoLocationManager.md) - [@ohos.geoLocationManager (Geolocation Manager)](reference/apis/js-apis-geoLocationManager.md)
...@@ -1118,9 +1325,15 @@ ...@@ -1118,9 +1325,15 @@
- [@ohos.account.osAccount (OS Account Management)](reference/apis/js-apis-osAccount.md) - [@ohos.account.osAccount (OS Account Management)](reference/apis/js-apis-osAccount.md)
- Customization - Customization
- [@ohos.configPolicy (Configuration Policy)](reference/apis/js-apis-configPolicy.md) - [@ohos.configPolicy (Configuration Policy)](reference/apis/js-apis-configPolicy.md)
- [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.accountManager (Account Management)](reference/apis/js-apis-enterprise-accountManager.md)
- [@ohos.enterprise.adminManager (Enterprise Device Management)](reference/apis/js-apis-enterprise-adminManager.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](reference/apis/js-apis-enterprise-adminManager.md)
- [@ohos.enterprise.bundleManager (Bundle Management)](reference/apis/js-apis-enterprise-bundleManager.md)
- [@ohos.enterprise.dateTimeManager (System Time Management)](reference/apis/js-apis-enterprise-dateTimeManager.md) - [@ohos.enterprise.dateTimeManager (System Time Management)](reference/apis/js-apis-enterprise-dateTimeManager.md)
- [@ohos.enterprise.deviceControl (Device Control Management)](reference/apis/js-apis-enterprise-deviceControl.md)
- [@ohos.enterprise.deviceInfo (Device Information Management)](reference/apis/js-apis-enterprise-deviceInfo.md)
- [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md)
- [@ohos.enterprise.networkManager (Network Management)](reference/apis/js-apis-enterprise-networkManager.md)
- [@ohos.enterprise.wifiManager (Wi-Fi Management)](reference/apis/js-apis-enterprise-wifiManager.md)
- Language Base Class Library - Language Base Class Library
- [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md) - [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md)
- [@ohos.convertxml (XML-to-JavaScript Conversion)](reference/apis/js-apis-convertxml.md) - [@ohos.convertxml (XML-to-JavaScript Conversion)](reference/apis/js-apis-convertxml.md)
...@@ -1162,17 +1375,18 @@ ...@@ -1162,17 +1375,18 @@
- [@ohos.fileio (File Management)](reference/apis/js-apis-fileio.md) - [@ohos.fileio (File Management)](reference/apis/js-apis-fileio.md)
- [@ohos.geolocation (Geolocation)](reference/apis/js-apis-geolocation.md) - [@ohos.geolocation (Geolocation)](reference/apis/js-apis-geolocation.md)
- [@ohos.hiAppEvent (Application Event Logging)](reference/apis/js-apis-hiappevent.md) - [@ohos.hiAppEvent (Application Event Logging)](reference/apis/js-apis-hiappevent.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](reference/apis/js-apis-medialibrary.md)
- [@ohos.prompt (Prompt)](reference/apis/js-apis-prompt.md) - [@ohos.prompt (Prompt)](reference/apis/js-apis-prompt.md)
- [@ohos.reminderAgent (Reminder Agent)](reference/apis/js-apis-reminderAgent.md) - [@ohos.reminderAgent (Reminder Agent)](reference/apis/js-apis-reminderAgent.md)
- [@ohos.statfs (statfs)](reference/apis/js-apis-statfs.md) - [@ohos.statfs (statfs)](reference/apis/js-apis-statfs.md)
- [@ohos.systemParameter (System Parameter)](reference/apis/js-apis-system-parameter.md) - [@ohos.systemParameter (System Parameter)](reference/apis/js-apis-system-parameter.md)
- [@ohos.systemTime (System Time and Time Zone)](reference/apis/js-apis-system-time.md) - [@ohos.systemTime (System Time and Time Zone)](reference/apis/js-apis-system-time.md)
- [@ohos.usb (USB Management)](reference/apis/js-apis-usb-deprecated.md) - [@ohos.usb (USB Management)](reference/apis/js-apis-usb-deprecated.md)
- [@ohos.usbV9 (USB Management)](reference/apis/js-apis-usb.md)
- [@system.app (Application Context)](reference/apis/js-apis-system-app.md) - [@system.app (Application Context)](reference/apis/js-apis-system-app.md)
- [@system.battery (Battery Information)](reference/apis/js-apis-system-battery.md) - [@system.battery (Battery Information)](reference/apis/js-apis-system-battery.md)
- [@system.bluetooth (Bluetooth)](reference/apis/js-apis-system-bluetooth.md) - [@system.bluetooth (Bluetooth)](reference/apis/js-apis-system-bluetooth.md)
- [@system.brightness (Screen Brightness)](reference/apis/js-apis-system-brightness.md) - [@system.brightness (Screen Brightness)](reference/apis/js-apis-system-brightness.md)
- [@system.cipher (Cipher Algorithm)](reference/apis/js-apis-system-cipher.md)
- [@system.configuration (Application Configuration)](reference/apis/js-apis-system-configuration.md) - [@system.configuration (Application Configuration)](reference/apis/js-apis-system-configuration.md)
- [@system.device (Device Information)](reference/apis/js-apis-system-device.md) - [@system.device (Device Information)](reference/apis/js-apis-system-device.md)
- [@system.fetch (Data Request)](reference/apis/js-apis-system-fetch.md) - [@system.fetch (Data Request)](reference/apis/js-apis-system-fetch.md)
...@@ -1202,6 +1416,8 @@ ...@@ -1202,6 +1416,8 @@
- [PermissionDef](reference/apis/js-apis-bundle-PermissionDef.md) - [PermissionDef](reference/apis/js-apis-bundle-PermissionDef.md)
- [remoteAbilityInfo](reference/apis/js-apis-bundle-remoteAbilityInfo.md) - [remoteAbilityInfo](reference/apis/js-apis-bundle-remoteAbilityInfo.md)
- [shortcutInfo](reference/apis/js-apis-bundle-ShortcutInfo.md) - [shortcutInfo](reference/apis/js-apis-bundle-ShortcutInfo.md)
- data/rdb
- [resultSet](reference/apis/js-apis-data-resultset.md)
- Error Codes - Error Codes
- [Universal Error Codes](reference/errorcodes/errorcode-universal.md) - [Universal Error Codes](reference/errorcodes/errorcode-universal.md)
- Ability Framework - Ability Framework
...@@ -1253,7 +1469,15 @@ ...@@ -1253,7 +1469,15 @@
- [Telephony Error Codes](reference/errorcodes/errorcode-telephony.md) - [Telephony Error Codes](reference/errorcodes/errorcode-telephony.md)
- Network Management - Network Management
- [Upload and Download Error Codes](reference/errorcodes/errorcode-request.md) - [Upload and Download Error Codes](reference/errorcodes/errorcode-request.md)
- [HTTP Error Codes](reference/errorcodes/errorcode-net-http.md)
- [Socket Error Codes](reference/errorcodes/errorcode-net-socket.md)
- [Network Connection Management Error Codes](reference/errorcodes/errorcode-net-connection.md)
- [Ethernet Connection Error Codes](reference/errorcodes/errorcode-net-ethernet.md)
- [Network Sharing Error Codes](reference/errorcodes/errorcode-net-sharing.md)
- [mDNS Error Codes](reference/errorcodes/errorcode-net-mdns.md)
- Connectivity - Connectivity
- [Bluetooth Error Codes](reference/errorcodes/errorcode-bluetoothManager.md)
- [Wi-Fi Error Codes](reference/errorcodes/errorcode-wifi.md)
- [NFC Error Codes](reference/errorcodes/errorcode-nfc.md) - [NFC Error Codes](reference/errorcodes/errorcode-nfc.md)
- [RPC Error Codes](reference/errorcodes/errorcode-rpc.md) - [RPC Error Codes](reference/errorcodes/errorcode-rpc.md)
- Basic Features - Basic Features
...@@ -1264,6 +1488,7 @@ ...@@ -1264,6 +1488,7 @@
- [HiDebug Error Codes](reference/errorcodes/errorcode-hiviewdfx-hidebug.md) - [HiDebug Error Codes](reference/errorcodes/errorcode-hiviewdfx-hidebug.md)
- [Input Method Framework Error Codes](reference/errorcodes/errorcode-inputmethod-framework.md) - [Input Method Framework Error Codes](reference/errorcodes/errorcode-inputmethod-framework.md)
- [Pasteboard Error Codes](reference/errorcodes/errorcode-pasteboard.md) - [Pasteboard Error Codes](reference/errorcodes/errorcode-pasteboard.md)
- [Screen Lock Management Error Codes](reference/errorcodes/errorcode-screenlock.md)
- [Time and Time Zone Service Error Codes](reference/errorcodes/errorcode-time.md) - [Time and Time Zone Service Error Codes](reference/errorcodes/errorcode-time.md)
- [Webview Error Codes](reference/errorcodes/errorcode-webview.md) - [Webview Error Codes](reference/errorcodes/errorcode-webview.md)
- Account Management - Account Management
...@@ -1293,10 +1518,7 @@ ...@@ -1293,10 +1518,7 @@
- [Native XComponent](reference/native-apis/_o_h___native_x_component.md) - [Native XComponent](reference/native-apis/_o_h___native_x_component.md)
- [HiLog](reference/native-apis/_hi_log.md) - [HiLog](reference/native-apis/_hi_log.md)
- [NativeWindow](reference/native-apis/_native_window.md) - [NativeWindow](reference/native-apis/_native_window.md)
- [OH_NativeBuffer](reference/native-apis/_o_h___native_buffer.md)
- [Drawing](reference/native-apis/_drawing.md) - [Drawing](reference/native-apis/_drawing.md)
- [OH_NativeImage](reference/native-apis/_o_h___native_image.md)
- [NativeVsync](reference/native-apis/_native_vsync.md)
- [Image](reference/native-apis/image.md) - [Image](reference/native-apis/image.md)
- [Rawfile](reference/native-apis/rawfile.md) - [Rawfile](reference/native-apis/rawfile.md)
- [MindSpore](reference/native-apis/_mind_spore.md) - [MindSpore](reference/native-apis/_mind_spore.md)
...@@ -1324,10 +1546,7 @@ ...@@ -1324,10 +1546,7 @@
- [external_window.h](reference/native-apis/external__window_8h.md) - [external_window.h](reference/native-apis/external__window_8h.md)
- [image_pixel_map_napi.h](reference/native-apis/image__pixel__map__napi_8h.md) - [image_pixel_map_napi.h](reference/native-apis/image__pixel__map__napi_8h.md)
- [log.h](reference/native-apis/log_8h.md) - [log.h](reference/native-apis/log_8h.md)
- [native_buffer.h](reference/native-apis/native__buffer_8h.md)
- [native_image.h](reference/native-apis/native__image_8h.md)
- [native_interface_xcomponent.h](reference/native-apis/native__interface__xcomponent_8h.md) - [native_interface_xcomponent.h](reference/native-apis/native__interface__xcomponent_8h.md)
- [native_vsync.h](reference/native-apis/native__vsync_8h.md)
- [raw_dir.h](reference/native-apis/raw__dir_8h.md) - [raw_dir.h](reference/native-apis/raw__dir_8h.md)
- [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md) - [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md)
- [raw_file.h](reference/native-apis/raw__file_8h.md) - [raw_file.h](reference/native-apis/raw__file_8h.md)
...@@ -1353,7 +1572,6 @@ ...@@ -1353,7 +1572,6 @@
- [native_huks_type.h](reference/native-apis/native__huks__type_8h.md) - [native_huks_type.h](reference/native-apis/native__huks__type_8h.md)
- Structs - Structs
- [OH_Drawing_BitmapFormat](reference/native-apis/_o_h___drawing___bitmap_format.md) - [OH_Drawing_BitmapFormat](reference/native-apis/_o_h___drawing___bitmap_format.md)
- [OH_NativeBuffer_Config](reference/native-apis/_o_h___native_buffer___config.md)
- [OH_NativeXComponent_Callback](reference/native-apis/_o_h___native_x_component___callback.md) - [OH_NativeXComponent_Callback](reference/native-apis/_o_h___native_x_component___callback.md)
- [OH_NativeXComponent_MouseEvent](reference/native-apis/_o_h___native_x_component___mouse_event.md) - [OH_NativeXComponent_MouseEvent](reference/native-apis/_o_h___native_x_component___mouse_event.md)
- [OH_NativeXComponent_MouseEvent_Callback](reference/native-apis/_o_h___native_x_component___mouse_event___callback.md) - [OH_NativeXComponent_MouseEvent_Callback](reference/native-apis/_o_h___native_x_component___mouse_event___callback.md)
...@@ -1393,27 +1611,33 @@ ...@@ -1393,27 +1611,33 @@
- [Native Standard Libraries Supported by Openharmony](reference/native-lib/third_party_libc/musl.md) - [Native Standard Libraries Supported by Openharmony](reference/native-lib/third_party_libc/musl.md)
- Appendix - Appendix
- [Native API Symbols Not Exported](reference/native-lib/third_party_libc/musl-peculiar-symbol.md) - [Native API Symbols Not Exported](reference/native-lib/third_party_libc/musl-peculiar-symbol.md)
- [Native API Symbols That May Fail to Be Invoked Due to Permission Control](reference/native-lib/third_party_libc/musl-permission-control-symbol.md)
- [EGL Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/egl-symbol.md) - [EGL Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/egl-symbol.md)
- [OpenGL ES 3.0 Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/openglesv3-symbol.md) - [OpenGL ES 3.0 Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/openglesv3-symbol.md)
- [OpenSL ES Interfaces Supported by Native APIs](reference/native-lib/third_party_opensles/opensles.md)
- FAQs - FAQs
- [Guide to Switching to Full SDK](quick-start/full-sdk-switch-guide.md) - [Full SDK Compilation Guide](faqs/full-sdk-compile-guide.md)
- [Programming Languages](faqs/faqs-language.md) - [Guide to Switching to Full SDK](faqs/full-sdk-switch-guide.md)
- [Ability Framework Development](faqs/faqs-ability.md) - [Ability Framework Development](faqs/faqs-ability.md)
- [Bundle Management Development](faqs/faqs-bundle.md) - ArkUI Framework Development (ArkTS)
- [ArkUI (ArkTS) Development](faqs/faqs-ui-ets.md) - [ArkUI Development (ArkTS Syntax)](faqs/faqs-arkui-arkts.md)
- [ArkUI Web Component (ArkTS) Development](faqs/faqs-web-arkts.md) - [Web Development](faqs/faqs-arkui-web.md)
- [ArkUI (JavaScript) Development](faqs/faqs-ui-js.md) - [Bundle Management Development](faqs/faqs-bundle-management.md)
- [Resource Management Development](faqs/faqs-globalization.md)
- [Common Event and Notification Development](faqs/faqs-event-notification.md) - [Common Event and Notification Development](faqs/faqs-event-notification.md)
- [Graphics and Image Development](faqs/faqs-graphics.md) - [Graphics and Image Development](faqs/faqs-graphics.md)
- [Window Management Development](faqs/faqs-window-manager.md)
- [Multimedia Development](faqs/faqs-multimedia.md)
- [Basic Security Capability Development](faqs/faqs-security.md)
- [Ability Access Control Development](faqs/faqs-ability-access-control.md)
- [Data Management Development](faqs/faqs-distributed-data-management.md)
- [File Management Development](faqs/faqs-file-management.md) - [File Management Development](faqs/faqs-file-management.md)
- [Media Development](faqs/faqs-media.md) - [Network Management Development](faqs/faqs-network-management.md)
- [Network and Connection Development](faqs/faqs-connectivity.md)
- [Device Management Development](faqs/faqs-data-management.md)
- [Device Management Development](faqs/faqs-device-management.md)
- [DFX Development](faqs/faqs-dfx.md) - [DFX Development](faqs/faqs-dfx.md)
- [Intl Development](faqs/faqs-international.md) - [Pan-Sensor Development](faqs/faqs-sensor.md)
- [Native API Usage](faqs/faqs-native.md) - [Startup Development](faqs/faqs-startup.md)
- [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-party-library.md) - [Distributed Device Development](faqs/faqs-distributed-device-profile.md)
- [IDE Usage](faqs/faqs-ide.md) - [SDK Usage](faqs/faqs-sdk.md)
- [Development Board](faqs/faqs-development-board.md) - [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-fourth-party-library.md)
<!--no_check-->
<!--no_check-->
\ No newline at end of file
# TypeScript and JavaScript Coding Style Guide
# Overview
## Purpose
This guide is applicable to the scenario where TypeScript and JavaScript are used during OpenHarmony application development.
Based on the technical features of language engines and OpenHarmony, as well as industry standards and practices, this guide provides coding guide for improving code standardization, security, and performance.
## Source
This guide is developed based on the *JavaScript Coding Style Guide* [1]. It integrates the technical features of OpenHarmony without violating industry rules, including ESLint and TSC configuration.
The correct and incorrect examples, marked with **@typescript-eslint**, in ESLint rules come from ESLint Rules [2].
## Document Structure
- [OpenHarmony Application Environment Restrictions](#openharmony-application-environment-restrictions)
All the restrictions provided in this section are raised for security purposes and therefore are mandatory.
- Programming language features: [Declaration and Initialization](#declaration-and-initialization), [Data Types](#data-types), [Operation and Expressions](#operation-and-expressions), [Functions](#functions), [Classes and Objects](#classes-and-objects), and [Exceptions](#exceptions), [Async Functions](#async-functions), and [Types](#types).
## Conventions
**Rule**: a convention that must be complied with
**Recommendation**: a convention that must be taken into consideration
It is necessary to understand the reason for each rule or recommendation and try to comply with them.
# OpenHarmony Application Environment Restrictions
## Use Strict Mode
**[Category] Rule**
**[Description]**
Strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting out of sloppy mode.
1. Strict mode eliminates some JavaScript silent errors by throwing errors.
1. Strict mode fixes defects that make it difficult for JavaScript engines to perform optimizations. Sometimes, the same code can run faster in strict mode than in non-strict mode.
1. Strict mode prohibits some syntax that may be defined in future versions of ECMAScript.
**Note: Currently, only TypeScript or JavaScript code in strict mode is supported on OpenHarmony ArkCompiler.**
## Do Not Use eval()
**[Category] Rule**
**[Description]**
Using **eval()** causes code disorder and poor readability.
**[Incorrect Example]**
```javascript
console.log (eval ({ a:2 })); // Output [object Object].
console.log(eval('"a" + 2')); // Output 'a2'.
console.log(eval('{a: 2}')); // Output 2.
console.log(eval('let value = 1 + 1;'); // Output undefined.
```
## Do Not Use with() {}
**[Category] Rule**
**[Description]**
Using **with()** makes the code semantically unclear because the object of **with()** may conflict with local variables, changing the original semantics.
**[Incorrect Example]**
```javascript
const foo = { x: 5 };
with (foo) {
let x = 3;
console.log(x); // x = 3
}
console.log(foo.x); // x = 3
```
## Do Not Dynamically Create Functions
**[Category] Rule**
**[Description]**
A function can be defined in three ways: declaration, constructor, and expression. No matter which means is used, the function created is an instance of the **Function** object and inherits all default or custom methods and attributes of the **Function** object. Defining a function by using a constructor is similar to the using of **eval()**. The constructor accepts any string as the function body, causing security vulnerabilities.
**[Incorrect Example]**
```javascript
let add = new Function('a','b','return a + b');
// The function constructor can have only one parameter, which can be any string.
let dd = new Function('alert("hello")');
```
**[Correct Example]**
```javascript
// Function declaration.
function add(a,b){
return a+b;
}
// Function expression.
let add = function(a,b){
return a+b;
}
```
# Declaration and Initialization
## Use const or let Instead of var to Declare Variables
**[Category] Rule**
**[Description]**
ECMAScript 6 allows the use of the **let** and **const** keywords to declare variables in the block scope instead of the function scope. The block scope is commonly used in many programming languages. It is helpful in preventing errors. Use **const** to define read-only variables, and use **let** to define other variables.
**[Incorrect Example]**
```javascript
var number = 1;
var count = 1;
if (isOK) {
count += 1;
}
```
**[Correct Example]**
```javascript
const number = 1;
let count = 1;
if (isOK) {
count += 1;
}
```
# Data Types
## Do Not Omit 0s Before and After the Decimal Point of a Floating-Point Number
**[Category] Rule**
**[Description]**
In JavaScript, a floating-point number must contain a decimal point, but no digit is required before or after the decimal point. This makes it difficult to distinguish between the decimal point and the dot operator. For this reason, you must use a digit before and after the decimal point for a floating-point number in OpenHarmony code.
**[Incorrect Example]**
```javascript
const num = .5;
const num = 2.;
const num = -.7;
```
**[Correct Example]**
```javascript
const num = 0.5;
const num = 2.0;
const num = -0.7;
```
## Use isNaN() to Check Whether a Variable Is NaN
**[Category] Rule**
**[Description]**
In JavaScript, NaN is a particular value of a numeric data type. It represents a non-numeric value in the double-precision 64-bit format, as defined in the IEEE floating-point standard.
NaN is unique in JavaScript because it is not equal to any value, including itself. Therefore, the result of comparison with NaN is confusing, as the values of **NaN !== NaN** and **NaN != NaN** are both **true**.
Therefore, you must use **Number.isNaN()** or the global **isNaN()** function to check whether a variable is NaN.
**[Incorrect Example]**
```javascript
if (foo == NaN) {
// ...
}
if (foo != NaN) {
// ...
}
```
**[Correct Example]**
```javascript
if (isNaN(foo)) {
// ...
}
if (!isNaN(foo)) {
// ...
}
```
## Do Not Use == or === to Check Whether Floating-Point Numbers Are Equal
**[Category] Rule**
**[Description]**
Due to the precision problem, mathematically equal numbers may not be equal in floating-point arithmetic. Therefore, the equality operators **==** and **===** cannot be used to check whether floating-point numbers are equal.
**[Incorrect Example]**
```javascript
0.1 + 0.2 == 0.3; // false
0.1 + 0.2 === 0.3; // false
```
**[Correct Example]**
```javascript
const EPSILON = 1e-6;
const num1 = 0.1;
const num2 = 0.2;
const sum = 0.3;
if(Math.abs(num1 + num2 - sum) < EPSILON) {
...
}
```
## Do Not Define or Use Non-numeric Attributes (Except Length) for Arrays
**[Category] Rule**
**[Description]**
In JavaScript, an array is an object, which can be added with attributes. To facilitate processing and avoid errors, use an array to store only a group of ordered data, that is, data with continuous indexes. If attributes must be added, use **Map** or **Object** instead.
**[Incorrect Example]**
```javascript
const myHash = [];
myHash['key1'] = 'val1';
myHash['key2'] = 'val2';
myHash[0] = '222';
for (const key in myHash) {
// The value of key is 0, key1, and key2.
console.log(key);
}
console.log(myHash.length); // The array length is 1.
```
**[Correct Example]**
Use Map and Object for non-numeric attributes.
```javascript
const map = new Map();
map.set('key1', 'val1');
map.set('key2', 'val2');
for(const [key, value] of map) {
console.log('Attribute:' + key +', value: '+ value);
}
```
## Preferentially Use Array Object Methods for Array Traversal
**[Category] Rule**
**[Description]**
To traverse an array, preferentially use the methods provided by **Array**, such as **forEach()**, **map()**, **every()**, **filter()**, **find()**, **findIndex()**, **reduce()**, and **some()**.
Do not use **for in** to traverse an array.
**[Incorrect Example]**
```javascript
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
// Use for in to traverse the array.
for (const num in numbers) {
console.log(num);
sum += num;
}
// Use for to traverse an existing array to generate a new array.
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) {
increasedByOne.push(numbers[i] + 1);
}
```
**[Correct Example]**
```javascript
const numbers = [1, 2, 3, 4, 5];
// Use for of to traverse the array and obtain the sum.
let sum = 0;
for (const num of numbers) {
sum += num;
}
// Use forEach to traverse the array and obtain the sum.
let sum = 0;
numbers.forEach(num => sum += num);
// Better: Use the reduce method to obtain the sum.
const sum = numbers.reduce((total, num) => total + num, 0);
// Use forEach to traverse an existing array to generate a new array.
const increasedByOne = [];
numbers.forEach(num => increasedByOne.push(num + 1));
// Better: Use the map method.
const increasedByOne = numbers.map(num => num + 1);
```
# Operation and Expressions
## Use === and !==, Instead of == or !=, to Check Whether the Operands Are Equal
**[Category] Rule**
**[Description]**
In JavaScript, type conversion is automatically performed when the **==** operator is used for equality judgment. For example, the values of **[] == false**, **[] == ![]**, and **3 == '03'** are **true**. For higher efficiency, use **===** in comparison when the type is determined.
**[Incorrect Example]**
```javascript
age == bee
foo == true
bananas != 1
value == undefined
typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
```
**[Correct Example]**
```javascript
age === bee
foo === true
bananas !== 1
value === undefined
typeof foo === 'undefined'
'hello' !== 'world'
0 === 0
true === true
```
**[Exceptions]**
```javascript
// Use the following to determine whether an object is null:
obj == null
obj != null
```
## Do Not Assign Values in Control Conditional Expressions
**[Category] Rule**
**[Description]**
Control conditional expressions are usually used in conditional statements such as **if**, **while**, **for**, and **?:**.
Assigning values in this type of expression often leads to unexpected behavior and poor code readability.
**[Incorrect Example]**
```javascript
// It is difficult to understand the value assignment in the control conditional expression.
if (isFoo = false) {
...
}
```
**[Correct Example]**
```javascript
const isFoo = someBoolean; // Assign a value above and directly use it in the if statement.
if (isFoo) {
...
}
```
# Functions
## Use the Same Return Statement
**[Category] Rule**
**[Description]**
Unlike statically typed languages that force a function to return a value of a specified type, JavaScript allows different code paths in a function to return different types of values.
JavaScript returns **undefined** in the following cases:
1. The **return** statement is not executed before the exit.
1. The **return** statement is executed, but no value is explicitly assigned.
1. The **return undefined** statement is executed.
1. The **return void** statement is executed, followed by an expression (for example, a function call).
1. The **return** statement is executed, followed by another expression equivalent to **undefined**.
In a function (especially in a larger function), if any code path explicitly returns a value but the other code paths do not explicitly return a value, this may be a coding error. Therefore, use the same **return** statement in a function.
**[Incorrect Example]**
```javascript
function doSomething(condition) {
if (condition) {
...
return true;
} else {
...
return;
}
}
function doSomething(condition) {
if (condition) {
...
return true;
}
}
```
**[Correct Example]**
```javascript
// Ensure that all paths return values in the same way.
function doSomething(condition) {
if (condition) {
...
return true;
} else {
...
return false;
}
}
function doSomething(condition) {
if (condition) {
...
return true;
}
...
return false;
}
```
## Use rest Instead of arguments
**[Category] Rule**
**[Description]**
The **rest** parameter is an array, and all array methods, such as **sort**, **map**, **forEach**, and **pop**, can be directly used on it. **arguments** is a class array. Therefore, use the **rest** syntax instead of **arguments**. In addition, place the **rest** parameter as the last parameter in the list.
**[Incorrect Example]**
```javascript
function concatenateAll() {
// arguments is a class array, and the join method can be used only after arguments is converted to a real array.
const args = Array.prototype.slice.call(arguments);
return args.join('');
}
```
**[Correct Example]**
```javascript
function concatenateAll(...args) {
return args.join('');
}
```
## Do Not Assign this to a Variable; Use this in a Scope
**[Category] Rule**
**[Description]**
Arrow functions provide a simpler syntax. **this** in an arrow function points to the object when it is defined. Assigning **this** to a variable is confusing.
**[Incorrect Example]**
```javascript
function foo() {
const self = this;
return function() {
console.log(self);
};
}
```
**[Correct Example]**
```javascript
function foo() {
return () => {
console.log(this);
};
}
```
For details, see [@typescript-eslint/no-this-alias](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-this-alias.md).
The description of ESLint is stricter. Therefore, do not assign **this** to a variable in any case.
# Classes and Objects
## Use Dots to Access Object Attributes and [] to Access Computed Attributes
**[Category] Rule**
**[Description]**
In JavaScript, you can use dots (**foo.bar**) or square brackets (**foo['bar']**) to access attributes. The use of dots is preferred because it is more readable, concise, and more suitable for JavaScript compression.
**[Correct Example]**
```javascript
const name = obj.name;
const key = getKeyFromDB();
const prop = obj[key]; // Use [] only when the attribute name is a variable.
```
## Do Not Modify the Prototype of a Built-in Object or Add Methods to the Prototype
**[Category] Rule**
**[Description]**
As a set of public interfaces, built-in objects have conventional behavior modes. Any modification to the prototype of a built-in object may damage the semantics. Therefore, never modify the prototype of a built-in object, or add methods to the prototype.
**[Incorrect Example]**
```javascript
Array.prototype.indexOf = function () {
return -1;
}
// Used in other places.
const arr = [1, 1, 1, 1, 1, 2, 1, 1, 1];
console.log (arr.indexOf(2)); // Output -1.
```
## Do Not Delete the Computed Attributes of an Object
**[Category] Rule**
**[Description]**
The delete operation changes the layout of an object. Deleting the computed attributes of an object is a dangerous behavior. It greatly restricts the runtime optimization and affects the execution performance.
You are advised not to delete any attribute of an object. If necessary, use **map** and **set**.
**[Incorrect Example]**
```javascript
// Can be replaced with the constant equivalents, such as container.aaa
delete container['aaa'];
// Dynamic, difficult-to-reason-about lookups
const name = 'name';
delete container[name];
delete container[name.toUpperCase()];
```
**[Correct Example]**
```javascript
// The code affects the optimization performance to some extent, but it is better than deleting the computed attributes.
delete container.aaa;
delete container[7];
```
For details, see [@typescript-eslint/no-dynamic-delete](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-dynamic-delete.md).
# Exceptions
## Do Not Use return, break, continue, or throw to End the Finally Block Abnormally
**[Category] Rule**
**[Description]**
In the finally block, if the **return**, **break**, **continue**, or **throw** statement is directly used or the exception that occurs during the method calling is not handled, the finally block ends abnormally. Such a block affects the throwing of exceptions in the **try** or **catch** block, or even the return value of the method. Therefore, you must ensure that the finally block ends normally.
**[Incorrect Example]**
```javascript
function foo() {
try {
...
return 1;
} catch(err) {
...
return 2;
} finally {
return 3;
}
}
```
**[Correct Example]**
```javascript
function foo() {
try {
...
return 1;
} catch(err) {
...
return 2;
} finally {
console.log('XXX!');
}
}
```
# Async Functions
## Use return await Only When Necessary
**[Category] Rule**
**[Description]**
The return value of an async function is always encapsulated in **Promise.resolve**. The **return await** statement does not actually do anything, but adds time before **Promise.resolve** or **reject**. Therefore, use **return await** only in the **try** or **catch** statement to capture errors of another promise-based function.
**[Incorrect Example]**
```javascript
async function foo() {
return await bar();
}
```
**[Correct Example]**
```javascript
async function foo() {
return bar();
}
async function foo() {
await bar();
return;
}
async function foo() {
const baz = await bar();
return baz;
}
async function foo() {
try {
return await bar();
} catch (error) {
// here can be executed, go on
}
}
```
## Do Not Wait for a Non-thenable Value
**[Category] Rule**
**[Description]**
**await** converts a non-thenable value to a promise that has been processed normally and waits for the processing result. In this case, the use of **await** affects the code performance.
**[Incorrect Example]**
```javascript
async function f3() {
const y = await 20;
console.log(y); // 20
}
f3();
console.log(30);
// output
// 30
// 20
```
**[Correct Example]**
```javascript
async function f3() {
const y = 20;
console.log(y); // 20
}
f3();
console.log(30);
// output
// 20
// 30
```
For details, see [@typescript-eslint/await-thenable](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/await-thenable.md).
# Types
## Forcibly Mark null and undefined as Independent Types
**[Category] Rule**
**[Description]**
Marking **null** and **undefined** as independent types improves code security and avoids null pointer exceptions.
**[Incorrect Example]**
```javascript
let userName: string;
userName = 'hello';
userName = undefined;
```
**[Correct Example]**
```javascript
let userName: string | undefined;
userName = 'hello';
userName = undefined;
```
## Explicitly Declare the Return Value Types of Functions and Class Methods
**[Category] Rule**
**[Description]**
Explicitly declare the return value type to ensure that the return value is assigned to the variable of the correct type. In addition, the explicit declaration ensures that **undefined** is not assigned to a variable when there is no return value.
**[Incorrect Example]**
```javascript
// When there is no return value, the return value type is not declared as void.
function test() {
return;
}
// The return value type is not declared as number.
function fn() {
return 1;
};
// The return value type is not declared as string.
let arrowFn = () => 'test';
class Test {
// When there is no return value, the return value type is not declared as void.
method() {
return;
}
}
```
**[Correct Example]**
```javascript
// When there is no return value, explicitly declare the return value type as void.
function test(): void {
return;
}
// Explicitly declare the return value type as number.
function fn(): number {
return 1;
};
// Explicitly declare the return value type as string.
let arrowFn = (): string => 'test';
class Test {
// When there is no return value, explicitly declare the return value type as void.
method(): void {
return;
}
}
```
For details, see [@typescript-eslint/explicit-function-return-type](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-function-return-type.md).
## Use Consistent Export Types
**[Category] Rule**
**[Description]**
To export a type, write the type to export and the objects to export separately.
**[Incorrect Example]**
```javascript
interface ButtonProps {
onClick: () => void;
}
class Button implements ButtonProps {
onClick() {
console.log('button!');
}
}
export { Button, ButtonProps };
```
**[Correct Example]**
```javascript
interface ButtonProps {
onClick: () => void;
}
class Button implements ButtonProps {
onClick() {
console.log('button!');
}
}
export { Button };
export type { ButtonProps };
```
For details, see [@typescript-eslint/consistent-type-exports](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/consistent-type-exports.md).
## Use Consistent Import Types
**[Category] Rule**
**[Description]**
To import a type, write the type to import and the objects to import separately.
**[Incorrect Example]**
```javascript
import { Foo } from 'Foo';
import Bar from 'Bar';
type T = Foo;
const x: Bar = 1;
```
**[Correct Example]**
```javascript
import type { Foo } from 'Foo';
import type Bar from 'Bar';
type T = Foo;
const x: Bar = 1;
```
For details, see [@typescript-eslint/consistent-type-imports](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/consistent-type-imports.md).
## Do Not Use any
**[Category] Rule**
**[Description]**
If the **any** type is used, all type checks during compilation are ignored. This behavior is not necessary and does not meet expectations. If the type is unknown, use **unknown**.
If the introduced third-party component does not use TypeScript or does not provide the TypeScript type declaration, you can use **any** to declare the related third-party component objects.
## Do Not Define the any Type
**[Category] Rule**
**[Description]**
Do not define the **any** type. This restriction makes types as clear as possible in TypeScript and helps the runtime optimization.
**[Incorrect Example]**
```javascript
const age: any = 'seventeen';
function greet(): any {}
function greet(param: Array<any>): string {}
```
**[Correct Example]**
```javascript
const age: number = 17;
function greet(): string {}
function greet(param: Array<string>): string {}
```
For details, see [@typescript-eslint/no-explicit-any](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-explicit-any.md).
## Do Not Pass In any as a Parameter
**[Category] Rule**
**[Incorrect Example]**
```javascript
declare function foo(arg1: string, arg2: number, arg3: string): void;
const anyTyped = 1 as any;
foo(...anyTyped);
foo(anyTyped, 1, 'a');
const tuple1 = ['a', anyTyped, 'b'] as const;
foo(...tuple1);
```
**[Correct Example]**
```javascript
declare function foo(arg1: string, arg2: number, arg3: string): void;
foo('a', 1, 'b');
const tuple1 = ['a', 1, 'b'] as const;
foo(...tuple1);
```
For details, see [@typescript-eslint/no-unsafe-argument](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-argument.md).
## Do Not Use any in Value Assignment
**[Category] Rule**
**[Incorrect Example]**
```javascript
const x = 1 as any,
const x: Set<string> = new Set<any>();
```
**[Correct Example]**
```javascript
const x = 1;
const x: Set<string> = new Set<string>();
```
For details, see [@typescript-eslint/no-unsafe-assignment](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md).
## Do Not Call a Variable with the any Type
**[Category] Rule**
**[Incorrect Example]**
```javascript
declare const anyVar: any;
declare const nestedAny: { prop: any };
anyVar();
anyVar.a.b();
nestedAny.prop();
nestedAny.prop['a']();
```
**[Correct Example]**
```javascript
declare const typedVar: () => void;
declare const typedNested: { prop: { a: () => void } };
typedVar();
typedNested.prop.a();
```
For details, see [@typescript-eslint/no-unsafe-call](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-call.md).
## Do Not Access Members of an Object with the any Type
**[Category] Rule**
**[Incorrect Example]**
```markup
declare const anyVar: any;
declare const nestedAny: { prop: any };
anyVar.a;
anyVar.a.b;
nestedAny.prop.a;
nestedAny.prop['a'];
```
**[Correct Example]**
```javascript
declare const properlyTyped: { prop: { a: string } };
properlyTyped.prop.a;
properlyTyped.prop['a'];
```
For details, see [@typescript-eslint/no-unsafe-member-access](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-member-access.md).
## Do Not Declare the Return Value Type of a Function as any or any[]
**[Category] Rule**
**[Incorrect Example]**
```javascript
function foo1() {
return 1 as any;
}
```
**[Correct Example]**
```javascript
function foo1() : number {
return 1;
}
```
For details, see [@typescript-eslint/no-unsafe-return](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-return.md).
# References
1. [JavaScript Coding Style Guide](OpenHarmony-JavaScript-coding-style-guide.md)
1. [ESLint Rules](https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/eslint-plugin/docs/rules)
1. High Performance JavaScript
# OpenHarmony Part Design Guide # OpenHarmony Component Design Guide
## About This Document ## Basic Concepts
For easy software design and management, OpenHarmony decouples software from physical components, parts, and modules. A **component** can be independently deployed and reused at the binary level. A **part** can be independently developed, built, and tested. A **module** can be reused at the code level. For easy software design and management, OpenHarmony decouples software from images, components (named components originally), and modules. Their relationship is shown below.
OpenHarmony abstracts system capabilities as parts, so you can assemble and configure these parts to customize an OS for different devices. ![](figures/Component-Module.png)
## Part Definition ### Component Definition
A part is the basic unit of system capabilities. Divided based on source code, every part has independent files and directories, and can be instantiated into libraries or executable files on different devices. OpenHarmony abstracts system capabilities as components, so you can customize OSs for different devices by assembling and configuring these components.
## Part Division A component is the basic unit of system capabilities. Divided based on source code, every component has independent files and directories, and can be instantiated into libraries or executable files on different devices.
Observe the following rules for part classification: The introduction of components is to enable a set of OS code to support a variety of product forms, thereby solving the problem of hardware and product fragmentation in different industries and improving the device development efficiency.
- A part must have an independent code directory for compiling libraries or executable files. ![](figures/Component-Definition.png)
- A part must be able to be independently deployed in the small system or standard system. Optional parts can be tailored without causing system exceptions. ## Component Design
- Functions of a part must be able to be independently tested and verified. ### Component Classification Rules
A part always belongs to a specific subsystem. A subsystem is a logical concept and consists of specific parts. When developing a new function that is optional and can be tailored, add a component, rather than a module. In addition, observe the following rules:
Note the following: - A component must have an independent code directory for compiling libraries or executable files.
- A component must be able to be independently deployed in the small system or standard system. Optional functions can be tailored without causing system exceptions.
- A component must be able to be independently tested and verified.
- External APIs provided by a part must be the same regardless of whether the configurable features of the part are configured. ### **Rules and Recommendations**
- Dependent third-party open source software libraries and parts that provide basic capabilities are called **dependent parts**, which must be deployed with other parts. Comply with the following rules and recommendations during component design:
- If a part can be split into smaller functional modules and provide APIs for applications, these modules are called **child parts**, which must be deployed with the parent part. A child part depends on a parent part, but a parent part does not depend on a child part. **Rule 1.1** Components must be developed individually to ensure decoupling and independence.
## Basic Principles **Rule 1.2** A common component should not depend on a specific chip, development board, or product form, except for a component related to drivers and kernels.
Comply with the following rules and recommendations during parts design and development: **Rule 1.3** All components in the minimum system component set are mandatory. They should not depend on an optional component outside the minimum system component set.
**Rule 1.1** Parts must be developed individually to ensure decoupling and independence. > For details about the definition of the minimum system and the minimum system component set, see **PCS** in [OpenHarmony Product Compatibility Specifications](https://www.openharmony.cn/certification/document/pcs).
**Rule 1.2** Parts must be managed in a decentralized manner. The dependency between parts must be simple, clear, and reasonable. **Rule 1.4** New components must be reviewed by architects and designers in the respective domain.
**Rule 1.3** Reverse dependency and cyclic dependency between parts are prohibited. Lower-layer parts must not depend on upper-layer parts. **Rule 1.5** Reverse dependency and cyclic dependency between components are prohibited. Lower-layer components must not depend on upper-layer components.
**Rule 1.4** It is prohibited that the implementation of a part depends on a specific development board or product form. **Rule 1.6** Application APIs provided by a component must be stable and compatible with earlier versions. Deprecated APIs must be reclaimed as planned.
**Rule 1.5** APIs provided by a part must be stable and compatible. Changes to released APIs are prohibited. **Rule 1.7** External APIs provided by a component must be the same regardless of whether the configurable features of the component are configured.
**Rec 1.1** Parts should support automated build and verification. **Rule 1.8** The component name must reflect the key function of a component and must be globally unique in the system. The name can contain a maximum of 63 characters and must be in the unix_like style, where only lowercase letters separated by underscores (\_) are used.
## Naming Rules **Rule 1.9** The component repository must be named in the format of <Subsystem\>\_<Component\>. For example, the repository name of the storage service component in the file management subsystem is **filemanagement\_storage\_service**. The repository name can contain a maximum of 100 characters.
#### **Part Name** > **NOTE**
The name must reflect the key function of a part and must be globally unique in the system. It can contain a maximum of 63 characters and must be in the unix\_like style, where only lowercase letters separated by underscores (\_) are used.
#### **Repository Name**
The part repository is named in the format of <Subsystem\>\_<Part\>. For example, the repository name of the storage service part in the file management subsystem is **filemanagement\_storage\_service**. The repository name can contain a maximum of 100 characters.
> Note:
> >
> 1. In principle, there is a one-to-one mapping between parts and repositories. In some cases, multiple parts can share a repository, but they must have independent directories. > 1. In principle, there is a one-to-one mapping between components and repositories. In some cases, multiple components can share a repository, but they must have independent directories.
> >
> 2. For a third-party open source part, use the original name with the prefix **third\_party**. All third-party open source parts are stored in the **third\_party** directory. > 2. For a third-party open source component, retain the original component name, and add the prefix **third_party** to the repository name. All third-party open source components are stored in the **third_party** directory.
> >
> 3. The subsystem names in the repository name and path should not contain underscores (\_). > 3. The subsystem names in the repository name and path should not contain underscores (\_).
#### **Path** **Rule 1.10**: The component source code path must be in the format of <Domain\>/<Subsystem\>/<Component\>, for example, **foundation/filemanagement/storage_service**.
The part name must be in the format of <Domain\>/<Subsystem\>/<Part\>, for example, **foundation/filemanagement/storage_service**.
#### **Part Directory Structure** **Rule 1.11** The component directory structure must be as follows:
```xml ```xml
├── interfaces # APIs ├── interfaces # APIs
│ ├── kits # Application APIs (optional) │ ├── kits # Application APIs (optional)
│ │ ├── js # JS APIs (optional) │ │ ├── js # JS APIs (optional)
│ │ └── native # C/C++ APIs (optional) │ │ └── native # C/C++ APIs (optional)
│ └── inner_api # Internal APIs of parts │ └── inner_api # Internal APIs of components
├── frameworks # Implementation of the part without independent processes (optional) ├── frameworks # Implementation of components without independent processes (optional)
│ ├── native # C/C++ API implementation (optional) │ ├── native # C/C++ API implementation (optional)
│ └── js # JS API implementation (optional) │ └── js # JS API implementation (optional)
│ ├── napi # Native API implementation (optional) │ ├── napi # Native API implementation (optional)
│ ├── builtin # Specific to LiteOS-M (optional) │ ├── builtin # Specific to LiteOS-M (optional)
│ └── plugin # Specific to ArkUI (optional) │ └── plugin # Specific to ArkUI (optional)
├── services # Implementation of parts with independent processes (optional) ├── services # Implementation of components with independent processes (optional)
├── test # Test code (mandatory) ├── test # Test code (mandatory)
├── BUILD.gn # Entry to build (mandatory) ├── BUILD.gn # Entry to build (mandatory)
└── bundle.json # Part description file (mandatory) └── bundle.json # Component description file (mandatory)
```
**Rec 1.1** Components should support automated build and verification.
### System Capabilities
System capabilities are provided by components. A system capability can be bound to one or more APIs. System capabilities function as a bridge between device development and application development. The differences in devices assembled with various components are represented by different system capabilities. In other words, the APIs that can be used vary according to the device in use. The figure below shows how system capabilities are used in the entire development process.
![](figures/Component-SysCap.png)
1. An application developer uses the normalized SDK that supports multiple devices to develop an application. The SDK contains a full set of system capabilities (optional and mandatory) and corresponding APIs.
2. A device developer assembles optional components and adds private components to form the system capability set of a device.
3. The system capability set is automatically written to the device during compilation and packaging.
4. A Product Compatibility ID (PCID) is automatically generated during device compilation. When developing an application for a specific device, the application developer imports the PCID to DevEco Studio to obtain the system capability set of the device during development.
5. A Required Product Compatibility ID (RPCID), a set of system capabilities required by the application, is automatically generated during application compilation and packaging.
6. When distributing an application, the application market matches the application's RPCID against the device's PCID. It distributes the application to that device only if the application's RPCID is within the device's PCID.
7. In the ability continuation scenario, the system capabilities are synchronized between devices.
8. In the installation-free scenario, the system capabilities of a device can be queried on the cloud.
#### Using System Capabilities During Application Development
An application developer can call the **CanIUse** API to query the system capabilities of a device at runtime. The code snippet is as follows:
```javascript
import geolocation from '@ohos.geolocation'
const isLocationAvailable = canIUse('SystemCapability.Location.Location');
if (isLocationAvailable) {
geolocation.getCurrentLocation((location) => {
console.log(location.latitude, location.longitue);
});
} else {
console.log('Location not by this device.')
}
```
The SDK defines the system capability set for typical device types. If a device type is selected during application development and the API called exceeds the range supported by the mandatory system capabilities of the device type, DevEco Studio displays a message indicating that the API is not supported by the device and the application compilation will fail.
#### Defining System Capabilities During Device Development
There is a one-to-one relationship between components and system capabilities, and the APIs mapped to different system capabilities do not overlap. A system capability must be named in the format of SystemCapability.Category. Feature.Subfeature (optional), for example, **SystemCapability.Media.Camera** and **SystemCapability.Media.Camera.Front**. Generally, a subfeature is implemented by an independent component. This component depends on a component that provides the basic feature, and therefore the dependent component must also be assembled into the product.
1. Declare the system capability in the **bundle.json** file of the component. The code snippet is as follows:
```json
{
...
"component": {
"name": "camera", # Component name.
"syscap": [ "SystemCapability.Media.Camera" ] # System capability of the component.
},
...
}
```
2. Declare the system capability attribute of the API in the corresponding .d.ts file for binding. The code snippet is as follows:
```js
/**
* @name camera
* @syscap SystemCapability.Media.Camera
* @ since 9
*/
declare namespace camera {
...
}
```
### Component Review
The addition, modification (function or interface changes), and deletion of components must be reviewed by the architecture SIG and [related domain SIGs](https://gitee.com/openharmony/community/tree/master/sig). The review process is as follows:
1. Prepare the following component attribute review form.
Table 1 Component attribute review form
| Component Attribute | Description |
| ------------ | ------------------------------------------------------------ |
| Component name | The name must reflect the key function of a component and must be globally unique in the system. The name can contain a maximum of 63 characters and must be in the unix\_like style, where only lowercase letters separated by underscores (\_) are used.|
| Subsystem | Subsystem to which the component belongs. |
| Function description | Brief description of the functions of the component in one or two sentences. |
| Configurable features | Features that can be configured externally. |
| SysCap | System capability, for example, **SystemCapability.Media.Camera** or **SystemCapability.Media.Camera.Front**.|
| Applicable systems| Mini system, small system, standard system, or their combinations. |
| Source code directory | Root directory of the source code of the component. |
| ROM | ROM baseline value of the component. |
| RAM | RAM baseline value of the component. |
| Dependencies | Components and open source software on which the component depends. |
2. Send an email to the architecture SIG (dev@openharmony.io) and the [related domain SIG leaders](https://gitee.com/openharmony/community/tree/master/sig) for review. Use "Applying for Adding/Modifying/Deleting OpenHarmony Components" as the email subject, and include the filled-in **Table 1 Component Attribute Review Form** in the email body.
> For deleted components, provide the plan for stopping component maintenance. Exercise caution when deleting or modifying components and evaluate the impact on existing versions.
3. After the review is passed, create a component repository and modify the manifest according to [SIG Management Regulations](https://gitee.com/openharmony/community/blob/master/sig/README_EN.md). After the SIG is incubated, incorporate it into the main code library of OpenHarmony.
## Component Development
After the component passes the review, the component name, repository, and source code path are determined. You can perform component development as follows:
### Adding a Description File
In the development state, create a **bundle.json** file in the root directory of the component. The file contains the component name, compilation, test, system capability, features, and internal interfaces. For details about the fields, see [Description File](../device-dev/subsystems/subsys-build-component-building-rules.md#description-file). The code snippet is as follows:
```json
{
"name": "@ohos/my_component",
"description": "my first component",
"version": "4.0",
"license": "Apache License 2.0",
"publicAs": "code-segment",
"segment": {
"destPath": "my_domain/my_subsystem/my_component"
},
"component": {
"name": "my_component",
"subsystem": "my_subsystem",
"syscap": [
"SystemCapability.MySubsystem.MyComponent"
],
"build": {
"moudles": [
"//my_domain/my_subsystem/my_component/my_module:my_module"
],
"inner_api": [
"name": "//my_domain/my_subsystem/my_component/my_module:inner_api",
"header_base": "//my_domain/my_subsystem/my_component/interfaces/inner_api/my_module"
],
"test": [
"//my_domain/my_subsystem/my_component:unit_test"
]
}
}
}
``` ```
## Adding, Deleting, or Modifying Parts **inner_api** is an interface declared by the component for dependency between components within the system. The dependency must be specified in **external_deps**. The following is an example:
The addition, deletion, and modification of parts must be reviewed by the architecture SIG and [related domain SIGs](https://gitee.com/openharmony/community/blob/master/sig/sigs_subsystem_list.md). The review process is as follows: ```c
ohos_executable("other_component") {
...
external_deps = [ "my_module:inner_api" ]
}
```
### Adding a Compilation Script
In the **bundle.json** file, **build:modules** provides the component compilation entry. The following is an example of the compilation script of the **my_module** module in the dynamic library:
```c
ohos_shared_library("my_module") {
sources = [ ... ]
...
external_deps = [ ... ]
part_name = "my_component"
subsystem_name = "my_subsystem"
}
```
1. Prepare the following part attribute review form. The component compilation script must comply with component-based requirements. For details, see [Component Building Specifications](../device-dev/subsystems/subsys-build-component-building-rules.md#component-building-specifications).
### Compilation Verification
After adding the description file and compilation script of the component, compile the code source to develop the functions of the component. To enable the compilation of a component, configure the component in the product configuration file. The following is an example:
```json
{
"product_name": "my_product",
"device_company": "my_device_company",
"target_cpu": "arm",
...
"subsystems": [
{
"subsystem": "my_subsystem",
"components": [
{
"component": "my_component"
}
]
},
...
]
}
```
The following code snippet is used to compile a component separately:
```c
./build.sh --product-name my_product --build-target my_domain/my_subsystem/my_component/my_module:my_module
```
Table 1 Part attribute review form Upload the compilation products and test cases of the component to the device to verify the functions.
Full compilation can also be used to verify a new component. For details, see [Adding and Compiling Components](../device-dev/subsystems/subsys-build-component.md#adding-and-building-a-component).
## Assembling Components
The product configuration file ***vendor*/*{company}*/*{product}*/config.json** can be used to assemble a product form based on the component and feature dimensions. It allows device developers to quickly build a product without intrusively modifying OpenHarmony source code. The product configuration includes the product name, development board, subsystems, and components. The following is an example:
```json
{
"product_name": "my_product",
"device_company": "my_device_company",
"target_cpu": "arm64",
"subsystems": [
{
"subsystem": "my_subsystem",
"components": [
{
"component": "my_component",
"features": []
}
]
},
...
]
}
```
| Part Attribute | Description | The compilation command is **./build.sh --product-name my_product**.
| ------------ | ------------------------------------------------------------ |
| Part name | The name must reflect the key function of a part and must be globally unique in the system. The name can contain a maximum of 63 characters and must be in the unix\_like style, where only lowercase letters separated by underscores (\_) are used. |
| Subsystem | Subsystem to which the part belongs. |
| Function description | Brief description of the functions of the part in one or two sentences. |
| Configurable features | Features that can be configured externally. |
| Applicable systems | Mini system, small system, standard system, or their combinations. |
| Source code directory | Root directory of the source code of the part. |
| ROM | ROM baseline value of the part. |
| RAM | RAM baseline value of the part. |
| Dependencies | Parts and open source software on which the part depends. |
### Determining Whether a Component Is Required
2. Send an email to the architecture SIG (dev@openharmony.io) and the [related domain SIG leaders](https://gitee.com/openharmony/community/blob/master/sig/sigs_subsystem_list.md) for review. Use "Application for Adding/Deleting/Modifying OpenHarmony Parts" as the email subject, and include the filled-in **Table 1 Part Attribute Review Form** in the email body. A component set can be configured for a product based on hardware and product functions. For example, NFC-related components are not configured on a device that does not need to provide the NFC feature.
> Note: > **NOTE**
>
> 1. The minimum system component set must be configured by default.
> >
> For modified parts, provide a before and after comparison of the part attributes. For deleted parts, provide the plan for stopping part maintenance. Exercise caution when deleting or modifying parts and evaluate the impact on existing versions. > 2. A component and its dependent components must be configured together. Otherwise, the compilation fails.
### Configuring Features
#### During Compilation
A feature in the **bundle.json** file of a component is the compilation state option declared by the component. It can be of the Boolean, numeric, or string type. The feature in the product configuration file can be changed to the default value provided by the component. For example, the screen saver feature of power management is disabled by default. You can enable it in the product as follows:
```json
{
{
"subsystem": "powermgr",
"components": [
{ "component": "powermgr", "features":[ "powermgr_screensaver_enable = true" ] }
]
}
}
```
For details about the feature configuration, see [Feature](../device-dev/subsystems/subsys-build-feature.md).
#### Runtime
For complex components, system parameters can be read or custom configuration files can be used during runtime to load different features, thereby meeting diverse product requirements. With feature configuration at the runtime, a component needs to be compiled only once. For different products, you only need to modify system parameters or configuration files during assembly and then create images.
### Inheritance
The product configuration file can inherit the component set through the **inherit** field. Currently, OpenHarmony provides two types of components: minimum system component set and typical product form set, which are defined in the **productdefine/common/base** and **productdefine/common/inherit** directories, respectively. The following is an example of inheriting the minimum system component set:
```json
{
"inherit": [ "productdefine/common/base/standard_system.json" ],
}
```
3. After the review is passed, create a part repository and modify the manifest according to [SIG Management Regulations](https://gitee.com/openharmony/community/blob/master/sig/README_EN.md). After the SIG is incubated, incorporate it into the main code library of OpenHarmony. Inheritance can simplify product configuration and improve efficiency.
...@@ -18,6 +18,10 @@ ...@@ -18,6 +18,10 @@
- [Configuring Parameters for Accelerating Local Build](subsys-build-reference.md) - [Configuring Parameters for Accelerating Local Build](subsys-build-reference.md)
- [Viewing Ninja Build Information](subsys-build-reference.md) - [Viewing Ninja Build Information](subsys-build-reference.md)
- [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md) - [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md)
- Rust Build Guide
- [Rust Module Configuration Rules and Guide](subsys-build-rust-compilation.md)
- [Using Interactive Tools](subsys-build-bindgen-cxx-guide.md)
- [Using Cargo2gn](subsys-build-cargo2gn-guide.md)
- [FAQs](subsys-build-FAQ.md) - [FAQs](subsys-build-FAQ.md)
- [ArkCompiler Development](subsys-arkcompiler-guide.md) - [ArkCompiler Development](subsys-arkcompiler-guide.md)
- [Distributed Remote Startup](subsys-remote-start.md) - [Distributed Remote Startup](subsys-remote-start.md)
......
# Interactive Tool User Guide
## Introduction
You can use Bindgen and CXX to implement the interaction between Rust and C/C++. Bindgen enables Rust to call C by converting C interfaces into Rust interfaces. CXX implement interaction between C++ and Rust by generating bindings between C interfaces and Rust interfaces.
![bindgen_and_cxx_tools](./figures/bindgen_and_cxx_tools.png)
## Using Bindgen
### Procedure
The following example shows how to use Bindgen to implement invocation of C by Rust.
1. In the header file **lib.h**, define two interfaces **FuncAAddB** and **SayHello** in C. The **FuncAAddB** interface calculates the sum of two numbers, and the **SayHello** interface prints strings.
```c
#ifndef BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_
#define BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_
#include <stdint.h>
#include "build/rust/tests/test_bindgen_test/test_for_hello_world/lib2.h"
uint32_t FuncAAddB(uint32_t a, uint32_t b);
void SayHello(const char *message);
#endif // BUILD_RUST_TESTS_BINDGEN_TEST_LIB_H_
```
2. Add the implementation of the two interfaces to **lib.c**.
```c
#include "build/rust/tests/test_bindgen_test/test_for_hello_world/lib.h"
#include <stdint.h>
#include <stdio.h>
void SayHello(const char *message)
{
printf("This is a test for bindgen hello world:\n");
printf("%s\n", message);
}
uint32_t FuncAAddB(uint32_t a, uint32_t b)
{
printf("This is a test for bindgen of a + b:\n");
return a + b;
}
```
3. Create the **main.rs** file to call C interfaces through c_ffi using Rust. Note that insecure interfaces called by Rust must be encapsulated by using **unsafe**.
```rust
//! bindgen test for hello world
#![allow(clippy::approx_constant)]
mod c_ffi {
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
include!(env!("BINDGEN_RS_FILE"));
}
/// pub fn add_two_numbers_in_c
pub fn add_two_numbers_in_c(a: u32, b: u32) -> u32 {
unsafe { c_ffi::FuncAAddB(a, b) }
}
use std::ffi::c_char;
use std::ffi::CString;
/// fn main()
fn main() {
println!("{} + {} = {}", 3, 7, add_two_numbers_in_c(3, 7));
let c_str = CString::new("This is a message from C").unwrap();
let c_world: *const c_char = c_str.as_ptr() as *const c_char;
unsafe {
c_ffi::SayHello(c_world);
}
}
```
4. Create the **BUILD.gn** file to define the dependency of the Rust module on the C module.
```GN
import("//build/ohos.gni")
ohos_shared_library("c_lib") {
sources = [ "lib.c" ]
defines = [ "COMPONENT_IMPLEMENTATION" ]
}
rust_bindgen("c_lib_bindgen") {
header = "lib.h"
}
ohos_rust_executable("bindgen_test") {
deps = [ ":c_lib" ]
deps += [ ":c_lib_bindgen" ]
sources = [ "main.rs" ]
bindgen_output = get_target_outputs(":c_lib_bindgen")
inputs = bindgen_output
rustenv = [ "BINDGEN_RS_FILE=" + rebase_path(bindgen_output[0]) ]
crate_root = "main.rs"
}
```
**Verification**
![bindgen_test](./figures/bindgen_test.png)
## Using CXX
### Calling Rust Interfaces by C++
1. In the Rust **lib.rs** file, add the C++ interfaces to be called in **mod ffi**, and add the interfaces in **extern "Rust"** to expose them to C++.
```rust
//! #[cxx::bridge]
#[cxx::bridge]
mod ffi{
#![allow(dead_code)]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Shared {
z: usize,
}
extern "Rust"{
fn print_message_in_rust();
fn r_return_primitive() -> usize;
fn r_return_shared() -> Shared;
fn r_return_rust_string() -> String;
fn r_return_sum(_: usize, _: usize) -> usize;
}
}
fn print_message_in_rust(){
println!("Here is a test for cpp call Rust.");
}
fn r_return_shared() -> ffi::Shared {
println!("Here is a message from Rust,test for ffi::Shared:");
ffi::Shared { z: 1996 }
}
fn r_return_primitive() -> usize {
println!("Here is a message from Rust,test for usize:");
1997
}
fn r_return_rust_string() -> String {
println!("Here is a message from Rust,test for String");
"Hello World!".to_owned()
}
fn r_return_sum(n1: usize, n2: usize) -> usize {
println!("Here is a message from Rust,test for {} + {} is:",n1 ,n2);
n1 + n2
}
```
2. Include **lib.rs.h** (converted from **lib.rs** by the CXX tool) in C++ code.
```c++
#include <iostream>
#include "build/rust/tests/test_cxx/src/lib.rs.h"
int main(int argc, const char* argv[])
{
int a = 2021;
int b = 4;
print_message_in_rust();
std::cout << r_return_primitive() << std::endl;
std::cout << r_return_shared().z << std::endl;
std::cout << std::string(r_return_rust_string()) << std::endl;
std::cout << r_return_sum(a, b) << std::endl;
return 0;
}
```
3. Create the **BUILD.gn** file. The underlying rust_cxx calls the CXX tool to convert the **lib.rs** file into **lib.rs.h** and **lib.rs.cc**. **ohos_rust_static_ffi** implements compilation of the Rust source code, and **ohos_executable** implements compilation of the C++ code.
```
import("//build/ohos.gni")
import("//build/templates/rust/rust_cxx.gni")
rust_cxx("test_cxx_exe_gen") {
sources = [ "src/lib.rs" ]
}
ohos_rust_static_ffi("test_cxx_examp_rust") {
sources = [ "src/lib.rs" ]
deps = [ "//build/rust:cxx_rustdeps" ]
}
ohos_executable("test_cxx_exe") {
sources = [ "main.cpp" ]
sources += get_target_outputs(":test_cxx_exe_gen")
include_dirs = [ "${target_gen_dir}" ]
deps = [
":test_cxx_examp_rust",
":test_cxx_exe_gen",
"//build/rust:cxx_cppdeps",
]
}
```
**Verification**
![cpp_call_rust](./figures/cpp_call_rust.png)
### Calling C++ by Rust
1. Create the header file **client_blobstore.h**.
```c++
#ifndef BUILD_RUST_TESTS_CLIENT_BLOBSTORE_H
#define BUILD_RUST_TESTS_CLIENT_BLOBSTORE_H
#include <memory>
#include "third_party/rust/cxx/include/cxx.h"
namespace nsp_org {
namespace nsp_blobstore {
struct MultiBufs;
struct Metadata_Blob;
class client_blobstore {
public:
client_blobstore();
uint64_t put_buf(MultiBufs &buf) const;
void add_tag(uint64_t blobid, rust::Str add_tag) const;
Metadata_Blob get_metadata(uint64_t blobid) const;
private:
class impl;
std::shared_ptr<impl> impl;
};
std::unique_ptr<client_blobstore> blobstore_client_new();
} // namespace nsp_blobstore
} // namespace nsp_org
#endif
```
2. Create the **client_blobstore.cpp** file.
```c++
#include <algorithm>
#include <functional>
#include <set>
#include <string>
#include <unordered_map>
#include "src/main.rs.h"
#include "build/rust/tests/test_cxx_rust/include/client_blobstore.h"
namespace nsp_org {
namespace nsp_blobstore {
// Toy implementation of an in-memory nsp_blobstore.
//
// The real implementation of client_blobstore could be a large complex C++
// library.
class client_blobstore::impl {
friend client_blobstore;
using Blob = struct {
std::string data;
std::set<std::string> tags;
};
std::unordered_map<uint64_t, Blob> blobs;
};
client_blobstore::client_blobstore() : impl(new class client_blobstore::impl) {}
// Upload a new blob and return a blobid that serves as a handle to the blob.
uint64_t client_blobstore::put_buf(MultiBufs &buf) const
{
std::string contents;
// Traverse the caller's res_chunk iterator.
//
// In reality there might be sophisticated batching of chunks and/or parallel
// upload implemented by the nsp_blobstore's C++ client.
while (true) {
auto res_chunk = next_chunk(buf);
if (res_chunk.size() == 0) {
break;
}
contents.append(reinterpret_cast<const char *>(res_chunk.data()), res_chunk.size());
}
// Insert into map and provide caller the handle.
auto res = std::hash<std::string> {} (contents);
impl->blobs[res] = {std::move(contents), {}};
return res;
}
// Add add_tag to an existing blob.
void client_blobstore::add_tag(uint64_t blobid, rust::Str add_tag) const
{
impl->blobs[blobid].tags.emplace(add_tag);
}
// Retrieve get_metadata about a blob.
Metadata_Blob client_blobstore::get_metadata(uint64_t blobid) const
{
Metadata_Blob get_metadata {};
auto blob = impl->blobs.find(blobid);
if (blob != impl->blobs.end()) {
get_metadata.size = blob->second.data.size();
std::for_each(blob->second.tags.cbegin(), blob->second.tags.cend(),
[&](auto &t) { get_metadata.tags.emplace_back(t); });
}
return get_metadata;
}
std::unique_ptr<client_blobstore> blobstore_client_new()
{
return std::make_unique<client_blobstore>();
}
} // namespace nsp_blobstore
} // namespace nsp_org
```
3. In **ffi** of the **main.rs** file, use the macro **includes!** to import the header file **client_blobstore.h**. Then, the **main()** function of Rust can call the C++ interfaces in ffi mode.
```rust
//! test_cxx_rust
#[cxx::bridge(namespace = "nsp_org::nsp_blobstore")]
mod ffi {
// Shared structs with fields visible to both languages.
struct Metadata_Blob {
size: usize,
tags: Vec<String>,
}
// Rust types and signatures exposed to C++.
extern "Rust" {
type MultiBufs;
fn next_chunk(buf: &mut MultiBufs) -> &[u8];
}
// C++ types and signatures exposed to Rust.
unsafe extern "C++" {
include!("build/rust/tests/test_cxx_rust/include/client_blobstore.h");
type client_blobstore;
fn blobstore_client_new() -> UniquePtr<client_blobstore>;
fn put_buf(&self, parts: &mut MultiBufs) -> u64;
fn add_tag(&self, blobid: u64, add_tag: &str);
fn get_metadata(&self, blobid: u64) -> Metadata_Blob;
}
}
// An iterator over contiguous chunks of a discontiguous file object.
//
// Toy implementation uses a Vec<Vec<u8>> but in reality this might be iterating
// over some more complex Rust data structure like a rope, or maybe loading
// chunks lazily from somewhere.
/// pub struct MultiBufs
pub struct MultiBufs {
chunks: Vec<Vec<u8>>,
pos: usize,
}
/// pub fn next_chunk
pub fn next_chunk(buf: &mut MultiBufs) -> &[u8] {
let next = buf.chunks.get(buf.pos);
buf.pos += 1;
next.map_or(&[], Vec::as_slice)
}
/// fn main()
fn main() {
let client = ffi::blobstore_client_new();
// Upload a blob.
let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()];
let mut buf = MultiBufs { chunks, pos: 0 };
let blobid = client.put_buf(&mut buf);
println!("This is a test for Rust call cpp:");
println!("blobid = {}", blobid);
// Add a add_tag.
client.add_tag(blobid, "rust");
// Read back the tags.
let get_metadata = client.get_metadata(blobid);
println!("tags = {:?}", get_metadata.tags);
}
```
4. Create the **BUILD.gn** file. Use CXX to convert **main.rs** into **lib.rs.h** and **lib.rs.cc**, which are used as the source code of **test_cxx_rust_staticlib**. Compile Rust **main.rs**, and add the dependency **test_cxx_rust_staticlib**.
```
import("//build/ohos.gni")
rust_cxx("test_cxx_rust_gen") {
sources = [ "src/main.rs" ]
}
ohos_static_library("test_cxx_rust_staticlib") {
sources = [ "src/client_blobstore.cpp" ]
sources += get_target_outputs(":test_cxx_rust_gen")
include_dirs = [
"${target_gen_dir}",
"//third_party/rust/cxx/v1/crate/include",
"include",
]
deps = [
":test_cxx_rust_gen",
"//build/rust:cxx_cppdeps",
]
}
ohos_rust_executable("test_cxx_rust") {
sources = [ "src/main.rs" ]
deps = [
":test_cxx_rust_staticlib",
"//build/rust:cxx_rustdeps",
]
}
```
**Verification**
![rust_call_cpp](./figures/rust_call_cpp.png)
# Using Cargo2gn
## Overview
Rust uses Cargo as its build system and package manager. **Cargo.toml** is the manifest file of Cargo. It contains metadata such as the name, version, and dependencies for crates (packages) in Rust.
When used in OpenHarmony, **Cargo.toml** needs to be converted into **BUILD.gn** rules. cargo2gn is the tool that can achieve this purpose. It can convert one or more Rust libraries.
## Converting a Single Library
1. Go to the directory of the rust library to be converted, for example, **bindgen**.
```
cd openharmony/third_party/rust/bindgen
```
2. Create the configuration file **cargo2gn.json**.
```
{
"copy-out": true,
"run": true,
"add-workspace": true,
"cargo-bin": "/mnt/xxx/openharmony/prebuilts/rustc/linux-x86_64/current/bin"
}
```
3. Run the following command to perform the conversion:
```
python /mnt/xxx/openharmony/build/scripts/cargo2gn.py --config cargo2gn.json
```
The conversion result is as follows:
```
import("//build/templates/rust/ohos_cargo_crate.gni")
ohos_cargo_crate("lib") {
crate_name = "bindgen"
crate_type = "rlib"
crate_root = "./lib.rs"
sources = ["./lib.rs"]
edition = "2018"
cargo_pkg_version = "0.64.0"
cargo_pkg_authors = "Jyun-Yan You <jyyou.tw@gmail.com>, Emilio Cobos Álvarez <emilio@crisal.io>, Nick Fitzgerald <fitzgen@gmail.com>, The Servo project developers"
cargo_pkg_name = "bindgen"
cargo_pkg_description = "Automatically generates Rust FFI bindings to C and C++ libraries."
deps = [
"//third_party/rust/bitflags:lib",
"//third_party/rust/cexpr:lib",
"//third_party/rust/clang-sys:lib",
"//third_party/rust/lazy_static:lib",
"//third_party/rust/lazycell:lib",
"//third_party/rust/log:lib",
"//third_party/rust/peeking_take_while:lib",
"//third_party/rust/proc-macro2:lib",
"//third_party/rust/quote:lib",
"//third_party/rust/regex:lib",
"//third_party/rust/rustc-hash:lib",
"//third_party/rust/shlex:lib",
"//third_party/rust/syn:lib",
"//third_party/rust/which:lib",
]
features = [
"default",
"log",
"logging",
"static",
"which",
"which-rustfmt",
]
build_root = "build.rs"
build_sources = ["build.rs"]
build_script_outputs = ["host-target.txt"]
}
```
## Converting Multiple Libraries in Batches
1. Go to the **rust** directory.
```
cd openharmony/third_party/rust
```
2. Add all the rust libraries to be converted to [workspace] in **Cargo.toml** in the **rust** directory.
```
[workspace]
members = [
"aho-corasick",
"memchr",
]
```
3. Perform steps 2 and 3 in section "Converting a Single Library".
...@@ -23,6 +23,17 @@ ohos_app_scope ...@@ -23,6 +23,17 @@ ohos_app_scope
ohos_js_assets ohos_js_assets
ohos_resources ohos_resources
# Rust templates
ohos_rust_executable
ohos_rust_shared_library
ohos_rust_static_library
ohos_rust_proc_macro
ohos_rust_shared_ffi
ohos_rust_static_ffi
ohos_rust_cargo_crate
ohos_rust_systemtest
ohos_rust_unittest
# Other templates # Other templates
# Configuration file # Configuration file
ohos_prebuilt_etc ohos_prebuilt_etc
...@@ -33,7 +44,7 @@ ohos_sa_profile ...@@ -33,7 +44,7 @@ ohos_sa_profile
You are advised to use the OpenHarmony customized templates. You are advised to use the OpenHarmony customized templates.
### C/C++ Template Examples ### C/C++ Template Example
The .gni file corresponding to the templates starting with **ohos** is located in **openharmony/build/templates/cxx/cxx.gni**. The .gni file corresponding to the templates starting with **ohos** is located in **openharmony/build/templates/cxx/cxx.gni**.
...@@ -69,7 +80,7 @@ ohos_shared_library("helloworld") { ...@@ -69,7 +80,7 @@ ohos_shared_library("helloworld") {
cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check. cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check.
cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check.
integer_overflow = [boolean] # Whether to enable the integer overflow check. integer_overflow = [boolean] # Whether to enable the integer overflow check.
boundary_sanitize = [boolean] # Whether to enable the bounds check. boundary_sanitize = [boolean] # Whether to enable the boundary check.
ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options.
all_ubsan = [boolean] # Whether to enable all UBSAN options. all_ubsan = [boolean] # Whether to enable all UBSAN options.
... ...
...@@ -91,12 +102,12 @@ ohos_shared_library("helloworld") { ...@@ -91,12 +102,12 @@ ohos_shared_library("helloworld") {
} }
``` ```
**ohos_static_library** example: **ohos_static_library** example
```shell ```shell
import("//build/ohos.gni") import("//build/ohos.gni")
ohos_static_library("helloworld") { ohos_static_library("helloworld") {
sources = ["file"] # Source code in .c format. sources = ["file"] # .c files.
include_dirs = ["dir"] # Directories to be included. include_dirs = ["dir"] # Directories to be included.
configs = [] # Configuration. configs = [] # Configuration.
deps = [] # Define dependent modules that belong to the same component. deps = [] # Define dependent modules that belong to the same component.
...@@ -114,11 +125,11 @@ ohos_static_library("helloworld") { ...@@ -114,11 +125,11 @@ ohos_static_library("helloworld") {
# Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default.
sanitize = { sanitize = {
# Sanitizer settings # Sanitizer settings
cfi = [boolean] # Whether to enable the CFI check. cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check.
cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check.
integer_overflow = [boolean] # Whether to enable the integer overflow check. integer_overflow = [boolean] # Whether to enable the integer overflow check.
boundary_sanitize = [boolean] # Whether to enable the bounds check. boundary_sanitize = [boolean] # Whether to enable the boundary check.
ubsan = [boolean] # Whether to enable some UBSAN options. ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options.
all_ubsan = [boolean] # Whether to enable all UBSAN options. all_ubsan = [boolean] # Whether to enable all UBSAN options.
... ...
...@@ -153,10 +164,10 @@ ohos_executable("helloworld") { ...@@ -153,10 +164,10 @@ ohos_executable("helloworld") {
# Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default.
sanitize = { sanitize = {
# Sanitizer settings # Sanitizer settings
cfi = [boolean] # Whether to enable the CFI check. cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check.
cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check.
integer_overflow = [boolean] # Whether to enable the integer overflow check. integer_overflow = [boolean] # Whether to enable the integer overflow check.
boundary_sanitize = [boolean] # Whether to enable the bounds check. boundary_sanitize = [boolean] # Whether to enable the boundary check.
ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options.
all_ubsan = [boolean] # Whether to enable all UBSAN options. all_ubsan = [boolean] # Whether to enable all UBSAN options.
... ...
...@@ -181,15 +192,15 @@ ohos_executable("helloworld") { ...@@ -181,15 +192,15 @@ ohos_executable("helloworld") {
} }
``` ```
**ohos_source_set** example: **ohos_source_set** example
```shell ```shell
import("//build/ohos.gni") import("//build/ohos.gni")
ohos_source_set("helloworld") { ohos_source_set("helloworld") {
sources = ["file"] # Source code in .c format. sources = ["file"] # .c files.
include_dirs = [] # Directories to be included. include_dirs = [] # Directories to be included.
configs = [] # Configuration. configs = [] # Configuration.
public = [] # Header files. public = [] # .h header files.
defines = [] defines = []
public_configs = [] public_configs = []
part_name = [string] # Component name. part_name = [string] # Component name.
...@@ -203,10 +214,10 @@ ohos_source_set("helloworld") { ...@@ -203,10 +214,10 @@ ohos_source_set("helloworld") {
# Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default.
sanitize = { sanitize = {
# Sanitizer settings # Sanitizer settings
cfi = [boolean] # Whether to enable the CFI check. cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check.
cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check.
integer_overflow = [boolean] # Whether to enable the integer overflow check. integer_overflow = [boolean] # Whether to enable the integer overflow check.
boundary_sanitize = [boolean] # Whether to enable the bounds check. boundary_sanitize = [boolean] # Whether to enable the boundary check.
ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options.
all_ubsan = [boolean] # Whether to enable all UBSAN options. all_ubsan = [boolean] # Whether to enable all UBSAN options.
... ...
...@@ -226,16 +237,15 @@ ohos_source_set("helloworld") { ...@@ -226,16 +237,15 @@ ohos_source_set("helloworld") {
} }
``` ```
> **NOTE** **NOTE**<br>
> - Only **sources** and **part_name** are mandatory.
> - Only **sources** and **part_name** are mandatory. - For details about the Sanitizer configuration, see [Using Sanitizer](subsys-build-reference.md#using-sanitizer).
> - For details about the Sanitizer configuration, see [Using Sanitizer](subsys-build-reference.md#using-sanitizer).
### Prebuilt Template Examples ### Prebuilt Template Example
The .gni file of the prebuilt templates is located in **openharmony/build/templates/cxx/prebuilt.gni**. The .gni file of the prebuilt templates is located in **openharmony/build/templates/cxx/prebuilt.gni**.
**ohos_prebuilt_executable** example: **ohos_prebuilt_executable** example
```shell ```shell
import("//build/ohos.gni") import("//build/ohos.gni")
...@@ -263,7 +273,7 @@ ohos_prebuilt_executable("helloworld") { ...@@ -263,7 +273,7 @@ ohos_prebuilt_executable("helloworld") {
} }
``` ```
**ohos_prebuilt_shared_library** example: **ohos_prebuilt_shared_library** example
```shell ```shell
import("//build/ohos.gni") import("//build/ohos.gni")
...@@ -291,7 +301,7 @@ ohos_prebuilt_shared_library("helloworld") { ...@@ -291,7 +301,7 @@ ohos_prebuilt_shared_library("helloworld") {
} }
``` ```
**ohos_prebuilt_static_library** example: **ohos_prebuilt_static_library** example
```shell ```shell
import("//build/ohos.gni") import("//build/ohos.gni")
...@@ -312,13 +322,15 @@ ohos_prebuilt_static_library("helloworld") { ...@@ -312,13 +322,15 @@ ohos_prebuilt_static_library("helloworld") {
} }
``` ```
>**NOTE**<br>Only **sources** and **part_name** are mandatory. ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: Only **sources** and **part_name** are mandatory.
### HAP Templates ### HAP Templates
For details, see [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md). For details about the HAP templates, see [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md).
### Rust Templates
For details about the Rust templates, see [Rust Module Configuration Rules and Guide](subsys-build-rust-compilation.md).
### Other Templates ### Other Templates
...@@ -357,7 +369,7 @@ ohos_sa_profile("helloworld") { ...@@ -357,7 +369,7 @@ ohos_sa_profile("helloworld") {
} }
``` ```
> **NOTE**<br>Only **sources** and **part_name** are mandatory. ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: Only **sources** and **part_name** are mandatory.
## Adding and Building a Module ## Adding and Building a Module
...@@ -409,7 +421,7 @@ The following figure shows the logic for adding a module. Generally, you need to ...@@ -409,7 +421,7 @@ The following figure shows the logic for adding a module. Generally, you need to
"build": { # Build-related configuration. "build": { # Build-related configuration.
"sub_component": [ "sub_component": [
"//foundation/arkui/napi:napi_packages", # Existing module 1. "//foundation/arkui/napi:napi_packages", # Existing module 1.
"//foundation/arkui/napi:napi_packages_ndk"# Existing module 2. "//foundation/arkui/napi:napi_packages_ndk" # Existing module 2.
"//foundation/arkui/napi:new" # Module to add. "//foundation/arkui/napi:new" # Module to add.
], # Component build entry. Configure the module here. ], # Component build entry. Configure the module here.
"inner_kits": [], # APIs between components. "inner_kits": [], # APIs between components.
...@@ -419,7 +431,9 @@ The following figure shows the logic for adding a module. Generally, you need to ...@@ -419,7 +431,9 @@ The following figure shows the logic for adding a module. Generally, you need to
} }
``` ```
> **NOTE**<br>The **bundle.json** file must be in the folder of the corresponding subsystem. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> The **bundle.json** file must be in the folder of the corresponding subsystem.
3. Start the build and check whether a .so file or binary file is generated. 3. Start the build and check whether a .so file or binary file is generated.
...@@ -429,7 +443,7 @@ The following figure shows the logic for adding a module. Generally, you need to ...@@ -429,7 +443,7 @@ The following figure shows the logic for adding a module. Generally, you need to
2. Create a **bundle.json** file in the folder of the corresponding subsystem. 2. Create a **bundle.json** file in the folder of the corresponding subsystem.
3. Add the new component to the end of existing components in **vendor/{product_company}/{product_name}/config.json**. 3. Add the new component to the end of existing components in **vendor/{product_company}/{product-name}/config.json**.
```shell ```shell
"subsystems": [ "subsystems": [
...@@ -476,7 +490,7 @@ The following figure shows the logic for adding a module. Generally, you need to ...@@ -476,7 +490,7 @@ The following figure shows the logic for adding a module. Generally, you need to
The **subsystem_config.json** file defines the subsystems and their directories. When adding a subsystem, specify **path** and **name** for the subsystem. The **subsystem_config.json** file defines the subsystems and their directories. When adding a subsystem, specify **path** and **name** for the subsystem.
4. If **product_name** in the **vendor/{product_company}/{product_name}** directory is **hispark_taurus_standard**, add the new component information to the end of existing components in the **config.json** file. 4. If **product-name** in the **vendor/{product_company}/{product-name}** directory is **hispark_taurus_standard**, add the new component information to the end of existing components in the **config.json** file.
```shell ```shell
"subsystems": [ "subsystems": [
...@@ -517,19 +531,19 @@ The following figure shows the logic for adding a module. Generally, you need to ...@@ -517,19 +531,19 @@ The following figure shows the logic for adding a module. Generally, you need to
You can start the build by using the [CLI or hb tool](subsys-build-all.md#build-commands). The following uses the CLI as an example: You can start the build by using the [CLI or hb tool](subsys-build-all.md#build-commands). The following uses the CLI as an example:
You can run the **--build-target** *Module_name* command to build a module separately. You can run the **--build-target** *Module_name* command to build a module separately.
```shell ```shell
./build.sh --build-target Module_name ./build.sh --build-target Module_name
``` ```
You can also build a product. For example, to build hispark_taurus_standard, run the following command: You can also build a product. For example, to build hispark_taurus_standard, run the following command:
```shell ```shell
./build.sh --product-name hispark_taurus_standard --build-target Module_name --ccache ./build.sh --product-name hispark_taurus_standard --build-target Module_name --ccache
``` ```
You can also build the component to which the module belongs. You can also build the component to which the module belongs.
```shell ```shell
./build.sh --product-name hispark_taurus_standard --build-target musl --build-target Module_name --ccache ./build.sh --product-name hispark_taurus_standard --build-target musl --build-target Module_name --ccache
......
# Rust Module Configuration Rules and Guide
## Introduction
Rust is a static, strongly typed programming language. It has advantages such as secure memory management, high running performance, and native support for multi-thread development. Rust uses Cargo to create projects and compile and build Rust code.
To integrate C/C++ code and improve the build speed, OpenHarmony uses Generate Ninja (GN) and Ninja as its build system. GN has simple and easy-to-use build language, and Ninja provides direct and efficient assembly-level build rules.
To integrate Rust code and maximize the interaction between the C/C++ code used in OpenHarmony and Rust, OpenHarmony uses GN as a unified build tool to build Rust source code files (xxx.rs) and is added with features such as interoperability with C/C++, compile time lints, test, IDL conversion, third-party library integration, and IDE. In addition, the GN framework is extended to support automatic interface conversion, which greatly simplifying development.
### Basic Concepts
| Term | Description |
| ----- | ------------------------------------------------------------ |
| Cargo | Cargo is an official build tool used by Rust. It allows Rust projects to declare dependencies and ensures reproducible builds.|
| crate | Crate is a unit that can be independently compiled. |
| Lint| Lint is a code analysis tool used to flag programming errors, bugs, stylistic errors, and suspicious constructs. It performs extensive error analysis on programs.|
## Configure Rules
OpenHarmony provides a variety of GN templates for compiling Rust executables, dynamic libraries, and static libraries. The following table describes the templates.
| GN Template | Description | Output |
| ------------------------ | ----------------- | ----------------------------------------------- |
| ohos_rust_executable | Rust executable file. | Rust executable file, without the file name extension. |
| ohos_rust_shared_library | Rust dynamic library. | Rust dylib dynamic library, with the default file name extension **.dylib.so**. |
| ohos_rust_static_library | Rust static library. | Rust rlib static library, with the default file name extension **.rlib**. |
| ohos_rust_proc_macro | Rust proc_macro library. | Rust proc_macro library, with the default file name extension **.so**. |
| ohos_rust_shared_ffi | Rust Foreign Function Interface (FFI) dynamic library. | Rust cdylib dynamic library, which is called by the C/C++ module. The default file name extension is **.so**.|
| ohos_rust_static_ffi | Rust FFI static library. | Rust staticlib library, which is called by the C/C++ module. The default file name extension is **.a**. |
| ohos_rust_cargo_crate | Third-party Cargo crate.| Third-party Rust crates, which support rlib, dylib, and bin. |
| ohos_rust_systemtest | Rust system test cases. | Executable system test cases for Rust, without the file name extension. |
| ohos_rust_unittest | Rust unit test cases. | Executable unit test cases for Rust, without the file name extension. |
## Configuration Guide
The configuration of the Rust module is similar to that of the C/C++ module. For details, see [Module Configuration Rules](subsys-build-module.md). The following provides examples of using different Rust templates.
### Configuring a Rust Static Library
The following example shows how to use the **ohos_rust_executable** and **ohos_rust_static_library** templates to build a binary executable and a static rlib library, respectively. The executable depends on the static library.
The procedure is as follows:
1. Create **build/rust/tests/test_rlib_crate/src/simple_printer.rs**.
```rust
//! simple_printer
/// struct RustLogMessage
pub struct RustLogMessage {
/// i32: id
pub id: i32,
/// String: msg
pub msg: String,
}
/// function rust_log_rlib
pub fn rust_log_rlib(msg: RustLogMessage) {
println!("id:{} message:{:?}", msg.id, msg.msg)
}
```
2. Create **build/rust/tests/test_rlib_crate/src/main.rs**.
```rust
//! rlib_crate example for Rust.
extern crate simple_printer_rlib;
use simple_printer_rlib::rust_log_rlib;
use simple_printer_rlib::RustLogMessage;
fn main() {
let msg: RustLogMessage = RustLogMessage {
id: 0,
msg: "string in rlib crate".to_string(),
};
rust_log_rlib(msg);
}
```
3. Configure the GN build script **build/rust/tests/test_rlib_crate/BUILD.gn**.
```
import("//build/ohos.gni")
ohos_rust_executable("test_rlib_crate") {
sources = [ "src/main.rs" ]
deps = [ ":simple_printer_rlib" ]
}
ohos_rust_static_library("simple_printer_rlib") {
sources = [ "src/simple_printer.rs" ]
crate_name = "simple_printer_rlib"
crate_type = "rlib"
features = [ "std" ]
}
```
4. Run the **BUILD.gn** to generate the build targets.
![test_rlib_crate](./figures/test_rlib_crate.png)
### Configuring a Third-Party Library
The following example shows how to use the **ohos_rust_executable** and **ohos_rust_cargo_crate** templates to build a third-party static rlib library whose code contains a prebuilt file **build.rs**.
The procedure is as follows:
1. Create **build/rust/tests/test_rlib_cargo_crate/crate/src/lib.rs**.
```rust
include!(concat!(env!("OUT_DIR"), "/generated/generated.rs"));
pub fn say_hello_from_crate() {
assert_eq!(run_some_generated_code(), 45);
#[cfg(is_new_rustc)]
println!("Is new rustc");
#[cfg(is_old_rustc)]
println!("Is old rustc");
#[cfg(is_ohos)]
println!("Is ohos");
#[cfg(is_mac)]
println!("Is darwin");
#[cfg(has_feature_a)]
println!("Has feature_a");
#[cfg(not(has_feature_a))]
panic!("Wasn't passed feature_a");
#[cfg(not(has_feature_b))]
#[cfg(test_a_and_b)]
panic!("feature_b wasn't passed");
#[cfg(has_feature_b)]
#[cfg(not(test_a_and_b))]
panic!("feature_b was passed");
}
#[cfg(test)]
mod tests {
/// Test features are passed through from BUILD.gn correctly. This test is the target configuration.
#[test]
#[cfg(test_a_and_b)]
fn test_features_passed_target1() {
#[cfg(not(has_feature_a))]
panic!("feature a was not passed");
#[cfg(not(has_feature_b))]
panic!("feature b was not passed");
}
#[test]
fn test_generated_code_works() {
assert_eq!(crate::run_some_generated_code(), 45);
}
}
```
2. Create **build/rust/tests/test_rlib_cargo_crate/crate/src/main.rs**.
```rust
pub fn main() {
test_rlib_crate::say_hello_from_crate();
}
```
3. Create **build/rust/tests/test_rlib_cargo_crate/crate/build.rs**.
```rust
use std::env;
use std::path::Path;
use std::io::Write;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
println!("cargo:rustc-cfg=build_script_ran");
let my_minor = match rustc_minor_version() {
Some(my_minor) => my_minor,
None => return,
};
if my_minor >= 34 {
println!("cargo:rustc-cfg=is_new_rustc");
} else {
println!("cargo:rustc-cfg=is_old_rustc");
}
let target = env::var("TARGET").unwrap();
if target.contains("ohos") {
println!("cargo:rustc-cfg=is_ohos");
}
if target.contains("darwin") {
println!("cargo:rustc-cfg=is_mac");
}
let feature_a = env::var_os("CARGO_FEATURE_MY_FEATURE_A").is_some();
if feature_a {
println!("cargo:rustc-cfg=has_feature_a");
}
let feature_b = env::var_os("CARGO_FEATURE_MY_FEATURE_B").is_some();
if feature_b {
println!("cargo:rustc-cfg=has_feature_b");
}
// Tests used to verify whether Cargo features are enabled.
assert!(Path::new("build.rs").exists());
assert!(Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("build.rs").exists());
assert!(Path::new(&env::var_os("OUT_DIR").unwrap()).exists());
// Ensure that the following env var is set.
env::var_os("CARGO_CFG_TARGET_ARCH").unwrap();
generate_some_code().unwrap();
}
fn generate_some_code() -> std::io::Result<()> {
let test_output_dir = Path::new(&env::var_os("OUT_DIR").unwrap()).join("generated");
let _ = std::fs::create_dir_all(&test_output_dir);
// Test that environment variables from .gn files are passed to build scripts.
let preferred_number = env::var("ENV_VAR_FOR_BUILD_SCRIPT").unwrap();
let mut file = std::fs::File::create(test_output_dir.join("generated.rs"))?;
write!(file, "fn run_some_generated_code() -> u32 {{ {} }}", preferred_number)?;
Ok(())
}
fn rustc_minor_version() -> Option<u32> {
let rustc_bin = match env::var_os("RUSTC") {
Some(rustc_bin) => rustc_bin,
None => return None,
};
let output = match Command::new(rustc_bin).arg("--version").output() {
Ok(output) => output,
Err(_) => return None,
};
let rustc_version = match str::from_utf8(&output.stdout) {
Ok(rustc_version) => rustc_version,
Err(_) => return None,
};
let mut pieces = rustc_version.split('.');
if pieces.next() != Some("rustc 1") {
return None;
}
let next_var = match pieces.next() {
Some(next_var) => next_var,
None => return None,
};
u32::from_str(next_var).ok()
}
```
4. Configure the GN build script **build/rust/tests/test_rlib_cargo_crate/BUILD.gn**.
```
import("//build/templates/rust/ohos_cargo_crate.gni")
ohos_cargo_crate("target") {
crate_name = "test_rlib_crate"
crate_root = "crate/src/lib.rs"
sources = [ "crate/src/lib.rs" ]
#To generate the build_script binary
build_root = "crate/build.rs"
build_sources = [ "crate/build.rs" ]
build_script_outputs = [ "generated/generated.rs" ]
features = [
"my-feature_a",
"my-feature_b",
"std",
]
rustflags = [
"--cfg",
"test_a_and_b",
]
rustenv = [ "ENV_VAR_FOR_BUILD_SCRIPT=45" ]
}
# Exists to test the case that a single crate has both a library and a binary
ohos_cargo_crate("test_rlib_crate_associated_bin") {
crate_root = "crate/src/main.rs"
crate_type = "bin"
sources = [ "crate/src/main.rs" ]
#To generate the build_script binary
build_root = "crate/build.rs"
build_sources = [ "crate/build.rs" ]
features = [
"my-feature_a",
"my-feature_b",
"std",
]
rustenv = [ "ENV_VAR_FOR_BUILD_SCRIPT=45" ]
deps = [ ":target" ]
}
```
5. Run the **BUILD.gn** to generate the build target.
![test_rlib_cargo_crate](./figures/test_rlib_cargo_crate.png)
### Other Configuration Examples
You can find the Rust module configuration examples in the **build/rust/tests** directory.
| Directory | Description |
| -------------------------------------------- | ------------------------------------------------------------ |
| build/rust/tests/test_bin_crate | Tests the build of an executable file on the host platform and running of the executable file on the target platform. |
| build/rust/tests/test_static_link | Tests the static linking of an executable file to a standard library. |
| build/rust/tests/test_dylib_crate | Tests the build of a dynamic library and dynamic linking. |
| build/rust/tests/test_rlib_crate | Tests the build of a static library and static linking. |
| build/rust/tests/test_proc_macro_crate | Tests the build of Rust process macros and the linking function. Test cases are provided for different types of macros. |
| build/rust/tests/test_cdylib_crate | Tests the generation of Rust FFI bindings to a C/C++ dynamic library. |
| build/rust/tests/test_staticlib_crate | Tests the generation of Rust FFI bindings to a C/C++ static library. |
| build/rust/tests/test_rust_ut | Tests the Rust code unit test template. |
| build/rust/tests/test_rust_st | Tests the Rust code system test template. |
| build/rust/tests/test_bin_cargo_crate | Tests the build and running of a Rust third-party executable file. The third-party code contains the **build.rs**. |
| build/rust/tests/test_rlib_cargo_crate | Tests the build of a Rust third-party static library and static linking. The third-party code contains the **build.rs**. |
| build/rust/tests/test_proc_macro_cargo_crate | Tests the build of Rust third-party process macros and linking. The third-party code contains the **build.rs**. |
## Reference
### Feature Examples
#### Linking a C/C++ library in Rust Source Code
By default, the dynamic library of the OpenHarmony C/C++ module is in the **.z.so** format. However, when the Rust **-l** command is executed, only the dynamic library in the **.so** format is linked by default. If a C/C++ dynamic library is used as the dependency, you need to add **output_extension = "so"** to the GN build script of the dynamic library to make the generated dynamic library be named with **.so** instead of **.z.so**.
If a dynamic library is directly linked in the Rust source code, the dynamic library must be in **.so** format. In this case, use the dynamic library name without "lib". The following is an example of linking **libhilog.so** in the Rust source code.
```rust
#[link(name = "hilog")]
```
#### Using externs
If a module depends on the binary rlib library, you can use the **externs** attribute.
```
executable("foo") {
sources = [ "main.rs" ]
externs = [{ # Convert it to `--extern bar=path/to/bar.rlib` during the compilation.
crate_name = "bar"
path = "path/to/bar.rlib"
}]
}
```
### Lint Rules
The OpenHarmony framework supports two types of lints: rustc lints and Clippy lints. Each type of lint has three levels: openharmony (highest), vendor, and none (lowest).
When configuring the Rust module, you can specify the lint level in **rustc_lints** or **clippy_lints**.
If **rustc_lints** or **clippy_lints** is not configured in the module, the lint level is matched based on the module path. Different restrictions apply to the syntax specifications of Rust code in different directories. Therefore, you need to pay attention to the path of the module when configuring the Rust module to build in OpenHarmony.
#### Levels of rustc Lints and Clippy Lints
| **Lint Type**| **Module Attribute**| **Lint Level**| **Lint Level Flag**| **Lint Content** |
| ------------- | ------------ | ------------- | ----------------- | ------------------------------------------------------------ |
| rustc lints | rustc_lints | openharmony | RustOhosLints | "-A deprecated", "-D missing-docs", "-D warnings" |
| rustc lints | rustc_lints | vendor | RustcVendorLints | "-A deprecated", "-D warnings" |
| rustc lints | rustc_lints | none | allowAllLints | "-cap-lints allow" |
| Clippy lints | clippy_lints | openharmony | ClippyOhosLints | "-A clippy::type-complexity", "-A clippy::unnecessary-wraps", "-A clippy::unusual-byte-groupings", "-A clippy::upper-case-acronyms" |
| Clippy lints | clippy_lints | vendor | ClippyVendorLints | "-A clippy::complexity", "-A Clippy::perf", "-A clippy::style" |
| Clippy lints | clippy_lints | none | allowAllLints | "--cap-lints allow" |
#### Mapping Between Code Paths and Lint Levels
| Path | Lint Level |
| ---------- | ----------- |
| thirdparty | none |
| prebuilts | none |
| vendor | vendor |
| device | vendor |
| others | openharmony |
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
## cl.filemanagement.1 environment Module Change ## cl.filemanagement.1 environment Module Change
The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **environment** module supports error code handling. The file management subsystem **d.ts** file has been archived and moved to the **file** directory. The **environment** module supports error code processing.
**Change Impact** **Change Impact**
If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **environment** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **environment** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details.
**Key API/Component Changes** **Key API/Component Changes**
...@@ -24,11 +24,11 @@ import environment from '@ohos.file.environment'; ...@@ -24,11 +24,11 @@ import environment from '@ohos.file.environment';
## cl.filemanagement.2 securityLabel Change ## cl.filemanagement.2 securityLabel Change
Moved the file management subsystem **d.ts** file to the **file** directory. The **securityLabel** module supports error code handling. Moved the file management subsystem **d.ts** file to the **file** directory. The **securityLabel** module supports error code processing.
**Change Impact** **Change Impact**
If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **securityLabel** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **securityLabel** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details.
**Key API/Component Changes** **Key API/Component Changes**
...@@ -58,11 +58,11 @@ The type of the **ino** attribute of **Stat** is changed from number to BigInt. ...@@ -58,11 +58,11 @@ The type of the **ino** attribute of **Stat** is changed from number to BigInt.
## cl.filemanagement.4 fileAccess Change ## cl.filemanagement.4 fileAccess Change
Moved the file management subsystem **d.ts** file to the **file** directory. The **fileAccess** module supports error code handling. Moved the file management subsystem **d.ts** file to the **file** directory. The **fileAccess** module supports error code processing.
**Change Impact** **Change Impact**
If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileAccess** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileAccess** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details.
**Key API/Component Changes** **Key API/Component Changes**
...@@ -80,11 +80,11 @@ import fileAccess from '@ohos.file.fileAccess'; ...@@ -80,11 +80,11 @@ import fileAccess from '@ohos.file.fileAccess';
## cl.filemanagement.5 fileExtensionInfo Change ## cl.filemanagement.5 fileExtensionInfo Change
Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code handling. Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code processing.
**Change Impact** **Change Impact**
If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileExtensionInfo** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **fileExtensionInfo** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details.
**Key API/Component Changes** **Key API/Component Changes**
...@@ -102,11 +102,11 @@ import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; ...@@ -102,11 +102,11 @@ import fileExtensionInfo from '@ohos.file.fileExtensionInfo';
## cl.filemanagement.6 storageStatistics Change ## cl.filemanagement.6 storageStatistics Change
Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code handling. Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code processing.
**Change Impact** **Change Impact**
If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **storageStatistics** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **storageStatistics** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details.
**Key API/Component Changes** **Key API/Component Changes**
...@@ -124,11 +124,11 @@ import storageStatistics from '@ohos.file.storageStatistics'; ...@@ -124,11 +124,11 @@ import storageStatistics from '@ohos.file.storageStatistics';
## cl.filemanagement.7 volumeManager Change ## cl.filemanagement.7 volumeManager Change
Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code handling. Moved the file management subsystem **d.ts** file to the **file** directory. The **fileExtensionInfo** module supports error code processing.
**Change Impact** **Change Impact**
If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **volumeManager** module supports error code handling. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md). If your application is developed based on earlier versions, note that the **d.ts** file location and the name of the module to be imported are changed. The **volumeManager** module supports error code processing. See [Adaptation Guide](../OpenHarmony_3.2.8.1/changelogs-filemanagement.md) for more details.
**Key API/Component Changes** **Key API/Component Changes**
......
# Ability Framework Changelog
Compared with OpenHarmony 3.2 Release, OpenHarmony 3.2.12.2 provides more detailed error code information for the APIs of the ability framework.
## cl.ability.1 Added and Optimized API Error Code Description
The error code description and all error codes that may be returned by the APIs are commented out. This helps developers control the error process more accurately.
**Change Impact**
The external declaration of the JS APIs of API version 9 is affected, but the API functionalities are not affected. You can determine whether to adapt to the JS APIs.
**Key API/Component Changes**
The comments of the following modules are updated. For details, see the corresponding external API declaration and API development guide.
| Module | Description of Major Changes |
| ----------------------------------- | ------------------------------------------------------------ |
| @ohos.app.ability.UIAbility | Added the description of error codes 16200001, 16200002, 16200004, 16200005, 16000050.|
| @ohos.app.ability.abilityManager | Added the description of error codes 201, 202, and 16000050, and adjusted the description of error code 401.|
| @ohos.app.ability.appManager | Added the description of error codes 201, 202, and 16000050, and adjusted the description of error code 401.|
| @ohos.app.ability.dataUriUtils | Added the description of error code 401. |
| @ohos.app.ability.errorManager | Added the description of error code 16000003. |
| @ohos.app.ability.missionManager | Added the description of error codes 201, 202, 16300001, 16300002, and 16000009, and adjusted the description of error code 401.|
| @ohos.app.ability.quickFixManager | Added the description of error codes 201, 202, 18500001, 18500002, and 18500008. |
| @ohos.app.ability.wantAgent | Added the description of error codes 16000007, 16000015, and 16000151. |
| application/AbilityDelegator | Added the description of error codes 16000001, 16000002, 16000004, 16000005, 16000006, 16000008, 16000009, 16000010, 16000011, 16000050, 16000053, 16000055, 16200001, and 16000100.|
| application/ApplicationContext | Added the description of error codes 16000011 and 16000050. |
| application/Context | Added the description of error codes 201, 202, and 401. |
| application/ServiceExtensionContext | Added the description of error codes 201, 202, 16000001, 16000002, 16000004, 16000005, 16000006, 16000008, 16000009, 16000010, 16000011, 16000050, 16000053, 16000055, and 16200001.|
| application/UIAbilityContext | Added the description of error codes 201, 16000001, 16000002, 16000004, 16000005, 16000006, 16000008, 16000009, 16000010, 16000011, 16000050, 16000053, 16000055, 16200001, and 16000100.|
| @ohos.app.form.formHost | Added the description of error codes 201, 202, 16500050, 16500060, 16501000, 16501001, and 16501003, and adjusted the description of error code 401.|
| @ohos.app.form.formProvider | Added the error codes 202, 16500050, 16500060, 16500100, 16501000, 16501001, 16501002, and 16501003, and adjusted the description of error code 401.|
| application/FormExtensionContext | Added the description of error codes 202, 401, 16500050, 16500100, 16500101, and 16501000.|
# Bundle Management Subsystem Changelog
## cl.bundlemanager.1 Changed Underlying Capability by Not Decompressing the HAP During HAP Installation
The HAP will no longer be decompressed during installation. After the installation is complete, only the HAP file exists in the installation directory. As a result, the application must use the standard resource management interface, rather than a combined path, to access a resource file.
**Change Impact**<br>
If the application uses a combined path to access a resource file, the access fails. It must use the resource management interface.
**Key API/Component Changes**<br>
No API or component change is involved.
**Adaptation Guide**<br>
The resource management subsystem provides the JS interface for accessing resource files. Reference: [Accessing Resource Files](../../../application-dev/reference/apis/js-apis-resource-manager.md#getrawfilecontent9)
...@@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability'; ...@@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability';
| 名称 | 类型 | 描述 | | 名称 | 类型 | 描述 |
| ----------- | -------------------- | ------------------------------------------------------------ | | ----------- | -------------------- | ------------------------------------------------------------ |
| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | DataAbilityHelper二级模块。 | | DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | DataAbilityHelper二级模块。 |
| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | PacMap二级模块。 | | PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | PacMap二级模块。 |
| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | DataAbilityOperation二级模块。 | | DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | DataAbilityOperation二级模块。 |
| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | DataAbilityResult二级模块。 | | DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | DataAbilityResult二级模块。 |
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 |
......
# @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry) # @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry)
AbilityDelegatorRegistry是[测试框架](../../ability-deprecated/ability-delegator.md)模块,该模块用于获取[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象,其中[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)对象提供添加用于监视指定ability的生命周期状态更改的AbilityMonitor对象的能力,[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象提供获取当前测试参数的能力。 AbilityDelegatorRegistry是[自动化测试框架使用指南](../../application-test/arkxtest-guidelines.md)模块,该模块用于获取[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象,其中[AbilityDelegator](js-apis-inner-application-abilityDelegator.md)对象提供添加用于监视指定ability的生命周期状态更改的AbilityMonitor对象的能力,[AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md)对象提供获取当前测试参数的能力。
> **说明:** > **说明:**
> >
......
...@@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common'; ...@@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common';
| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | FormExtensionContext二级模块。 | | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | FormExtensionContext二级模块。 |
| ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | ServiceExtensionContext二级模块。 | | ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | ServiceExtensionContext二级模块。 |
| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | EventHub二级模块。 | | EventHub | [EventHub](js-apis-inner-application-eventHub.md) | EventHub二级模块。 |
| PacMap | [PacMap](js-apis-inner-application-pacMap.md) | PacMap二级模块。 | | PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | PacMap二级模块。 |
| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 |
| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 | | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 |
......
...@@ -130,6 +130,6 @@ import Want from '@ohos.application.Want'; ...@@ -130,6 +130,6 @@ import Want from '@ohos.application.Want';
}); });
``` ```
- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want - 更多详细说明和示例请参见: [应用模型](../../application-models/application-model-composition.md)的信息传递载体Want
<!--no_check--> <!--no_check-->
\ No newline at end of file
...@@ -865,8 +865,8 @@ call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCa ...@@ -865,8 +865,8 @@ call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCa
| uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' |
| method | string | 是 | 指示被调用的方法名。 | | method | string | 是 | 指示被调用的方法名。 |
| arg | string | 是 | 指示需传入的参数。 | | arg | string | 是 | 指示需传入的参数。 |
| extras | [PacMap](js-apis-inner-application-pacMap.md) | 是 | 指示扩展的键值对参数。 | | extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | 是 | 指示扩展的键值对参数。 |
| callback | AsyncCallback\<[PacMap](js-apis-inner-application-pacMap.md)> | 是 | 指示数据操作的回调方法,返回操作结果。 | | callback | AsyncCallback\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | 是 | 指示数据操作的回调方法,返回操作结果。 |
**示例:** **示例:**
...@@ -901,13 +901,13 @@ call(uri: string, method: string, arg: string, extras: PacMap): Promise\<PacMap> ...@@ -901,13 +901,13 @@ call(uri: string, method: string, arg: string, extras: PacMap): Promise\<PacMap>
| uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' |
| method | string | 是 | 指示被调用的方法名。 | | method | string | 是 | 指示被调用的方法名。 |
| arg | string | 是 | 指示需传入的参数。 | | arg | string | 是 | 指示需传入的参数。 |
| extras | [PacMap](js-apis-inner-application-pacMap.md) | 是 | 指示扩展的键值对参数。 | | extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | 是 | 指示扩展的键值对参数。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
|------ | ------- | |------ | ------- |
|Promise\<[PacMap](js-apis-inner-application-pacMap.md)> | 返回操作结果。 | |Promise\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | 返回操作结果。 |
**示例:** **示例:**
...@@ -998,3 +998,13 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi ...@@ -998,3 +998,13 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi
}); });
``` ```
## PacMap
[key: string]: number | string | boolean | Array\<string | number | boolean> | null;
**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel
| 参数名 | 参数类型 | 必填 | 说明 |
| ------ | ------ | ------ | ------ |
| [key: string] | number \| string \| boolean \| Array\<string \| number \| boolean\> \| null | Yes| 数据存储在键值对中。|
\ No newline at end of file
...@@ -72,6 +72,6 @@ import Want from '@ohos.app.ability.Want'; ...@@ -72,6 +72,6 @@ import Want from '@ohos.app.ability.Want';
// ... // ...
``` ```
- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want - 更多详细说明和示例请参见: [应用模型](../../application-models/application-model-composition.md)的信息传递载体Want
<!--no_check--> <!--no_check-->
\ No newline at end of file
...@@ -358,9 +358,9 @@ Audio/Video播放demo可参考:[音频播放开发指导](../../media/using-av ...@@ -358,9 +358,9 @@ Audio/Video播放demo可参考:[音频播放开发指导](../../media/using-av
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| url<sup>9+</sup> | string | 是 | 是 | 媒体URL,只允许在**idle**状态下设置,静态属性。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav)。<br/>**支持路径示例**<br>1. fd类型播放:fd://xx。<br>![](figures/zh-cn_image_url.png)<br>2. http网络播放: http://xx。<br/>3. https网络播放: https://xx。<br/>4. hls网络播放路径:http://xx或者https://xx。 | | url<sup>9+</sup> | string | 是 | 是 | 媒体URL,只允许在**idle**状态下设置,静态属性。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。<br/>**支持路径示例**<br>1. fd类型播放:fd://xx。<br>![](figures/zh-cn_image_url.png)<br>2. http网络播放: http://xx。<br/>3. https网络播放: https://xx。<br/>4. hls网络播放路径:http://xx或者https://xx。 |
| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 媒体文件描述,只允许在**idle**状态下设置,静态属性。<br/>使用场景:应用中的媒体资源被连续存储在同一个文件中。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav)。<br/>**使用示例**<br/>假设一个连续存储的媒体文件: <br/>视频1(地址偏移:0,字节长度:100);<br/>视频2(地址偏移:101,字节长度:50);<br/>视频3(地址偏移:151,字节长度:150);<br/>1. 播放视频1:AVFileDescriptor { fd = 资源句柄; offset = 0; length = 100; }。<br/>2. 播放视频2:AVFileDescriptor { fd = 资源句柄; offset = 101; length = 50; }。<br/>3. 播放视频3:AVFileDescriptor { fd = 资源句柄; offset = 151; length = 150; }。<br/>假设是一个独立的媒体文件: 请使用src=fd://xx。 | | fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 媒体文件描述,只允许在**idle**状态下设置,静态属性。<br/>使用场景:应用中的媒体资源被连续存储在同一个文件中。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。<br/>**使用示例**<br/>假设一个连续存储的媒体文件: <br/>视频1(地址偏移:0,字节长度:100);<br/>视频2(地址偏移:101,字节长度:50);<br/>视频3(地址偏移:151,字节长度:150);<br/>1. 播放视频1:AVFileDescriptor { fd = 资源句柄; offset = 0; length = 100; }。<br/>2. 播放视频2:AVFileDescriptor { fd = 资源句柄; offset = 101; length = 50; }。<br/>3. 播放视频3:AVFileDescriptor { fd = 资源句柄; offset = 151; length = 150; }。<br/>假设是一个独立的媒体文件: 请使用src=fd://xx。 |
| dataSrc<sup>10+</sup> | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | 是 | 是 | 流式媒体资源描述,只允许在**idle**状态下设置,静态属性。<br/>使用场景:应用播放从远端下载到本地的文件,在应用未下载完整音视频资源时,提前播放已获取的资源文件。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav)。<br/>**使用示例**<br/>假设用户正在从远端服务器获取音视频媒体文件,希望下载到本地的同时播放已经下载好的部分: <br/>1.用户需要获取媒体文件的总大小size(单位为字节),获取不到时设置为-1。<br/>2.用户需要实现回调函数func用于填写数据,如果size = -1,则func形式为:func(buffer: ArrayBuffer, length: number),此时播放器只会按照顺序获取数据;否则func形式为:func(buffer: ArrayBuffer, length: number, pos: number),播放器会按需跳转并获取数据。<br/>3.用户设置AVDataSrcDescriptor {fileSize = size, callback = func}。<br/>**注意事项**<br/>如果播放的是mp4/m4a格式用户需要保证moov字段(媒体信息字段)在mdat字段(媒体数据字段)之前,或者moov之前的字段小于10M,否则会导致解析失败无法播放。 | | dataSrc<sup>10+</sup> | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | 是 | 是 | 流式媒体资源描述,只允许在**idle**状态下设置,静态属性。<br/>使用场景:应用播放从远端下载到本地的文件,在应用未下载完整音视频资源时,提前播放已获取的资源文件。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。<br/>**使用示例**<br/>假设用户正在从远端服务器获取音视频媒体文件,希望下载到本地的同时播放已经下载好的部分: <br/>1.用户需要获取媒体文件的总大小size(单位为字节),获取不到时设置为-1。<br/>2.用户需要实现回调函数func用于填写数据,如果size = -1,则func形式为:func(buffer: ArrayBuffer, length: number),此时播放器只会按照顺序获取数据;否则func形式为:func(buffer: ArrayBuffer, length: number, pos: number),播放器会按需跳转并获取数据。<br/>3.用户设置AVDataSrcDescriptor {fileSize = size, callback = func}。<br/>**注意事项**<br/>如果播放的是mp4/m4a格式用户需要保证moov字段(媒体信息字段)在mdat字段(媒体数据字段)之前,或者moov之前的字段小于10M,否则会导致解析失败无法播放。 |
| surfaceId<sup>9+</sup> | string | 是 | 是 | 视频窗口ID,默认无窗口,只允许在**initialized**状态下设置,静态属性。<br/>使用场景:视频播放的窗口渲染,纯音频播放不用设置。<br/>**使用示例**<br/>[通过Xcomponent创建surfaceId](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid)。 | | surfaceId<sup>9+</sup> | string | 是 | 是 | 视频窗口ID,默认无窗口,只允许在**initialized**状态下设置,静态属性。<br/>使用场景:视频播放的窗口渲染,纯音频播放不用设置。<br/>**使用示例**<br/>[通过Xcomponent创建surfaceId](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid)。 |
| loop<sup>9+</sup> | boolean | 是 | 是 | 视频循环播放属性,默认'false',设置为'true'表示循环播放,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。<br/>直播场景不支持loop设置。 | | loop<sup>9+</sup> | boolean | 是 | 是 | 视频循环播放属性,默认'false',设置为'true'表示循环播放,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。<br/>直播场景不支持loop设置。 |
| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式,默认VIDEO_SCALE_TYPE_FIT_CROP,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 | | videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式,默认VIDEO_SCALE_TYPE_FIT_CROP,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 |
......
...@@ -767,7 +767,7 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 ...@@ -767,7 +767,7 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用
| uid<sup>9+</sup> | number[] | 是 | 否 | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。 | | uid<sup>9+</sup> | number[] | 是 | 否 | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。 |
| technology<sup>9+</sup> | number[] | 是 | 否 | 支持的技术类型,每个number值表示所支持技术类型的常量值。 | | technology<sup>9+</sup> | number[] | 是 | 否 | 支持的技术类型,每个number值表示所支持技术类型的常量值。 |
| supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#tagtaginfo)替代。 | | supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#tagtaginfo)替代。 |
| extrasData<sup>9+</sup> | [PacMap](js-apis-inner-application-pacMap.md)[] | 是 | 否 | 标签所支持技术的扩展属性值。<br>**系统接口:** 此接口为系统接口。 | | extrasData<sup>9+</sup> | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | 是 | 否 | 标签所支持技术的扩展属性值。<br>**系统接口:** 此接口为系统接口。 |
| tagRfDiscId<sup>9+</sup> | number | 是 | 否 | 标签发现时分配的ID值。<br>**系统接口:** 此接口为系统接口。 | | tagRfDiscId<sup>9+</sup> | number | 是 | 否 | 标签发现时分配的ID值。<br>**系统接口:** 此接口为系统接口。 |
| remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | 是 | 否 | NFC服务进程的远端对象,用于客户端和服务之间的接口通信。<br>**系统接口:** 此接口为系统接口。 | | remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | 是 | 否 | NFC服务进程的远端对象,用于客户端和服务之间的接口通信。<br>**系统接口:** 此接口为系统接口。 |
## NdefRecord<sup>9+</sup> ## NdefRecord<sup>9+</sup>
......
...@@ -33,14 +33,14 @@ enableWifi(): boolean ...@@ -33,14 +33,14 @@ enableWifi(): boolean
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.enableWifi(); wifi.enableWifi();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.disableWifi ## wifi.disableWifi
...@@ -63,14 +63,15 @@ disableWifi(): boolean ...@@ -63,14 +63,15 @@ disableWifi(): boolean
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.disableWifi(); wifi.disableWifi();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.isWifiActive ## wifi.isWifiActive
...@@ -91,15 +92,15 @@ isWifiActive(): boolean ...@@ -91,15 +92,15 @@ isWifiActive(): boolean
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let isActivate = wifi.isActivate(); let isActivate = wifi.isActivate();
console.info("isActivate:" + isActivate); console.info("isActivate:" + isActivate);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.scan ## wifi.scan
...@@ -120,14 +121,14 @@ scan(): boolean ...@@ -120,14 +121,14 @@ scan(): boolean
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.scan(); wifi.scan();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.getScanInfos ## wifi.getScanInfos
...@@ -164,10 +165,11 @@ getScanInfos(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): void ...@@ -164,10 +165,11 @@ getScanInfos(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): void
| callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&gt; | 是 | 回调函数。当成功时,err为0,data为扫描到的热点;否则err为非0值,data为空。 | | callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&gt; | 是 | 回调函数。当成功时,err为0,data为扫描到的热点;否则err为非0值,data为空。 |
**示例:** **示例:**
```js
import wifi from '@ohos.wifi';
wifi.getScanInfos((err, result) => { ```js
import wifi from '@ohos.wifi';
wifi.getScanInfos((err, result) => {
if (err) { if (err) {
console.error("get scan info error"); console.error("get scan info error");
return; return;
...@@ -186,9 +188,9 @@ getScanInfos(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): void ...@@ -186,9 +188,9 @@ getScanInfos(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): void
console.info("channelWidth: " + result[i].channelWidth); console.info("channelWidth: " + result[i].channelWidth);
console.info("timestamp: " + result[i].timestamp); console.info("timestamp: " + result[i].timestamp);
} }
}); });
wifi.getScanInfos().then(result => { wifi.getScanInfos().then(result => {
var len = Object.keys(result).length; var len = Object.keys(result).length;
console.log("wifi received scan info: " + len); console.log("wifi received scan info: " + len);
for (var i = 0; i < len; ++i) { for (var i = 0; i < len; ++i) {
...@@ -202,8 +204,8 @@ getScanInfos(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): void ...@@ -202,8 +204,8 @@ getScanInfos(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): void
console.info("channelWidth: " + result[i].channelWidth); console.info("channelWidth: " + result[i].channelWidth);
console.info("timestamp: " + result[i].timestamp); console.info("timestamp: " + result[i].timestamp);
} }
}); });
``` ```
## WifiScanInfo ## WifiScanInfo
...@@ -285,10 +287,10 @@ addDeviceConfig(config: WifiDeviceConfig): Promise&lt;number&gt; ...@@ -285,10 +287,10 @@ addDeviceConfig(config: WifiDeviceConfig): Promise&lt;number&gt;
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
ssid : "****", ssid : "****",
preSharedKey : "****", preSharedKey : "****",
...@@ -297,9 +299,9 @@ addDeviceConfig(config: WifiDeviceConfig): Promise&lt;number&gt; ...@@ -297,9 +299,9 @@ addDeviceConfig(config: WifiDeviceConfig): Promise&lt;number&gt;
wifi.addDeviceConfig(config).then(result => { wifi.addDeviceConfig(config).then(result => {
console.info("result:" + JSON.stringify(result)); console.info("result:" + JSON.stringify(result));
}); });
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## WifiDeviceConfig ## WifiDeviceConfig
...@@ -378,10 +380,10 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;) ...@@ -378,10 +380,10 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;)
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
ssid : "****", ssid : "****",
preSharedKey : "****", preSharedKey : "****",
...@@ -390,9 +392,9 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;) ...@@ -390,9 +392,9 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;)
wifi.addDeviceConfig(config,(error,result) => { wifi.addDeviceConfig(config,(error,result) => {
console.info("result:" + JSON.stringify(result)); console.info("result:" + JSON.stringify(result));
}); });
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.addUntrustedConfig<sup>7+</sup> ## wifi.addUntrustedConfig<sup>7+</sup>
...@@ -415,11 +417,12 @@ addUntrustedConfig(config: WifiDeviceConfig): Promise&lt;boolean&gt; ...@@ -415,11 +417,12 @@ addUntrustedConfig(config: WifiDeviceConfig): Promise&lt;boolean&gt;
| **类型** | **说明** | | **类型** | **说明** |
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise对象。表示操作结果,true: 成功, false: 失败。 | | Promise&lt;boolean&gt; | Promise对象。表示操作结果,true: 成功, false: 失败。 |
**示例:** **示例:**
````` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
ssid : "****", ssid : "****",
preSharedKey : "****", preSharedKey : "****",
...@@ -428,10 +431,10 @@ addUntrustedConfig(config: WifiDeviceConfig): Promise&lt;boolean&gt; ...@@ -428,10 +431,10 @@ addUntrustedConfig(config: WifiDeviceConfig): Promise&lt;boolean&gt;
wifi.addUntrustedConfig(config).then(result => { wifi.addUntrustedConfig(config).then(result => {
console.info("result:" + JSON.stringify(result)); console.info("result:" + JSON.stringify(result));
}); });
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
````` ```
## wifi.addUntrustedConfig<sup>7+</sup> ## wifi.addUntrustedConfig<sup>7+</sup>
...@@ -451,10 +454,10 @@ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;boolean& ...@@ -451,10 +454,10 @@ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;boolean&
| callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 |
**示例:** **示例:**
````` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
ssid : "****", ssid : "****",
preSharedKey : "****", preSharedKey : "****",
...@@ -463,10 +466,10 @@ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;boolean& ...@@ -463,10 +466,10 @@ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;boolean&
wifi.addUntrustedConfig(config,(error,result) => { wifi.addUntrustedConfig(config,(error,result) => {
console.info("result:" + JSON.stringify(result)); console.info("result:" + JSON.stringify(result));
}); });
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
````` ```
## wifi.removeUntrustedConfig<sup>7+</sup> ## wifi.removeUntrustedConfig<sup>7+</sup>
...@@ -490,17 +493,19 @@ removeUntrustedConfig(config: WifiDeviceConfig): Promise&lt;boolean&gt; ...@@ -490,17 +493,19 @@ removeUntrustedConfig(config: WifiDeviceConfig): Promise&lt;boolean&gt;
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise对象。表示操作结果,true: 成功, false: 失败。 | | Promise&lt;boolean&gt; | Promise对象。表示操作结果,true: 成功, false: 失败。 |
``` **示例:**
import wifi from '@ohos.wifi';
try { ```js
import wifi from '@ohos.wifi';
try {
let networkId = 0; let networkId = 0;
wifi.removeUntrustedConfig(networkId).then(result => { wifi.removeUntrustedConfig(networkId).then(result => {
console.info("result:" + JSON.stringify(result)); console.info("result:" + JSON.stringify(result));
}); });
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
...@@ -522,17 +527,17 @@ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;boole ...@@ -522,17 +527,17 @@ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;boole
| callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let networkId = 0; let networkId = 0;
wifi.removeUntrustedConfig(networkId,(error,result) => { wifi.removeUntrustedConfig(networkId,(error,result) => {
console.info("result:" + JSON.stringify(result)); console.info("result:" + JSON.stringify(result));
}); });
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.connectToNetwork ## wifi.connectToNetwork
...@@ -561,15 +566,15 @@ connectToNetwork(networkId: number): boolean ...@@ -561,15 +566,15 @@ connectToNetwork(networkId: number): boolean
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let networkId = 0; let networkId = 0;
wifi.connectToNetwork(networkId); wifi.connectToNetwork(networkId);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.connectToDevice ## wifi.connectToDevice
...@@ -598,10 +603,10 @@ connectToDevice(config: WifiDeviceConfig): boolean ...@@ -598,10 +603,10 @@ connectToDevice(config: WifiDeviceConfig): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
ssid : "****", ssid : "****",
preSharedKey : "****", preSharedKey : "****",
...@@ -609,9 +614,9 @@ connectToDevice(config: WifiDeviceConfig): boolean ...@@ -609,9 +614,9 @@ connectToDevice(config: WifiDeviceConfig): boolean
} }
wifi.connectToDevice(config); wifi.connectToDevice(config);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.disconnect ## wifi.disconnect
...@@ -634,14 +639,14 @@ disconnect(): boolean ...@@ -634,14 +639,14 @@ disconnect(): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.disconnect(); wifi.disconnect();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.getSignalLevel ## wifi.getSignalLevel
...@@ -668,17 +673,17 @@ getSignalLevel(rssi: number, band: number): number ...@@ -668,17 +673,17 @@ getSignalLevel(rssi: number, band: number): number
| number | 信号强度,取值范围为[0,&nbsp;4]。 | | number | 信号强度,取值范围为[0,&nbsp;4]。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let rssi = 0; let rssi = 0;
let band = 0; let band = 0;
let level = wifi.getSignalLevel(rssi,band); let level = wifi.getSignalLevel(rssi,band);
console.info("lelvel:" + JSON.stringify(lelvel)); console.info("lelvel:" + JSON.stringify(lelvel));
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
...@@ -716,23 +721,23 @@ getLinkedInfo(callback: AsyncCallback&lt;WifiLinkedInfo&gt;): void ...@@ -716,23 +721,23 @@ getLinkedInfo(callback: AsyncCallback&lt;WifiLinkedInfo&gt;): void
| callback | AsyncCallback&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | 是 | 回调函数。当获取成功时,err为0,data表示WLAN连接信息。如果error为非0,表示处理出现错误。 | | callback | AsyncCallback&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | 是 | 回调函数。当获取成功时,err为0,data表示WLAN连接信息。如果error为非0,表示处理出现错误。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
wifi.getLinkedInfo((err, data) => { wifi.getLinkedInfo((err, data) => {
if (err) { if (err) {
console.error("get linked info error"); console.error("get linked info error");
return; return;
} }
console.info("get wifi linked info: " + JSON.stringify(data)); console.info("get wifi linked info: " + JSON.stringify(data));
}); });
wifi.getLinkedInfo().then(data => { wifi.getLinkedInfo().then(data => {
console.info("get wifi linked info: " + JSON.stringify(data)); console.info("get wifi linked info: " + JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.info("get linked info error"); console.info("get linked info error");
}); });
``` ```
## WifiLinkedInfo ## WifiLinkedInfo
...@@ -877,16 +882,16 @@ isFeatureSupported(featureId: number): boolean ...@@ -877,16 +882,16 @@ isFeatureSupported(featureId: number): boolean
| boolean | true:支持,&nbsp;false:不支持。 | | boolean | true:支持,&nbsp;false:不支持。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let featureId = 0 let featureId = 0
let ret = wifi.isFeatureSupported(featureId); let ret = wifi.isFeatureSupported(featureId);
console.info("isFeatureSupported:" + ret); console.info("isFeatureSupported:" + ret);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
...@@ -909,15 +914,15 @@ getDeviceMacAddress(): string[] ...@@ -909,15 +914,15 @@ getDeviceMacAddress(): string[]
| string[] | MAC地址。 | | string[] | MAC地址。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let ret = wifi.getDeviceMacAddress(); let ret = wifi.getDeviceMacAddress();
console.info("deviceMacAddress:" + JSON.stringify(ret)); console.info("deviceMacAddress:" + JSON.stringify(ret));
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
...@@ -938,15 +943,15 @@ getIpInfo(): IpInfo ...@@ -938,15 +943,15 @@ getIpInfo(): IpInfo
| [IpInfo](#ipinfo7) | IP信息。 | | [IpInfo](#ipinfo7) | IP信息。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let info = wifi.getIpInfo(); let info = wifi.getIpInfo();
console.info("info:" + JSON.stringify(info)); console.info("info:" + JSON.stringify(info));
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## IpInfo<sup>7+</sup> ## IpInfo<sup>7+</sup>
...@@ -983,15 +988,15 @@ getCountryCode(): string ...@@ -983,15 +988,15 @@ getCountryCode(): string
| string | 国家码。 | | string | 国家码。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let code = wifi.getCountryCode(); let code = wifi.getCountryCode();
console.info("code:" + code); console.info("code:" + code);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.reassociate<sup>7+</sup> ## wifi.reassociate<sup>7+</sup>
...@@ -1013,14 +1018,14 @@ reassociate(): boolean ...@@ -1013,14 +1018,14 @@ reassociate(): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.reassociate(); wifi.reassociate();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.reconnect<sup>7+</sup> ## wifi.reconnect<sup>7+</sup>
...@@ -1042,14 +1047,14 @@ reconnect(): boolean ...@@ -1042,14 +1047,14 @@ reconnect(): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.reconnect(); wifi.reconnect();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.getDeviceConfigs<sup>7+</sup> ## wifi.getDeviceConfigs<sup>7+</sup>
...@@ -1071,15 +1076,15 @@ getDeviceConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; ...@@ -1071,15 +1076,15 @@ getDeviceConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt;
| &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; | 网络配置信息的数组。 | | &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; | 网络配置信息的数组。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let configs = wifi.getDeviceConfigs(); let configs = wifi.getDeviceConfigs();
console.info("configs:" + JSON.stringify(configs)); console.info("configs:" + JSON.stringify(configs));
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.updateNetwork<sup>7+</sup> ## wifi.updateNetwork<sup>7+</sup>
...@@ -1107,10 +1112,10 @@ updateNetwork(config: WifiDeviceConfig): number ...@@ -1107,10 +1112,10 @@ updateNetwork(config: WifiDeviceConfig): number
| number | 返回更新的网络配置ID,如果值为-1表示更新失败。 | | number | 返回更新的网络配置ID,如果值为-1表示更新失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
ssid : "****", ssid : "****",
preSharedKey : "****", preSharedKey : "****",
...@@ -1118,9 +1123,9 @@ updateNetwork(config: WifiDeviceConfig): number ...@@ -1118,9 +1123,9 @@ updateNetwork(config: WifiDeviceConfig): number
} }
let ret = wifi.updateNetwork(config); let ret = wifi.updateNetwork(config);
console.error("ret:" + ret); console.error("ret:" + ret);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.disableNetwork<sup>7+</sup> ## wifi.disableNetwork<sup>7+</sup>
...@@ -1148,15 +1153,15 @@ disableNetwork(netId: number): boolean ...@@ -1148,15 +1153,15 @@ disableNetwork(netId: number): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let netId = 0; let netId = 0;
wifi.disableNetwork(netId); wifi.disableNetwork(netId);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.removeAllNetwork<sup>7+</sup> ## wifi.removeAllNetwork<sup>7+</sup>
...@@ -1178,14 +1183,14 @@ removeAllNetwork(): boolean ...@@ -1178,14 +1183,14 @@ removeAllNetwork(): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.removeAllNetwork(); wifi.removeAllNetwork();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.removeDevice<sup>7+</sup> ## wifi.removeDevice<sup>7+</sup>
...@@ -1213,15 +1218,15 @@ removeDevice(id: number): boolean ...@@ -1213,15 +1218,15 @@ removeDevice(id: number): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let id = 0; let id = 0;
wifi.removeDevice(id); wifi.removeDevice(id);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.enableHotspot<sup>7+</sup> ## wifi.enableHotspot<sup>7+</sup>
...@@ -1243,14 +1248,14 @@ enableHotspot(): boolean ...@@ -1243,14 +1248,14 @@ enableHotspot(): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。| | boolean | true:操作成功,&nbsp;false:操作失败。|
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.enableHotspot(); wifi.enableHotspot();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.disableHotspot<sup>7+</sup> ## wifi.disableHotspot<sup>7+</sup>
...@@ -1272,14 +1277,14 @@ disableHotspot(): boolean ...@@ -1272,14 +1277,14 @@ disableHotspot(): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。| | boolean | true:操作成功,&nbsp;false:操作失败。|
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifiManager'; import wifi from '@ohos.wifiManager';
try { try {
wifiManager.disableHotspot(); wifiManager.disableHotspot();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.isHotspotDualBandSupported<sup>7+</sup> ## wifi.isHotspotDualBandSupported<sup>7+</sup>
...@@ -1301,15 +1306,15 @@ isHotspotDualBandSupported(): boolean ...@@ -1301,15 +1306,15 @@ isHotspotDualBandSupported(): boolean
| boolean | true:支持,&nbsp;false:不支持。| | boolean | true:支持,&nbsp;false:不支持。|
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let ret = wifi.isHotspotDualBandSupported(); let ret = wifi.isHotspotDualBandSupported();
console.info("result:" + ret); console.info("result:" + ret);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.isHotspotActive<sup>7+</sup> ## wifi.isHotspotActive<sup>7+</sup>
...@@ -1331,15 +1336,15 @@ isHotspotActive(): boolean ...@@ -1331,15 +1336,15 @@ isHotspotActive(): boolean
| boolean | true:已使能,&nbsp;false:未使能。| | boolean | true:已使能,&nbsp;false:未使能。|
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let ret = wifi.isHotspotActive(); let ret = wifi.isHotspotActive();
console.info("result:" + ret); console.info("result:" + ret);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.setHotspotConfig<sup>7+</sup> ## wifi.setHotspotConfig<sup>7+</sup>
...@@ -1367,10 +1372,10 @@ setHotspotConfig(config: HotspotConfig): boolean ...@@ -1367,10 +1372,10 @@ setHotspotConfig(config: HotspotConfig): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
ssid: "****", ssid: "****",
securityType: 3, securityType: 3,
...@@ -1381,9 +1386,9 @@ setHotspotConfig(config: HotspotConfig): boolean ...@@ -1381,9 +1386,9 @@ setHotspotConfig(config: HotspotConfig): boolean
} }
let ret = wifi.setHotspotConfig(); let ret = wifi.setHotspotConfig();
console.info("result:" + ret); console.info("result:" + ret);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## HotspotConfig<sup>7+</sup> ## HotspotConfig<sup>7+</sup>
...@@ -1422,15 +1427,15 @@ getHotspotConfig(): HotspotConfig ...@@ -1422,15 +1427,15 @@ getHotspotConfig(): HotspotConfig
| [HotspotConfig](#hotspotconfig7) | 热点的配置信息。 | | [HotspotConfig](#hotspotconfig7) | 热点的配置信息。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = wifi.getHotspotConfig(); let config = wifi.getHotspotConfig();
console.info("result:" + JSON.stringify(config)); console.info("result:" + JSON.stringify(config));
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.getStations<sup>7+</sup> ## wifi.getStations<sup>7+</sup>
...@@ -1452,15 +1457,15 @@ getStations(): &nbsp;Array&lt;[StationInfo](#stationinfo7)&gt; ...@@ -1452,15 +1457,15 @@ getStations(): &nbsp;Array&lt;[StationInfo](#stationinfo7)&gt;
| &nbsp;Array&lt;[StationInfo](#stationinfo7)&gt; | 连接的设备数组。 | | &nbsp;Array&lt;[StationInfo](#stationinfo7)&gt; | 连接的设备数组。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let stations = wifi.getStations(); let stations = wifi.getStations();
console.info("result:" + JSON.stringify(stations)); console.info("result:" + JSON.stringify(stations));
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## StationInfo<sup>7+</sup> ## StationInfo<sup>7+</sup>
...@@ -1538,20 +1543,20 @@ getP2pLinkedInfo(callback: AsyncCallback&lt;WifiP2pLinkedInfo&gt;): void ...@@ -1538,20 +1543,20 @@ getP2pLinkedInfo(callback: AsyncCallback&lt;WifiP2pLinkedInfo&gt;): void
| callback | AsyncCallback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | 是 | 回调函数。当操作成功时,err为0,data表示P2P连接信息。如果error为非0,表示处理出现错误。 | | callback | AsyncCallback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | 是 | 回调函数。当操作成功时,err为0,data表示P2P连接信息。如果error为非0,表示处理出现错误。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
wifi.getP2pLinkedInfo((err, data) => { wifi.getP2pLinkedInfo((err, data) => {
if (err) { if (err) {
console.error("get p2p linked info error"); console.error("get p2p linked info error");
return; return;
} }
console.info("get wifi p2p linked info: " + JSON.stringify(data)); console.info("get wifi p2p linked info: " + JSON.stringify(data));
}); });
wifi.getP2pLinkedInfo().then(data => { wifi.getP2pLinkedInfo().then(data => {
console.info("get wifi p2p linked info: " + JSON.stringify(data)); console.info("get wifi p2p linked info: " + JSON.stringify(data));
}); });
``` ```
## wifi.getCurrentGroup<sup>8+</sup> ## wifi.getCurrentGroup<sup>8+</sup>
...@@ -1588,20 +1593,20 @@ getCurrentGroup(callback: AsyncCallback&lt;WifiP2pGroupInfo&gt;): void ...@@ -1588,20 +1593,20 @@ getCurrentGroup(callback: AsyncCallback&lt;WifiP2pGroupInfo&gt;): void
| callback | AsyncCallback&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 | | callback | AsyncCallback&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
wifi.getCurrentGroup((err, data) => { wifi.getCurrentGroup((err, data) => {
if (err) { if (err) {
console.error("get current P2P group error"); console.error("get current P2P group error");
return; return;
} }
console.info("get current P2P group: " + JSON.stringify(data)); console.info("get current P2P group: " + JSON.stringify(data));
}); });
wifi.getCurrentGroup().then(data => { wifi.getCurrentGroup().then(data => {
console.info("get current P2P group: " + JSON.stringify(data)); console.info("get current P2P group: " + JSON.stringify(data));
}); });
``` ```
## wifi.getP2pPeerDevices<sup>8+</sup> ## wifi.getP2pPeerDevices<sup>8+</sup>
...@@ -1638,20 +1643,20 @@ getP2pPeerDevices(callback: AsyncCallback&lt;WifiP2pDevice[]&gt;): void ...@@ -1638,20 +1643,20 @@ getP2pPeerDevices(callback: AsyncCallback&lt;WifiP2pDevice[]&gt;): void
| callback | AsyncCallback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 | | callback | AsyncCallback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifiManager'; import wifi from '@ohos.wifiManager';
wifi.getP2pPeerDevices((err, data) => { wifi.getP2pPeerDevices((err, data) => {
if (err) { if (err) {
console.error("get P2P peer devices error"); console.error("get P2P peer devices error");
return; return;
} }
console.info("get P2P peer devices: " + JSON.stringify(data)); console.info("get P2P peer devices: " + JSON.stringify(data));
}); });
wifi.getP2pPeerDevices().then(data => { wifi.getP2pPeerDevices().then(data => {
console.info("get P2P peer devices: " + JSON.stringify(data)); console.info("get P2P peer devices: " + JSON.stringify(data));
}); });
``` ```
## WifiP2pDevice<sup>8+</sup> ## WifiP2pDevice<sup>8+</sup>
...@@ -1707,10 +1712,10 @@ createGroup(config: WifiP2PConfig): boolean ...@@ -1707,10 +1712,10 @@ createGroup(config: WifiP2PConfig): boolean
| boolean | true:创建群组操作执行成功,&nbsp;false:创建群组操作执行失败。 | | boolean | true:创建群组操作执行成功,&nbsp;false:创建群组操作执行失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let config = { let config = {
deviceAddress: "****", deviceAddress: "****",
netId: 0, netId: 0,
...@@ -1720,9 +1725,9 @@ createGroup(config: WifiP2PConfig): boolean ...@@ -1720,9 +1725,9 @@ createGroup(config: WifiP2PConfig): boolean
} }
wifi.createGroup(config); wifi.createGroup(config);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## WifiP2PConfig<sup>8+</sup> ## WifiP2PConfig<sup>8+</sup>
...@@ -1770,14 +1775,14 @@ removeGroup(): boolean ...@@ -1770,14 +1775,14 @@ removeGroup(): boolean
| boolean | true:操作执行成功,&nbsp;false:操作执行失败。 | | boolean | true:操作执行成功,&nbsp;false:操作执行失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.removeGroup(); wifi.removeGroup();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.p2pConnect<sup>8+</sup> ## wifi.p2pConnect<sup>8+</sup>
...@@ -1805,10 +1810,10 @@ p2pConnect(config: WifiP2PConfig): boolean ...@@ -1805,10 +1810,10 @@ p2pConnect(config: WifiP2PConfig): boolean
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pConnectionChangeFunc = result => { var recvP2pConnectionChangeFunc = result => {
console.info("p2p connection change receive event: " + JSON.stringify(result)); console.info("p2p connection change receive event: " + JSON.stringify(result));
wifi.getP2pLinkedInfo((err, data) => { wifi.getP2pLinkedInfo((err, data) => {
if (err) { if (err) {
...@@ -1817,15 +1822,15 @@ p2pConnect(config: WifiP2PConfig): boolean ...@@ -1817,15 +1822,15 @@ p2pConnect(config: WifiP2PConfig): boolean
} }
console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); console.info("get getP2pLinkedInfo: " + JSON.stringify(data));
}); });
} }
wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc);
var recvP2pDeviceChangeFunc = result => { var recvP2pDeviceChangeFunc = result => {
console.info("p2p device change receive event: " + JSON.stringify(result)); console.info("p2p device change receive event: " + JSON.stringify(result));
} }
wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc);
var recvP2pPeerDeviceChangeFunc = result => { var recvP2pPeerDeviceChangeFunc = result => {
console.info("p2p peer device change receive event: " + JSON.stringify(result)); console.info("p2p peer device change receive event: " + JSON.stringify(result));
wifi.getP2pPeerDevices((err, data) => { wifi.getP2pPeerDevices((err, data) => {
if (err) { if (err) {
...@@ -1848,10 +1853,10 @@ p2pConnect(config: WifiP2PConfig): boolean ...@@ -1848,10 +1853,10 @@ p2pConnect(config: WifiP2PConfig): boolean
} }
} }
}); });
} }
wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);
var recvP2pPersistentGroupChangeFunc = () => { var recvP2pPersistentGroupChangeFunc = () => {
console.info("p2p persistent group change receive event"); console.info("p2p persistent group change receive event");
wifi.getCurrentGroup((err, data) => { wifi.getCurrentGroup((err, data) => {
...@@ -1861,15 +1866,15 @@ p2pConnect(config: WifiP2PConfig): boolean ...@@ -1861,15 +1866,15 @@ p2pConnect(config: WifiP2PConfig): boolean
} }
console.info("get current group: " + JSON.stringify(data)); console.info("get current group: " + JSON.stringify(data));
}); });
} }
wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);
setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000);
setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000);
setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000);
setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000);
console.info("start discover devices -> " + wifi.startDiscoverDevices()); console.info("start discover devices -> " + wifi.startDiscoverDevices());
``` ```
## wifi.p2pCancelConnect<sup>8+</sup> ## wifi.p2pCancelConnect<sup>8+</sup>
...@@ -1888,14 +1893,14 @@ p2pCancelConnect(): boolean ...@@ -1888,14 +1893,14 @@ p2pCancelConnect(): boolean
| boolean | true:操作执行成功,&nbsp;false:操作执行失败。 | | boolean | true:操作执行成功,&nbsp;false:操作执行失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.p2pCancelConnect(); wifi.p2pCancelConnect();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.startDiscoverDevices<sup>8+</sup> ## wifi.startDiscoverDevices<sup>8+</sup>
...@@ -1915,14 +1920,14 @@ startDiscoverDevices(): boolean ...@@ -1915,14 +1920,14 @@ startDiscoverDevices(): boolean
| boolean | true:操作执行成功,&nbsp;false:操作执行失败。 | | boolean | true:操作执行成功,&nbsp;false:操作执行失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.startDiscoverDevices(); wifi.startDiscoverDevices();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.stopDiscoverDevices<sup>8+</sup> ## wifi.stopDiscoverDevices<sup>8+</sup>
...@@ -1942,14 +1947,14 @@ stopDiscoverDevices(): boolean ...@@ -1942,14 +1947,14 @@ stopDiscoverDevices(): boolean
| boolean | true:操作执行成功,操作执行失败。 | | boolean | true:操作执行成功,操作执行失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
wifi.stopDiscoverDevices(); wifi.stopDiscoverDevices();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.deletePersistentGroup<sup>8+</sup> ## wifi.deletePersistentGroup<sup>8+</sup>
...@@ -1978,15 +1983,15 @@ deletePersistentGroup(netId: number): boolean ...@@ -1978,15 +1983,15 @@ deletePersistentGroup(netId: number): boolean
| boolean | true:操作执行成功,操作执行失败。 | | boolean | true:操作执行成功,操作执行失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let netId = 0; let netId = 0;
wifi.deletePersistentGroup(netId); wifi.deletePersistentGroup(netId);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## WifiP2pGroupInfo<sup>8+</sup> ## WifiP2pGroupInfo<sup>8+</sup>
...@@ -2033,15 +2038,15 @@ setDeviceName(devName: string): boolean ...@@ -2033,15 +2038,15 @@ setDeviceName(devName: string): boolean
| boolean | true:操作成功,&nbsp;false:操作失败。 | | boolean | true:操作成功,&nbsp;false:操作失败。 |
**示例:** **示例:**
``` ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let name = "****"; let name = "****";
wifi.setDeviceName(netId); wifi.setDeviceName(netId);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.on('wifiStateChange')<sup>7+</sup> ## wifi.on('wifiStateChange')<sup>7+</sup>
...@@ -2089,19 +2094,19 @@ off(type: "wifiStateChange", callback?: Callback&lt;number&gt;): void ...@@ -2089,19 +2094,19 @@ off(type: "wifiStateChange", callback?: Callback&lt;number&gt;): void
| callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvPowerNotifyFunc = result => { var recvPowerNotifyFunc = result => {
console.info("Receive power state change event: " + result); console.info("Receive power state change event: " + result);
} }
// Register event // Register event
wifi.on("wifiStateChange", recvPowerNotifyFunc); wifi.on("wifiStateChange", recvPowerNotifyFunc);
// Unregister event // Unregister event
wifi.off("wifiStateChange", recvPowerNotifyFunc); wifi.off("wifiStateChange", recvPowerNotifyFunc);
``` ```
## wifi.on('wifiConnectionChange')<sup>7+</sup> ## wifi.on('wifiConnectionChange')<sup>7+</sup>
...@@ -2147,19 +2152,19 @@ off(type: "wifiConnectionChange", callback?: Callback&lt;number&gt;): void ...@@ -2147,19 +2152,19 @@ off(type: "wifiConnectionChange", callback?: Callback&lt;number&gt;): void
| callback | Callback&lt;number&gt; | 否 | 连接状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;number&gt; | 否 | 连接状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvWifiConnectionChangeFunc = result => { var recvWifiConnectionChangeFunc = result => {
console.info("Receive wifi connection change event: " + result); console.info("Receive wifi connection change event: " + result);
} }
// Register event // Register event
wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc);
// Unregister event // Unregister event
wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc);
``` ```
## wifi.on('wifiScanStateChange')<sup>7+</sup> ## wifi.on('wifiScanStateChange')<sup>7+</sup>
...@@ -2204,19 +2209,19 @@ off(type: "wifiScanStateChange", callback?: Callback&lt;number&gt;): void ...@@ -2204,19 +2209,19 @@ off(type: "wifiScanStateChange", callback?: Callback&lt;number&gt;): void
| callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvWifiScanStateChangeFunc = result => { var recvWifiScanStateChangeFunc = result => {
console.info("Receive Wifi scan state change event: " + result); console.info("Receive Wifi scan state change event: " + result);
} }
// Register event // Register event
wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc);
// Unregister event // Unregister event
wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc);
``` ```
## wifi.on('wifiRssiChange')<sup>7+</sup> ## wifi.on('wifiRssiChange')<sup>7+</sup>
...@@ -2254,20 +2259,19 @@ off(type: "wifiRssiChange", callback?: Callback&lt;number&gt;): void ...@@ -2254,20 +2259,19 @@ off(type: "wifiRssiChange", callback?: Callback&lt;number&gt;): void
| callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvWifiRssiChangeFunc = result => { var recvWifiRssiChangeFunc = result => {
console.info("Receive wifi rssi change event: " + result); console.info("Receive wifi rssi change event: " + result);
} }
// Register event
wifi.on("wifiRssiChange", recvWifiRssiChangeFunc);
// Unregister event // Register event
wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); wifi.on("wifiRssiChange", recvWifiRssiChangeFunc);
```
// Unregister event
wifi.off("wifiRssiChange", recvWifiRssiChangeFunc);
```
## wifi.on('hotspotStateChange')<sup>7+</sup> ## wifi.on('hotspotStateChange')<sup>7+</sup>
on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void
...@@ -2295,20 +2299,19 @@ on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void ...@@ -2295,20 +2299,19 @@ on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void
| 3 | 去激活中。 | | 3 | 去激活中。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvHotspotStateChangeFunc = result => { var recvHotspotStateChangeFunc = result => {
console.info("Receive hotspot state change event: " + result); console.info("Receive hotspot state change event: " + result);
} }
// Register event
wifi.on("hotspotStateChange", recvHotspotStateChangeFunc);
// Unregister event // Register event
wifi.off("hotspotStateChange", recvHotspotStateChangeFunc); wifi.on("hotspotStateChange", recvHotspotStateChangeFunc);
```
// Unregister event
wifi.off("hotspotStateChange", recvHotspotStateChangeFunc);
```
## wifi.off('hotspotStateChange')<sup>7+</sup> ## wifi.off('hotspotStateChange')<sup>7+</sup>
...@@ -2373,19 +2376,19 @@ off(type: "p2pStateChange", callback?: Callback&lt;number&gt;): void ...@@ -2373,19 +2376,19 @@ off(type: "p2pStateChange", callback?: Callback&lt;number&gt;): void
| callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pStateChangeFunc = result => { var recvP2pStateChangeFunc = result => {
console.info("Receive p2p state change event: " + result); console.info("Receive p2p state change event: " + result);
} }
// Register event // Register event
wifi.on("p2pStateChange", recvP2pStateChangeFunc); wifi.on("p2pStateChange", recvP2pStateChangeFunc);
// Unregister event // Unregister event
wifi.off("p2pStateChange", recvP2pStateChangeFunc); wifi.off("p2pStateChange", recvP2pStateChangeFunc);
``` ```
## wifi.on('p2pConnectionChange')<sup>8+</sup> ## wifi.on('p2pConnectionChange')<sup>8+</sup>
...@@ -2423,19 +2426,19 @@ off(type: "p2pConnectionChange", callback?: Callback&lt;WifiP2pLinkedInfo&gt;): ...@@ -2423,19 +2426,19 @@ off(type: "p2pConnectionChange", callback?: Callback&lt;WifiP2pLinkedInfo&gt;):
| callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pConnectionChangeFunc = result => { var recvP2pConnectionChangeFunc = result => {
console.info("Receive p2p connection change event: " + result); console.info("Receive p2p connection change event: " + result);
} }
// Register event // Register event
wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc);
// Unregister event // Unregister event
wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc); wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);
``` ```
## wifi.on('p2pDeviceChange')<sup>8+</sup> ## wifi.on('p2pDeviceChange')<sup>8+</sup>
...@@ -2473,19 +2476,19 @@ off(type: "p2pDeviceChange", callback?: Callback&lt;WifiP2pDevice&gt;): void ...@@ -2473,19 +2476,19 @@ off(type: "p2pDeviceChange", callback?: Callback&lt;WifiP2pDevice&gt;): void
| callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pDeviceChangeFunc = result => { var recvP2pDeviceChangeFunc = result => {
console.info("Receive recv p2p device change event: " + result); console.info("Receive recv p2p device change event: " + result);
} }
// Register event // Register event
wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc);
// Unregister event // Unregister event
wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc); wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);
``` ```
## wifi.on('p2pPeerDeviceChange')<sup>8+</sup> ## wifi.on('p2pPeerDeviceChange')<sup>8+</sup>
...@@ -2523,19 +2526,19 @@ off(type: "p2pPeerDeviceChange", callback?: Callback&lt;WifiP2pDevice[]&gt;): vo ...@@ -2523,19 +2526,19 @@ off(type: "p2pPeerDeviceChange", callback?: Callback&lt;WifiP2pDevice[]&gt;): vo
| callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pPeerDeviceChangeFunc = result => { var recvP2pPeerDeviceChangeFunc = result => {
console.info("Receive recv p2p peer device change event: " + result); console.info("Receive recv p2p peer device change event: " + result);
} }
// Register event // Register event
wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);
// Unregister event // Unregister event
wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);
``` ```
## wifi.on('p2pPersistentGroupChange')<sup>8+</sup> ## wifi.on('p2pPersistentGroupChange')<sup>8+</sup>
...@@ -2573,20 +2576,20 @@ off(type: "p2pPersistentGroupChange", callback?: Callback&lt;void&gt;): void ...@@ -2573,20 +2576,20 @@ off(type: "p2pPersistentGroupChange", callback?: Callback&lt;void&gt;): void
| callback | Callback&lt;void&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;void&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pPersistentGroupChangeFunc = result => { var recvP2pPersistentGroupChangeFunc = result => {
console.info("Receive recv p2p persistent group change event: " + result); console.info("Receive recv p2p persistent group change event: " + result);
} }
// Register event // Register event
wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);
// Unregister event // Unregister event
wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);
``` ```
## wifi.on('p2pDiscoveryChange')<sup>8+</sup> ## wifi.on('p2pDiscoveryChange')<sup>8+</sup>
...@@ -2631,16 +2634,16 @@ off(type: "p2pDiscoveryChange", callback?: Callback&lt;number&gt;): void ...@@ -2631,16 +2634,16 @@ off(type: "p2pDiscoveryChange", callback?: Callback&lt;number&gt;): void
| callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | | callback | Callback&lt;number&gt; | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 |
**示例:** **示例:**
```js ```js
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pDiscoveryChangeFunc = result => { var recvP2pDiscoveryChangeFunc = result => {
console.info("Receive recv p2p discovery change event: " + result); console.info("Receive recv p2p discovery change event: " + result);
} }
// Register event // Register event
wifi.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); wifi.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc);
// Unregister event // Unregister event
wifi.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); wifi.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc);
``` ```
\ No newline at end of file \ No newline at end of file
...@@ -31,7 +31,7 @@ Text(content?: string | Resource) ...@@ -31,7 +31,7 @@ Text(content?: string | Resource)
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| ----------------------- | ----------------------------------- | ------------------------------------------- | | ----------------------- | ----------------------------------- | ------------------------------------------- |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式。<br/>默认值:TextAlign.Start<br/>说明:<br/>文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,即align属性中Alignment.TopStart、Alignment.Top、Alignment.TopEnd效果相同,控制内容在顶部,Alignment.Start、Alignment.Center、Alignment.End效果相同,控制内容垂直居中,Alignment.BottomStart、Alignment.Bottom、Alignment.BottomEnd效果相同,控制内容在底部。结合TextAlign属性可控制内容在水平方向的位置。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式。<br/>默认值:TextAlign.Start<br/>说明:<br/>文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,即align属性中Alignment.TopStart、Alignment.Top、Alignment.TopEnd效果相同,控制内容在顶部,Alignment.Start、Alignment.Center、Alignment.End效果相同,控制内容垂直居中,Alignment.BottomStart、Alignment.Bottom、Alignment.BottomEnd效果相同,控制内容在底部。结合TextAlign属性可控制内容在水平方向的位置。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| textOverflow | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。<br/>默认值:{overflow:&nbsp;TextOverflow.Clip}<br/>**说明:**<br/>文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。<br />`overflow`设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。设置TextOverflow.None与TextOverflow.Clip效果一样。当`overflow`设置为TextOverflow.Marquee时,文本在一行内滚动显示,设置`maxLines`属性不生效。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | textOverflow | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。<br/>默认值:{overflow:&nbsp;TextOverflow.Clip}<br/>**说明:**<br/>文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。<br />`overflow`设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。设置TextOverflow.None与TextOverflow.Clip效果一样。当`overflow`设置为TextOverflow.Marquee时,文本在一行内滚动显示,设置`maxLines``copyOption`属性均不生效。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| maxLines | number | 设置文本的最大行数。<br />默认值:Infinity<br/>**说明:**<br />默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 `textOverflow`来指定截断方式。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | maxLines | number | 设置文本的最大行数。<br />默认值:Infinity<br/>**说明:**<br />默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 `textOverflow`来指定截断方式。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| lineHeight | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | lineHeight | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| decoration | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor)<br/>} | 设置文本装饰线样式及其颜色。<br />默认值:{<br/>type:&nbsp;TextDecorationType.None,<br/>color:Color.Black<br/>} <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。| | decoration | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor)<br/>} | 设置文本装饰线样式及其颜色。<br />默认值:{<br/>type:&nbsp;TextDecorationType.None,<br/>color:Color.Black<br/>} <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
......
...@@ -42,7 +42,7 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te ...@@ -42,7 +42,7 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te
| showPasswordIcon<sup>9+</sup> | boolean | 密码输入模式时,输入框末尾的图标是否显示。<br/>默认值:true | | showPasswordIcon<sup>9+</sup> | boolean | 密码输入模式时,输入框末尾的图标是否显示。<br/>默认值:true |
| style<sup>9+</sup> | [TextInputStyle](#textinputstyle9枚举说明) | 设置输入框为默认风格或内联输入风格。<br/>默认值:TextInputStyle.Default | | style<sup>9+</sup> | [TextInputStyle](#textinputstyle9枚举说明) | 设置输入框为默认风格或内联输入风格。<br/>默认值:TextInputStyle.Default |
| textAlign<sup>9+</sup> | [TextAlign](ts-appendix-enums.md#textalign) | 设置输入文本在输入框中的对齐方式。<br/>默认值:TextAlign.Start | | textAlign<sup>9+</sup> | [TextAlign](ts-appendix-enums.md#textalign) | 设置输入文本在输入框中的对齐方式。<br/>默认值:TextAlign.Start |
| selectedBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | 设置文本选中底板颜色。 | | selectedBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | 设置文本选中底板颜色。<br/>如果未设置透明度,默认为不透明(例如:“0x80000000”为50%透明度黑色)。 |
| caretStyle<sup>10+</sup> | {<br/>width:&nbsp;[Length](ts-types.md#length)<br/>} | 设置光标风格。 | | caretStyle<sup>10+</sup> | {<br/>width:&nbsp;[Length](ts-types.md#length)<br/>} | 设置光标风格。 |
| caretPosition<sup>10+</sup> | number | 设置光标位置。 | | caretPosition<sup>10+</sup> | number | 设置光标位置。 |
......
# 键鼠穿越管理错误码 # 键鼠穿越管理错误码(待停用)
> **说明:** > **说明:**
> >
......
# 预置应用配置与安装指导
预置应用是指随OpenHarmony系统出厂预置的应用。
本文介绍开发者如何将一个非预置应用配置为预置应用,以及已有预置应用更新后如何重新安装。
## 将非预置应用配置为预置应用。
1. 确定预置应用支持的路径,可以通过下述命令查询。本文将以路径/system/etc/app/为例。
```
hdc_std param get const.cust.config_dir_layer
```
2. 在install_list.json中配置hap在设备上的路径。
```
hdc_std shell mount -o rw,renount /
hdc_std file recv /system/etc/app/install_list.json .
```
3. 按照json中的配置方式,配置对应的字段。
```
{
"app_dir":"system/app/xxxx/yyyy", // 设备上的hap路径,如果不存在,需要手动创建,并推送hap到此目录。
"removable":true // 是否支持卸载,false表示不可卸载,true表示可以卸载。
}
```
4. 修改完成后,将install_list.json文件推送到设备上,并重启设备生效。
```
hdc_std shell mount -o rw,remount /
hdc_std file send install_list.json /system/etc/app/install_list.json
hdc_std shell reboot
```
## 重新安装更新后的已有预置应用
有两种方法。
- 方法一:直接清空data,重启设备,应用会自动安装。
```
hdc_std shell mount -o rw,remount /
hdc_std shell rm /data/* -rf
hdc_std shell sync
hdc_std shell /system/bin/udevadm trigger
hdc_std shell reboot
```
- 方法二:如果该应用之前没有安装过,则可以执行下面命令后重启设备。
```
hdc_std shell mount -o rw,remount /
hdc_std shell param set persist.bms.test-upgrade true
hdc_std shell reboot
```
如果应用之前已经安装过,这时继续推送新的hap到/system/app/的路径下,则需要保证应用的版本号,分为[Stage模型的版本号(versionCode)](../../application-dev/quick-start/app-configuration-file.md)[FA模型的版本号(code)](../../application-dev/quick-start/app-structure.md#version对象内部结构)比之前的大。 这时执行方法二的命令,重启后应用同样可以正常安装。需要注意的是方法二命令,不需要反复执行, 重启之后依然生效。
\ No newline at end of file
...@@ -68,18 +68,3 @@ ...@@ -68,18 +68,3 @@
安装完成后,当界面输出“DevEco Device Tool successfully installed.”时,表示DevEco Device Tool安装成功。 安装完成后,当界面输出“DevEco Device Tool successfully installed.”时,表示DevEco Device Tool安装成功。
![zh-cn_image_0000001338201457](figures/zh-cn_image_0000001338201457.png) ![zh-cn_image_0000001338201457](figures/zh-cn_image_0000001338201457.png)
6. 使用如下apt-get命令安装后续操作所需的库和工具。
```shell
sudo apt-get update && sudo apt-get install binutils binutils-dev git git-lfs gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib gcc-arm-linux-gnueabi libc6-dev-i386 libc6-dev-amd64 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 bc gnutls-bin python3.8 python3-pip ruby genext2fs device-tree-compiler make libffi-dev e2fsprogs pkg-config perl openssl libssl-dev libelf-dev libdwarf-dev u-boot-tools mtd-utils cpio doxygen liblz4-tool openjdk-8-jre gcc g++ texinfo dosfstools mtools default-jre default-jdk libncurses5 apt-utils wget scons python3.8-distutils tar rsync git-core libxml2-dev lib32z-dev grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
>
> 以上安装命令适用于Ubuntu18.04,其他版本请根据安装包名称采用对应的安装命令。其中:
>
> - Python要求安装Python 3.8及以上版本,此处以Python 3.8为例。
>
> - Java要求java8及以上版本,此处以java8为例。
...@@ -20,8 +20,6 @@ OpenHarmony Stable Version类型的源码为OpenHarmony稳定版本源码,通 ...@@ -20,8 +20,6 @@ OpenHarmony Stable Version类型的源码为OpenHarmony稳定版本源码,通
## 操作步骤 ## 操作步骤
OpenHarmony稳定版本源码,支持OpenHarmony-v1.1.4-LTS、OpenHarmony-v3.0.3-LTS和OpenHarmony-v3.1-Release版本。
1. 打开DevEco Device Tool,进入Home页,点击**New Project**创建新工程。 1. 打开DevEco Device Tool,进入Home页,点击**New Project**创建新工程。
![zh-cn_image_0000001272258726](figures/zh-cn_image_0000001272258726.png) ![zh-cn_image_0000001272258726](figures/zh-cn_image_0000001272258726.png)
......
# 预置应用配置指南 # 预置应用配置与安装指导
OpenHarmony支持在不同产品上对预置应用进行差异化配置,设备厂商可根据需要对预置应用进行配置。 预置应用是指随设备出厂预置的应用。OpenHarmony支持在不同设备上对预置应用进行差异化配置,设备厂商可根据需要对与预置应用进行配置。
此外,OpenHarmony根据GetCfgDirList获得系统支持的预置目录,如system、chipset、sys_prod、chip_prod;并且按照返回的顺序越靠后优先级越高,如chip_prod的优先级高于system的优先级。 ## 将应用配置为预置应用
## 预置应用安装列表配置 1. 在进行预置应用配置前,使用如下命令查询系统支持的预置目录。
### 应用预置到系统中的配置步骤 命令查询结果如system、chipset、sys_prod、chip_prod等,并且返回的顺序越靠后优先级越高,如chip_prod的优先级高于system的优先级。本文以路径/system/etc/app/为例。
1. 在预置目录下创建应用的名称作为应用目录 ```
2. 将应用预置到应用目录下,如 /system/app/Hiworld/entry.hap hdc shell param get const.cust.config_dir_layer
3. 添加应用目录到[install_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list.json),根据需求配置removable ```
2. 在install_list.json中配置hap在设备上的路径。
```
hdc shell mount -o rw,remount /
hdc file recv /system/etc/app/install_list.json .
```
### 示例 3. 按照json中的配置方式,配置对应的字段。
``` ```
{ {
"install_list" : [ "install_list" : [
{ {
"app_dir" : "/system/app/Hiworld", "app_dir":"system/app/xxxx/yyyy", // 设备上的hap路径,如果不存在,需要手动创建,并推送hap到此目录。
"removable" : false // 是否可卸载 "removable":true // 是否支持卸载,false表示不可卸载,true表示可以卸载。
} }
] ]
} }
``` ```
## 预置不安装列表配置 4. 修改完成后,将install_list.json文件推送到设备上,并重启设备生效。
```
hdc shell mount -o rw,remount /
hdc file send install_list.json /system/etc/app/install_list.json
hdc shell reboot
```
## 更新预置应用
预置应用更新后,使用如下方法重新安装。
- 方法一:直接清空data,重启设备,应用会自动安装。
```
hdc shell mount -o rw,remount /
hdc shell rm /data/* -rf
hdc shell sync
hdc shell /system/bin/udevadm trigger
hdc shell reboot
```
- 方法二:执行如下命令,重启设备,应用即可安装。
如果应用之前已经安装过,这时推送新的hap到/system/app/路径下,需保证应用的版本号(Stage模型下对应app.json5配置文件中的[versionCode](../../application-dev/quick-start/app-configuration-file.md)标签;FA模型下对应配置文件中的[code](../../application-dev/quick-start/app-structure.md#version对象内部结构)标签)大于之前的版本号。
```
hdc shell mount -o rw,remount /
hdc shell param set persist.bms.test-upgrade true
hdc shell reboot
```
# 预置不安装列表配置
[uninstall_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/uninstall_list.json)的配置优先级高于install_list.json,在该文件中配置后,则对应的预置应用不会安装。 [uninstall_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/uninstall_list.json)的配置优先级高于install_list.json,在该文件中配置后,则对应的预置应用不会安装。
### 示例一 ## 示例一
``` ```
/system/etc/app/uninstall_list.json /system/etc/app/uninstall_list.json
...@@ -39,7 +77,7 @@ OpenHarmony支持在不同产品上对预置应用进行差异化配置,设备 ...@@ -39,7 +77,7 @@ OpenHarmony支持在不同产品上对预置应用进行差异化配置,设备
} }
``` ```
### 示例二 ## 示例二
``` ```
/system/etc/app/uninstall_list.json /system/etc/app/uninstall_list.json
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册