diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index 65f2b4c16ea42ecdf37082a5a9f8e26eb20dd6e6..65d5dc91d92ae7622d7a5824759798230f3a4806 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -17,7 +17,6 @@ - ExtensionAbility Component - [ExtensionAbility Component Overview](extensionability-overview.md) - [ServiceExtensionAbility](serviceextensionability.md) - - [DataShareExtensionAbility (for System Applications Only)](datashareextensionability.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [InputMethodExtensionAbility](inputmethodextentionability.md) @@ -37,9 +36,9 @@ - [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md) - Widget Event Development - [Widget Event Capability Overview](arkts-ui-widget-event-overview.md) + - [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) - [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md) - [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md) - - [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) - Widget Data Interaction - [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md) - [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md) @@ -62,8 +61,8 @@ - [Cross-Device Migration (for System Applications Only)](hop-cross-device-migration.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) - - IPC - - [Process Model](process-model-stage.md) + - Process Model + - [Process Model Overview](process-model-stage.md) - Common Events - [Introduction to Common Events](common-event-overview.md) - Common Event Subscription @@ -74,13 +73,13 @@ - [Publishing Common Events](common-event-publish.md) - [Removing Sticky Common Events](common-event-remove-sticky.md) - [Background Services](background-services.md) - - Inter-Thread Communication - - [Thread Model](thread-model-stage.md) + - Thread Model + - [Thread Model Overview](thread-model-stage.md) - [Using Emitter for Inter-Thread Communication](itc-with-emitter.md) - [Using Worker for Inter-Thread Communication](itc-with-worker.md) - Mission Management - [Mission Management Scenarios](mission-management-overview.md) - - [Mission Management and Launch Type](mission-management-launch-type.md) + - [Mission and Launch Type](mission-management-launch-type.md) - [Page Stack and MissionList](page-mission-stack.md) - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - [Application Configuration File](config-file-stage.md) @@ -120,12 +119,12 @@ - [Context](application-context-fa.md) - [Want](want-fa.md) - [Component Startup Rules](component-startup-rules-fa.md) - - IPC - - [Process Model](process-model-fa.md) + - Process Model + - [Process Model Overview](process-model-fa.md) - [Common Events](common-event-fa.md) - [Background Services](rpc.md) - - Inter-Thread Communication - - [Thread Model](thread-model-fa.md) + - Thread Model + - [Thread Model Overview](thread-model-fa.md) - [Inter-Thread Communication](itc-fa-overview.md) - [Mission Management](mission-management-fa.md) - [Application Configuration File](config-file-fa.md) diff --git a/en/application-dev/application-models/datashareextensionability.md b/en/application-dev/application-models/datashareextensionability.md deleted file mode 100644 index bea3de69c6d7ad375206fb1d53bcc36c2624989d..0000000000000000000000000000000000000000 --- a/en/application-dev/application-models/datashareextensionability.md +++ /dev/null @@ -1,4 +0,0 @@ -# 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). diff --git a/en/application-dev/application-models/mission-management-launch-type.md b/en/application-dev/application-models/mission-management-launch-type.md index 199de6eefead9fc056adf8d08c49f792a54a4a83..56a389cc52e093008491f75e01144bd7635b94eb 100644 --- a/en/application-dev/application-models/mission-management-launch-type.md +++ b/en/application-dev/application-models/mission-management-launch-type.md @@ -1,4 +1,4 @@ -# 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. @@ -11,13 +11,13 @@ The following describes how the mission list manager manages the UIAbility insta ![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 ![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 diff --git a/en/application-dev/application-models/mission-management-overview.md b/en/application-dev/application-models/mission-management-overview.md index ba55ebb136ebffca0294bf69013f2f2ab4392e7f..785a9f8291ea43e756ebed07843ceef23570160d 100644 --- a/en/application-dev/application-models/mission-management-overview.md +++ b/en/application-dev/application-models/mission-management-overview.md @@ -4,7 +4,7 @@ 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. @@ -30,42 +30,42 @@ 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. -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 import missionManager from '@ohos.app.ability.missionManager' let listener = { - // Listen for mission creation. - onMissionCreated: function (mission) { - console.info("--------onMissionCreated-------") - }, - // Listen for mission destruction. - onMissionDestroyed: function (mission) { - console.info("--------onMissionDestroyed-------") - }, - // Listen for mission snapshot changes. - onMissionSnapshotChanged: function (mission) { - console.info("--------onMissionSnapshotChanged-------") - }, - // Listen for switching the mission to the foreground. - onMissionMovedToFront: function (mission) { - console.info("--------onMissionMovedToFront-------") - }, - // Listen for mission icon changes. - onMissionIconUpdated: function (mission, icon) { - console.info("--------onMissionIconUpdated-------") - }, - // Listen for mission name changes. - onMissionLabelUpdated: function (mission) { - console.info("--------onMissionLabelUpdated-------") - }, - // Listen for mission closure events. - onMissionClosed: function (mission) { - console.info("--------onMissionClosed-------") - } + // Listen for mission creation. + onMissionCreated: function (mission) { + console.info("--------onMissionCreated-------") + }, + // Listen for mission destruction. + onMissionDestroyed: function (mission) { + console.info("--------onMissionDestroyed-------") + }, + // Listen for mission snapshot changes. + onMissionSnapshotChanged: function (mission) { + console.info("--------onMissionSnapshotChanged-------") + }, + // Listen for switching the mission to the foreground. + onMissionMovedToFront: function (mission) { + console.info("--------onMissionMovedToFront-------") + }, + // Listen for mission icon changes. + onMissionIconUpdated: function (mission, icon) { + console.info("--------onMissionIconUpdated-------") + }, + // Listen for mission name changes. + onMissionLabelUpdated: function (mission) { + console.info("--------onMissionLabelUpdated-------") + }, + // Listen for mission closure events. + onMissionClosed: function (mission) { + console.info("--------onMissionClosed-------") + } }; // 1. Register a mission change listener. @@ -73,56 +73,56 @@ You can use **missionManager** to manage missions, for example, listening for mi // 2. Obtain the latest 20 missions in the system. missionManager.getMissionInfos("", 20, (error, missions) => { - console.info("getMissionInfos is called, error.code = " + error.code); - console.info("size = " + missions.length); - console.info("missions = " + JSON.stringify(missions)); + console.info("getMissionInfos is called, error.code = " + error.code); + console.info("size = " + missions.length); + console.info("missions = " + JSON.stringify(missions)); }); // 3. Obtain the detailed information about a mission. let missionId = 11; // The mission ID 11 is only an example. let mission = missionManager.getMissionInfo("", missionId).catch(function (err) { - console.info(err); + console.info(err); }); // 4. Obtain the mission snapshot. missionManager.getMissionSnapShot("", missionId, (error, snapshot) => { - console.info("getMissionSnapShot is called, error.code = " + error.code); - console.info("bundleName = " + snapshot.ability.bundleName); + console.info("getMissionSnapShot is called, error.code = " + error.code); + console.info("bundleName = " + snapshot.ability.bundleName); }) // 5. Obtain the low-resolution mission snapshot. missionManager.getLowResolutionMissionSnapShot("", missionId, (error, snapshot) => { - console.info("getLowResolutionMissionSnapShot is called, error.code = " + error.code); - console.info("bundleName = " + snapshot.ability.bundleName); + console.info("getLowResolutionMissionSnapShot is called, error.code = " + error.code); + console.info("bundleName = " + snapshot.ability.bundleName); }) // 6. Lock or unlock the mission. missionManager.lockMission(missionId).then(() => { - console.info("lockMission is called "); + console.info("lockMission is called "); }); missionManager.unlockMission(missionId).then(() => { - console.info("unlockMission is called "); + console.info("unlockMission is called "); }); // 7. Switch the mission to the foreground. missionManager.moveMissionToFront(missionId).then(() => { - console.info("moveMissionToFront is called "); + console.info("moveMissionToFront is called "); }); // 8. Clear a single mission. missionManager.clearMission(missionId).then(() => { - console.info("clearMission is called "); + console.info("clearMission is called "); }); // 9. Clear all missions. missionManager.clearAllMissions().catch(function (err) { - console.info(err); + console.info(err); }); // 10. Deregister the mission change listener. missionManager.off('mission', listenerId, (error) => { - console.info("unregisterMissionListener"); + console.info("unregisterMissionListener"); }) ``` diff --git a/en/application-dev/application-models/process-model-fa.md b/en/application-dev/application-models/process-model-fa.md index 699643031121521fbf95d26a949df906fa175a18..ce4c9778d3bf678c7ecb8094477050a42eebb7d7 100644 --- a/en/application-dev/application-models/process-model-fa.md +++ b/en/application-dev/application-models/process-model-fa.md @@ -1,4 +1,4 @@ -# Process Model (FA Model) +# Process Model Overview (FA Model) The OpenHarmony process model is shown below. diff --git a/en/application-dev/application-models/process-model-stage.md b/en/application-dev/application-models/process-model-stage.md index 03da480722de124a1ede58da52e74cd48c5f23f0..cf758d94636773dfd190366d0e215de655902abd 100644 --- a/en/application-dev/application-models/process-model-stage.md +++ b/en/application-dev/application-models/process-model-stage.md @@ -1,4 +1,4 @@ -# Process Model (Stage Model) +# Process Model Overview (Stage Model) The OpenHarmony process model is shown below. diff --git a/en/application-dev/application-models/thread-model-fa.md b/en/application-dev/application-models/thread-model-fa.md index 75401be69cba994ac631b6da997fb6ce2ea35a2f..f6b335f8932ee1ebd5bb9bdf11db99ff354a1470 100644 --- a/en/application-dev/application-models/thread-model-fa.md +++ b/en/application-dev/application-models/thread-model-fa.md @@ -1,13 +1,11 @@ -# Thread Model (FA Model) - +# Thread Model Overview (FA Model) There are three types of threads in the FA model: - - Main thread - -Manages other threads. - + + Manages other threads. + - Ability thread - One ability thread for each ability. - Distributes input events. @@ -19,10 +17,8 @@ Manages other threads. Performs time-consuming operations - Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. - > **NOTE** > > The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread. diff --git a/en/application-dev/application-models/thread-model-stage.md b/en/application-dev/application-models/thread-model-stage.md index 4ca9fb3ed369f78cf12054c7b6da085b8640b1db..7343b9b619a5d68354e65e254a22a2b078ca44ee 100644 --- a/en/application-dev/application-models/thread-model-stage.md +++ b/en/application-dev/application-models/thread-model-stage.md @@ -1,4 +1,4 @@ -# Thread Model (Stage Model) +# Thread Model Overview (Stage Model) For an OpenHarmony application, each process has a main thread to provide the following functionalities: diff --git a/en/application-dev/file-management/share-app-file.md b/en/application-dev/file-management/share-app-file.md index d9ee1d90904f5cdb43cd1987a66b09668200bc81..c2f8f8d12f5ff056e043fb632cff9752c95256ce 100644 --- a/en/application-dev/file-management/share-app-file.md +++ b/en/application-dev/file-management/share-app-file.md @@ -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: - file://<bundleName>/<path>/\#networkid=<networkid> + file://<bundleName>/<path> - **file**: indicates a file URI. @@ -20,8 +20,6 @@ The file URIs are in the following format: - *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 Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path). diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index b12b546360875f9bb0d71e8840c8d8716bf62907..b942d5aa2a56cfc90c0496074d2ca7dda6d96b6f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -18,8 +18,6 @@ - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](js-apis-app-form-formExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.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 - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) - [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md) @@ -39,10 +37,12 @@ - [@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.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.formHost (FormHost)](js-apis-app-form-formHost.md) - [@ohos.app.form.formInfo (FormInfo)](js-apis-app-form-formInfo.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) - [@ohos.ability.dataUriUtils (DataUriUtils)](js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md) @@ -139,7 +139,11 @@ - [NotificationSlot](js-apis-inner-notification-notificationSlot.md) - [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md) - [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) -- Bundle Management + - 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 - [@ohos.bundle.appControl (appControl)](js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md) - [@ohos.bundle.bundleMonitor (bundleMonitor)](js-apis-bundleMonitor.md) @@ -148,6 +152,7 @@ - [@ohos.bundle.freeInstall (freeInstall)](js-apis-freeInstall.md) - [@ohos.bundle.installer (installer)](js-apis-installer.md) - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](js-apis-launcherBundleManager.md) + - [@ohos.bundle.overlay (overlay)](js-apis-overlay.md) - [@ohos.zlib (Zip)](js-apis-zlib.md) - bundleManager - [abilityInfo](js-apis-bundleManager-abilityInfo.md) @@ -155,18 +160,22 @@ - [AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md) - [bundleInfo](js-apis-bundleManager-bundleInfo.md) - [BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md) + - [BusinessAbilityInfo](js-apis-bundleManager-businessAbilityInfo.md) - [dispatchInfo](js-apis-bundleManager-dispatchInfo.md) - [elementName](js-apis-bundleManager-elementName.md) - [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - [metadata](js-apis-bundleManager-metadata.md) + - [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md) - [permissionDef](js-apis-bundleManager-permissionDef.md) - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) + - [SharedBundleInfo](js-apis-bundleManager-sharedBundleInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - UI Page - [@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.curves (Interpolation Calculation)](js-apis-curve.md) - [@ohos.matrix4 (Matrix Transformation)](js-apis-matrix4.md) @@ -264,7 +273,7 @@ - [@ohos.net.connection (Network Connection Management)](js-apis-net-connection.md) - [@ohos.net.ethernet (Ethernet Connection Management)](js-apis-net-ethernet.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.socket (Socket Connection)](js-apis-socket.md) - [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md) @@ -449,4 +458,4 @@ - [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - [shortcutInfo](js-apis-bundle-ShortcutInfo.md) - data/rdb - - [resultSet (Result Set)](js-apis-data-resultset.md) \ No newline at end of file + - [resultSet](js-apis-data-resultset.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-ability-ability.md b/en/application-dev/reference/apis/js-apis-ability-ability.md index 80610df7f925ac5a5d29744b48179488e8efc7f6..04313f3dfe02920b468647e7e717065760da46cc 100644 --- a/en/application-dev/reference/apis/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability'; | Name | Type | Description | | ----------- | -------------------- | ------------------------------------------------------------ | | 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**.| | DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | Level-2 module **DataAbilityResult**.| | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md index 54785d5ddb6a24dba26fff11e436f7a222ae96f2..9f59a5506ce0d330fc8da3179bc03978f06353f2 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -1,6 +1,6 @@ # @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** > diff --git a/en/application-dev/reference/apis/js-apis-app-ability-common.md b/en/application-dev/reference/apis/js-apis-app-ability-common.md index e18bc26fecc0695b771769df0abee199c4254ed9..dacf140793402f8d0512b7ac388fe7f7d65ee6b0 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-common.md @@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common'; | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.| | ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Level-2 module **ServiceExtensionContext**.| | 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**.| | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.| diff --git a/en/application-dev/reference/apis/js-apis-application-want.md b/en/application-dev/reference/apis/js-apis-application-want.md index 65f7fb03e38244ee92c9f94797fa3435072d2f60..1c61a91f7852898d4539ff7b8208d1bd9a9f63ac 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -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). diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index cef362d3702423395594a8ae52326b99e5aee191..0cea1311feadeba8b3dc9f7dd250894e57267c67 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -81,7 +81,7 @@ Unsubscribes from bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ---------------------------------------------------------- | | type| BundleChangedEvent| Yes | Type of the event to unsubscribe from. | -| callback | callback\| No | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| +| callback | callback\| No | Callback used for the unsubscription. By default, no value is passed, and all callbacks of the current event are unsubscribed from.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index 4b6512f5a040108714c782387e81393a9dab4df7..596d5a1666d0481558af56303d39811bfe4a32aa 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -232,7 +232,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ----------------------------------------- | -| 17700004 | The specified user ID is not found. | | 17700023 | The specified default app does not exist. | | 17700025 | The specified type is invalid. | @@ -415,7 +414,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ---------------------------------------------- | -| 17700004 | The specified user ID is not found. | | 17700025 | The specified type is invalid. | | 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 | ID| Error Message | | -------- | ----------------------------------- | -| 17700004 | The specified user ID is not found. | | 17700025 | The specified type is invalid. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md b/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md index 3fa93ccd105819ea71a709d861a71287ae1312cc..4942ff0b537c71b02ccdc20700dc31978f12c990 100644 --- a/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md +++ b/en/application-dev/reference/apis/js-apis-file-cloudsyncmanager.md @@ -3,10 +3,8 @@ The **cloudSyncManager** module provides APIs for changing the cloud and device service status and notifying the data changes. > **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 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 @@ -36,6 +34,15 @@ Changes the device-cloud file synchronization switch for an application. This AP | --------------------- | ---------------- | | Promise<void> | 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** ```js @@ -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.| | callback | AsyncCallback<void> | 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** ```js @@ -78,6 +94,7 @@ Changes the device-cloud file synchronization switch for an application. This AP } }); ``` + ## cloudSyncManager.notifyDataChange notifyDataChange(accountId: string, bundleName: string): Promise<void>; @@ -99,6 +116,15 @@ Notifies the cloud and device services of the application data change in the clo | --------------------- | ---------------- | | Promise<void> | 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** ```js @@ -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.| | callback | AsyncCallback<void> | 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** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-environment.md b/en/application-dev/reference/apis/js-apis-file-environment.md index c87c8465d7909f495baf6babad02e8e5b118424c..fb48f1a4103cb29bff4fb48e076ef2d87c717ab2 100644 --- a/en/application-dev/reference/apis/js-apis-file-environment.md +++ b/en/application-dev/reference/apis/js-apis-file-environment.md @@ -1,12 +1,11 @@ # @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** > > - 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 support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import @@ -28,6 +27,15 @@ Obtains the root directory of the storage. This API uses a promise to return the | --------------------- | ---------------- | | Promise<string> | 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** ```js @@ -52,6 +60,15 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac | -------- | --------------------------- | ---- | -------------------------------- | | callback | AsyncCallback<string> | 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** ```js @@ -68,7 +85,7 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac getUserDataDir():Promise<string> -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 @@ -76,7 +93,16 @@ Obtains the root directory of public files. This API uses a promise to return th | Type | Description | | --------------------- | ------------------ | -| Promise<string> | Promise returned with the root directory of public files.| +| Promise<string> | 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** @@ -92,7 +118,7 @@ Obtains the root directory of public files. This API uses a promise to return th getUserDataDir(callback:AsyncCallback<string>): 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 @@ -100,7 +126,16 @@ Obtains the root directory of public files. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of public files.| +| callback | AsyncCallback<string> | 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** diff --git a/en/application-dev/reference/apis/js-apis-file-fileuri.md b/en/application-dev/reference/apis/js-apis-file-fileuri.md index f8c6717fab58f9ca5eacac6ebc3963a6faae63fa..1aa5fe9cf08005980285bd04ae87763e58de8751 100644 --- a/en/application-dev/reference/apis/js-apis-file-fileuri.md +++ b/en/application-dev/reference/apis/js-apis-file-fileuri.md @@ -41,9 +41,9 @@ Obtains the URI of a file in synchronous mode. **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| string | File URI obtained.| + | Type | Description | + | ---------------------------- | ---------- | + | string | File URI obtained.| **Error codes** @@ -52,7 +52,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod | ---------------------------- | ---------- | | 401 | The input parameter is invalid | - **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md index 897d38e76b6614eaa3f4078cbbcb4b5f6ddc893b..d063029b27f7b8a705bf61ef757cf5f997c1995b 100644 --- a/en/application-dev/reference/apis/js-apis-file-fs.md +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -14,7 +14,7 @@ import fs from '@ohos.file.fs'; ## 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** @@ -29,7 +29,7 @@ export default class EntryAbility extends UIAbility { } ``` -**FA Model** +FA Model ```js import featureAbility from '@ohos.ability.featureAbility'; @@ -58,13 +58,13 @@ Obtains detailed file information. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| Promise<[Stat](#stat)> | Promise used to return the file information obtained.| + | Type | Description | + | ---------------------------- | ---------- | + | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| **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** @@ -94,7 +94,7 @@ Obtains detailed file information. This API uses an asynchronous callback to ret **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** @@ -120,17 +120,17 @@ Obtains detailed file information synchronously. | 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** -| Type | Description | -| ------------- | ---------- | -| [Stat](#stat) | File information obtained.| + | Type | Description | + | ------------- | ---------- | + | [Stat](#stat) | File information obtained.| **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** @@ -155,13 +155,13 @@ Checks whether a file exists. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<boolean> | Promise used to return the result. The value **true** means the file exists; the value **false** means the opposite.| **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** @@ -193,7 +193,7 @@ Checks whether a file exists. This API uses an asynchronous callback to return t **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** @@ -226,13 +226,13 @@ Synchronously checks whether a file exists. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| boolean | Returns **true** if the file exists; returns **false** otherwise.| + | Type | Description | + | ------------------- | ---------------------------- | + | boolean | Returns **true** if the file exists; returns **false** otherwise.| **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** @@ -259,19 +259,19 @@ Closes a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | file | [File](#file)\|number | Yes | File object or FD of the file to close.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -296,14 +296,14 @@ Closes a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------ | -| file | [File](#file)\|number | Yes | File object or FD of the file to close.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | file | [File](#file)\|number | Yes | File object or FD of the file to close.| + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is closed.| **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** @@ -329,13 +329,13 @@ Synchronously closes a file. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| file | [File](#file)\|number | Yes | File object or FD of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | file | [File](#file)\|number | Yes | File object or FD of the file to close.| **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** @@ -355,21 +355,21 @@ Copies a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------- | ---- | ---------------------------------------- | -| 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. | -| 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.
**0**: overwrite the file of the same name.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | 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. | + | 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.
**0**: overwrite the file with the same name.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -393,16 +393,16 @@ Copies a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------- | ---- | ---------------------------------------- | -| 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. | -| 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.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | -------------------------- | ---- | ---------------------------------------- | + | 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. | + | 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.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is copied. | **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** @@ -429,15 +429,15 @@ Synchronously copies a file. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------- | ---- | ---------------------------------------- | -| 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. | -| 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.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | 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. | + | 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.
**0**: overwrite the file with the same name and truncate the part that is not overwritten.| **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** @@ -447,6 +447,93 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem fs.copyFileSync(srcPath, dstPath); ``` +## fs.copyDir10+ + +copyDir(src: string, dest: string, mode?: number): Promise\ + +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**.
- **0**: Throw an exception if a file conflict occurs.
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.
- **1**: Forcibly overwrite the files with the same name in the destination directory.
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<void> | 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.copyDir10+ + +copyDir(src: string, dest: string, mode?: number, callback: AsyncCallback\): 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**.
- **0**: Throw an exception if a file conflict occurs.
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.
- **1**: Forcibly overwrite the files with the same name in the destination directory.
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<void> | 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 mkdir(path: string): Promise<void> @@ -463,13 +550,13 @@ Creates a directory. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -499,7 +586,7 @@ Creates a directory. This API uses an asynchronous callback to return the result **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** @@ -530,7 +617,7 @@ Synchronously creates a directory. **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** @@ -556,13 +643,13 @@ Opens a file. This API uses a promise to return the result. File uniform resourc **Return value** -| Type | Description | -| --------------------- | ----------- | -| Promise<[File](#file)> | Promise used to return the file object.| + | Type | Description | + | --------------------- | ----------- | + | Promise<[File](#file)> | Promise used to return the file object.| **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** @@ -593,7 +680,7 @@ Opens a file. This API uses an asynchronous callback to return the result. File **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** @@ -625,13 +712,13 @@ Synchronously opens a file. File URIs are supported. **Return value** -| Type | Description | -| ------ | ----------- | -| [File](#file) | File object opened.| + | Type | Description | + | ------ | ----------- | + | [File](#file) | File object opened.| **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** @@ -660,13 +747,13 @@ Reads data from a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<number> | Promise used to return the data read.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<number> | Promise used to return the data read.| **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** @@ -693,16 +780,16 @@ Reads data from a file. This API uses an asynchronous callback to return the res **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| -| callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is read asynchronously. | **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** @@ -731,21 +818,21 @@ Synchronously reads data from a file. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | -| options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.| **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data read.| + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| **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** @@ -773,13 +860,13 @@ Deletes a directory. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -809,7 +896,7 @@ Deletes a directory. This API uses an asynchronous callback to return the result **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** @@ -840,7 +927,7 @@ Synchronously deletes a directory. **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** @@ -865,13 +952,13 @@ Deletes a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -897,11 +984,11 @@ Deletes a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | +| callback | AsyncCallback<void> | Yes | Callback invoked immediately after the file is deleted. | **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** @@ -932,7 +1019,7 @@ Synchronously deletes a file. **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** @@ -952,21 +1039,21 @@ Writes data into a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| 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:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **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.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | 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:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **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** -| Type | Description | -| --------------------- | -------- | -| Promise<number> | Promise used to return the length of the data written.| + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Promise used to return the length of the data written.| **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** @@ -991,16 +1078,16 @@ Writes data into a file. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| 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:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **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<number> | Yes | Callback invoked when the data is written asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | 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:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **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<number> | Yes | Callback invoked when the data is written asynchronously. | **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** @@ -1027,21 +1114,21 @@ Synchronously writes data into a file. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| 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:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **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.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | 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:
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **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** -| Type | Description | -| ------ | -------- | -| number | Length of the data written in the file.| + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| **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** @@ -1070,13 +1157,13 @@ Truncates a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -1108,7 +1195,7 @@ Truncates a file. This API uses an asynchronous callback to return the result. **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** @@ -1141,7 +1228,7 @@ Synchronously truncates a file. **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** @@ -1168,13 +1255,13 @@ Reads the text content of a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| --------------------- | ---------- | -| Promise<string> | Promise used to return the content read.| + | Type | Description | + | --------------------- | ---------- | + | Promise<string> | Promise used to return the content read.| **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** @@ -1205,7 +1292,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu **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** @@ -1237,13 +1324,13 @@ Synchronously reads the text of a file. **Return value** -| Type | Description | -| ------ | -------------------- | -| string | Promise used to return the content of the file read.| + | Type | Description | + | ------ | -------------------- | + | string | Promise used to return the content of the file read.| **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** @@ -1269,13 +1356,13 @@ Obtains information about a symbolic link. This API uses a promise to return the **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| + | Type | Description | + | ---------------------------- | ---------- | + | Promise<[Stat](#stat)> | Promise used to return the symbolic link information obtained. For details, see **stat**.| **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** @@ -1305,7 +1392,7 @@ Obtains information about a symbolic link. This API uses an asynchronous callbac **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** @@ -1336,13 +1423,13 @@ Obtains information about a symbolic link synchronously. **Return value** -| Type | Description | -| ------------- | ---------- | -| [Stat](#stat) | File information obtained.| + | Type | Description | + | ------------- | ---------- | + | [Stat](#stat) | File information obtained.| **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** @@ -1368,13 +1455,13 @@ Renames a file or folder. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -1406,7 +1493,7 @@ Renames a file or folder. This API uses an asynchronous callback to return the r **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** @@ -1439,7 +1526,7 @@ Renames a file or folder synchronously. **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** @@ -1459,19 +1546,19 @@ Flushes data of a file to disk. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -1495,14 +1582,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------------- | -| fd | number | Yes | FD of the file. | -| Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | FD of the file. | + | Callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **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** @@ -1530,13 +1617,13 @@ Flushes data of a file to disk synchronously. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **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** @@ -1557,19 +1644,19 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -1594,14 +1681,14 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------- | -| fd | number | Yes | FD of the file. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ----------------- | + | fd | number | Yes | FD of the file. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **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** @@ -1628,13 +1715,13 @@ Synchronizes data in a file synchronously. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------------ | -| fd | number | Yes | FD of the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | FD of the file.| **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** @@ -1662,13 +1749,13 @@ Creates a symbolic link based on a file path. This API uses a promise to return **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -1700,7 +1787,7 @@ Creates a symbolic link based on a file path. This API uses an asynchronous call **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** @@ -1733,7 +1820,7 @@ Synchronously creates a symbolic link based on a file path. **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** @@ -1750,34 +1837,34 @@ listFile(path: string, options?: { filter?: Filter; }): Promise -Lists all files in a directory. This API uses a promise to return the result.
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.
This API supports recursive listing of all files (including files in subfolders) and file filtering. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| path | string | Yes | Application sandbox path of the folder.| -| options | Object | No | File filtering options. The files are not filtered by default.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| **options parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| -| 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.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | 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.| + | 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** -| Type | Description | -| --------------------- | ---------- | -| Promise<string[]> | Promise used to return the files names listed.| + | Type | Description | + | --------------------- | ---------- | + | Promise<string[]> | Promise used to return the files names listed.| **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** @@ -1809,27 +1896,27 @@ listFile(path: string, options?: { filter?: Filter; }, callback: AsyncCallback): void -Lists all files in a directory. This API uses an asynchronous callback to return the result.
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.
This API supports recursive listing of all files (including files in subfolders) and file filtering. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| path | string | Yes | Application sandbox path of the folder.| -| options | Object | No | File filtering options. The files are not filtered by default.| -| callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| + | callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | **options parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| -| 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.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | 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.| + | 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** -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** @@ -1864,32 +1951,32 @@ listFileSync(path: string, options?: { filter?: Filter; }): 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** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| path | string | Yes | Application sandbox path of the folder.| -| options | Object | No | File filtering options. The files are not filtered by default.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | path | string | Yes | Application sandbox path of the folder.| + | options | Object | No | File filtering options. The files are not filtered by default.| **options parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| -| 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.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | 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.| + | 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** -| Type | Description | -| --------------------- | ---------- | -| string[] | File names listed.| + | Type | Description | + | --------------------- | ---------- | + | string[] | File names listed.| **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** @@ -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\ -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 **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source folder.| -| dest | string | Yes | Application sandbox path of the destination folder.| -| mode | number | No | Mode for moving the folder. The default value is **0**.
- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.
- **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.
- **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.
- **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.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the directory to move.| + | dest | string | Yes | Application sandbox path of the destination directory.| + | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
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.
- **2**: Forcibly overwrite the conflicting files in the destination directory.
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.
- **3**: Forcibly overwrite the conflicting directory.
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** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** ```js - // move directory from srcPath to destPath/srcPath + // move directory from srcPath to destPath let srcPath = pathDir + "/srcDir/"; let destPath = pathDir + "/destDir/"; 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 moveDir(src: string, dest: string, mode?: number, callback: AsyncCallback\): 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 **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source folder.| -| dest | string | Yes | Application sandbox path of the destination folder.| -| mode | number | No | Mode for moving the folder. The default value is **0**.
- **0**: Throw an exception if the destination directory has folders of the same names with the source folder.
- **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.
- **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.
- **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.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the folder is moved. | + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source directory.| + | dest | string | Yes | Application sandbox path of the destination directory.| + | mode | number | No | Mode for moving the directory. The default value is **0**.
- **0**: Throw an exception if a directory conflict occurs.
Throw an exception if there is a directory with the same name in the destination directory.
- **1**: Throw an exception if a file conflict occurs.
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.
- **2**: Forcibly overwrite the conflicting files in the destination directory.
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.
- **3**: Forcibly overwrite the conflicting directory.
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<void> | Yes | Callback invoked when the directory is moved. | **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** ```js - // move directory from srcPath to destPath/srcPath + // move directory from srcPath to destPath let srcPath = pathDir + "/srcDir/"; let destPath = pathDir + "/destDir/"; fs.moveDir(srcPath, destPath, 1, (err) => { @@ -2008,21 +2095,21 @@ Moves a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source 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**.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| + | mode | number | No | Whether to overwrite the file with the same name in the destination directory.
The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.
The default value is **0**.| **Return value** -| Type | Description | -| ------------------- | ---------------------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------------------- | + | Promise<void> | Promise that returns no value.| **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** @@ -2046,16 +2133,16 @@ Moves a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source 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**.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| + | mode | number | No | Whether to overwrite the file with the same name in the destination directory.
The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.
The default value is **0**.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | **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** @@ -2081,15 +2168,15 @@ Moves a file synchronously. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| src | string | Yes | Application sandbox path of the source 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**.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | src | string | Yes | Application sandbox path of the source file.| + | dest | string | Yes | Application sandbox path of the destination file.| + | mode | number | No | Whether to overwrite the file with the same name in the destination directory.
The value **0** means to overwrite the file with the same name in the destination directory; the value **1** means to throw an exception.
The default value is **0**.| **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** @@ -2110,19 +2197,19 @@ Creates a temporary directory. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** -| Type | Description | -| --------------------- | ---------- | -| Promise<string> | Promise used to return the unique directory generated.| + | Type | Description | + | --------------------- | ---------- | + | Promise<string> | Promise used to return the unique directory generated.| **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** @@ -2144,14 +2231,14 @@ Creates a temporary directory. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| -| callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | --------------------------- | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | **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** @@ -2175,25 +2262,25 @@ Synchronously creates a temporary directory. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------------------- | -| prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| **Return value** -| Type | Description | -| ------ | ---------- | -| string | Unique path generated.| + | Type | Description | + | ------ | ---------- | + | string | Unique path generated.| **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** ```js let res = fs.mkdtempSync(pathDir + "/XXXXXX"); - ``` + ``` ## fs.createStream @@ -2212,13 +2299,13 @@ Creates a stream based on the file path. This API uses a promise to return the r **Return value** -| Type | Description | -| --------------------------------- | --------- | -| Promise<[Stream](#stream)> | Promise used to return the result.| + | Type | Description | + | --------------------------------- | --------- | + | Promise<[Stream](#stream)> | Promise used to return the result.| **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** @@ -2250,7 +2337,7 @@ Creates a stream based on the file path. This API uses an asynchronous callback **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** @@ -2282,13 +2369,13 @@ Synchronously creates a stream based on the file path. **Return value** -| Type | Description | -| ------------------ | --------- | -| [Stream](#stream) | Stream opened.| + | Type | Description | + | ------------------ | --------- | + | [Stream](#stream) | Stream opened.| **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** @@ -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<Stream> -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 **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **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).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **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** -| Type | Description | -| --------------------------------- | --------- | -| Promise<[Stream](#stream)> | Promise used to return the result.| + | Type | Description | + | --------------------------------- | --------- | + | Promise<[Stream](#stream)> | Promise used to return the result.| **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** @@ -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<Stream>): 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 **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **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<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **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<[Stream](#stream)> | Yes | Callback invoked when the stream is opened. | **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** @@ -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 -Synchronously opens a stream based on the FD. +Synchronously opens a stream based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| fd | number | Yes | FD of the file. | -| mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **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).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | FD of the file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **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.
- **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).
- **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** -| Type | Description | -| ------------------ | --------- | -| [Stream](#stream) | Stream opened.| + | Type | Description | + | ------------------ | --------- | + | [Stream](#stream) | Stream opened.| **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** @@ -2417,21 +2504,21 @@ Creates a **Watcher** object to observe file or directory changes. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| 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 (|)|.
- **0x1: IN_ACCESS**: A file is accessed.
- **0x2: IN_MODIFY**: The file content is modified.
- **0x4: IN_ATTRIB**: Metadata is changed.
- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.
- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.
- **0x20: IN_OPEN**: A file or directory is opened.
- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.
- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.
- **0x100: IN_CREATE**: A file or directory is created in the observed directory.
- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.
- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.
- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.
- **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. | + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | 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 (|)|.
- **0x1: IN_ACCESS**: A file is accessed.
- **0x2: IN_MODIFY**: The file content is modified.
- **0x4: IN_ATTRIB**: Metadata is changed.
- **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed.
- **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed.
- **0x20: IN_OPEN**: A file or directory is opened.
- **0x40: IN_MOVED_FROM**: A file in the observed directory is moved.
- **0x80: IN_MOVED_TO**: A file is moved to the observed directory.
- **0x100: IN_CREATE**: A file or directory is created in the observed directory.
- **0x200: IN_DELETE**: A file or directory is deleted from the observed directory.
- **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops.
- **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues.
- **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. | **Return value** -| Type | Description | -| ------------------ | --------- | -| [Watcher](#watcher10) | **Watcher** object created.| + | Type | Description | + | ------------------ | --------- | + | [Watcher](#watcher10) | **Watcher** object created.| **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** @@ -2463,10 +2550,10 @@ Called when an observed event occurs. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ---------------------------------------- | -| event | WatchEvent | Yes | Event for the callback to invoke. | - + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | event | WatchEvent | Yes | Event for the callback to invoke. | + ## WatchEvent10+ Defines the event to observe. @@ -2490,7 +2577,7 @@ Represents detailed file information. Before calling any API of the **Stat()** c ### Attributes | Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | ---------------------------------------- | +| ------ | ------ | ---- | ---- | ---------------------------------------- | | ino | number | Yes | No | File ID. Different files on the same device have different **ino**s.| | | mode | number | Yes | No | File permissions. The meaning of each bit is as follows:
- **0o400**: The owner has the read permission on a regular file or a directory entry.
- **0o200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o040**: The user group has the read permission on a regular file or a directory entry.
- **0o020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o004**: Other users have the permission to read a regular file or read a directory entry.
- **0o002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| | uid | number | Yes | No | ID of the file owner.| @@ -2510,13 +2597,13 @@ Checks whether this file is a block special file. A block special file supports **Return value** -| Type | Description | -| ------- | ---------------- | -| boolean | Whether the file is a block special file.| + | Type | Description | + | ------- | ---------------- | + | boolean | Whether the file is a block special file.| **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** @@ -2535,13 +2622,13 @@ Checks whether this file is a character special file. A character special file s **Return value** -| Type | Description | -| ------- | ----------------- | -| boolean | Whether the file is a character special file.| + | Type | Description | + | ------- | ----------------- | + | boolean | Whether the file is a character special file.| **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** @@ -2560,13 +2647,13 @@ Checks whether this file is a directory. **Return value** -| Type | Description | -| ------- | ------------- | -| boolean | Whether the file is a directory.| + | Type | Description | + | ------- | ------------- | + | boolean | Whether the file is a directory.| **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** @@ -2585,13 +2672,13 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int **Return value** -| Type | Description | -| ------- | --------------------- | -| boolean | Whether the file is a FIFO.| + | Type | Description | + | ------- | --------------------- | + | boolean | Whether the file is a FIFO.| **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** @@ -2610,13 +2697,13 @@ Checks whether this file is a regular file. **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the file is a regular file.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the file is a regular file.| **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** @@ -2635,13 +2722,13 @@ Checks whether this file is a socket. **Return value** -| Type | Description | -| ------- | -------------- | -| boolean | Whether the file is a socket.| + | Type | Description | + | ------- | -------------- | + | boolean | Whether the file is a socket.| **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** @@ -2660,13 +2747,13 @@ Checks whether this file is a symbolic link. **Return value** -| Type | Description | -| ------- | --------------- | -| boolean | Whether the file is a symbolic link.| + | Type | Description | + | ------- | --------------- | + | boolean | Whether the file is a symbolic link.| **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** @@ -2689,13 +2776,13 @@ Closes the stream. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ------------- | -| Promise<void> | Promise used to return the stream close result.| + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream close result.| **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** @@ -2719,13 +2806,13 @@ Closes the stream. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked immediately after the stream is closed.| **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** @@ -2736,7 +2823,7 @@ For details about error codes, see "Basic File I/O Error Codes" in [File Managem if (err) { console.info("close stream failed with error message: " + err.message + ", error code: " + err.code); } else { - console.info("close stream success"): + console.info("close stream success"); } }); ``` @@ -2751,7 +2838,7 @@ Synchronously closes the stream. **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** @@ -2771,13 +2858,13 @@ Flushes the stream. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ------------- | -| Promise<void> | Promise used to return the stream flushing result.| + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream flushing result.| **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** @@ -2801,13 +2888,13 @@ Flushes the stream. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | -------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | -------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| **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** @@ -2833,7 +2920,7 @@ Synchronously flushes the stream. **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** @@ -2853,20 +2940,20 @@ Writes data into the stream. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| 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:
- **length** (number): length of the data to write. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **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.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | 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:
- **length** (number): length of the data to write. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **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** -| Type | Description | -| --------------------- | -------- | -| Promise<number> | Promise used to return the length of the data written.| + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Promise used to return the length of the data written.| **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** @@ -2890,15 +2977,15 @@ Writes data into the stream. This API uses an asynchronous callback to return th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| 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:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **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<number> | Yes | Callback invoked when the data is written asynchronously. | + | Name | Type | Mandatory| Description | + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | 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:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **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<number> | Yes | Callback invoked when the data is written asynchronously. | **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** @@ -2926,20 +3013,20 @@ Synchronously writes data into the stream. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------------------- | -| 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:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **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.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | 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:
- **length** (number): length of the data to write. This parameter is optional. The default value is the buffer length.
- **offset** (number): start position to write the data in the file. This parameter is optional. By default, data is written from the current position.
- **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** -| Type | Description | -| ------ | -------- | -| number | Length of the data written in the file.| + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| **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** @@ -2959,20 +3046,20 @@ Reads data from the stream. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.| **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<number> | Promise used to return the data read.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<number> | Promise used to return the data read.| **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** @@ -2998,15 +3085,15 @@ Reads data from the stream. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **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<number> | Yes | Callback invoked when data is read asynchronously from the stream. | + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **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<number> | Yes | Callback invoked when data is read asynchronously from the stream. | **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** @@ -3034,20 +3121,20 @@ Synchronously reads data from the stream. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------- | ---- | ---------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer used to store the file read. | -| options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.
| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **length** (number): length of the data to read. This parameter is optional. The default value is the buffer length.
- **offset** (number): position of the data to read in the file. By default, data is read from the current position.
| **Return value** -| Type | Description | -| ------ | -------- | -| number | Length of the data read.| + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| **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** @@ -3079,19 +3166,19 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A **Parameters** -| 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. | + | 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. | **Return value** -| Type | Description | -| ---------------------------------- | ------ | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------------------- | ------ | + | Promise<void> | Promise that returns no value.| **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** @@ -3114,14 +3201,14 @@ Applies an exclusive lock or a shared lock on this file in blocking mode. This A **Parameters** -| 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. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the file is locked. | + | 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. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is locked. | **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** @@ -3146,13 +3233,13 @@ Applies an exclusive lock or a shared lock on this file in non-blocking mode. **Parameters** -| 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. | + | 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. | **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** @@ -3172,7 +3259,7 @@ Unlocks this file synchronously. **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** @@ -3199,7 +3286,7 @@ Starts listening. **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** @@ -3222,7 +3309,7 @@ Stops listening. **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** @@ -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. | | 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**. | + +## 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.| diff --git a/en/application-dev/reference/apis/js-apis-file-hash.md b/en/application-dev/reference/apis/js-apis-file-hash.md index eb9247ab3ccc6ee628fbd12e8a8a51413abbda01..87592b5b9f7ea94fc46dac6e72c25803d2c658d2 100644 --- a/en/application-dev/reference/apis/js-apis-file-hash.md +++ b/en/application-dev/reference/apis/js-apis-file-hash.md @@ -1,11 +1,10 @@ # @ohos.file.hash (File Hash Processing) -The **fileHash** module implements hash processing on files. +The **FileHash** module implements hash processing on files. > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> 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 @@ -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: -**Stage Model** +Stage Model ```js import UIAbility from '@ohos.app.ability.UIAbility'; @@ -30,7 +29,7 @@ export default class EntryAbility extends UIAbility { } ``` -**FA Model** +FA Model ```js 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 | --------------------- | -------------------------- | | Promise<string> | 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** ```js @@ -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. | | 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<string> | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| +| callback | AsyncCallback<string> | 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** + ```js let filePath = pathDir + "/test.txt"; Hash.hash(filePath, "sha256", (err, str) => { diff --git a/en/application-dev/reference/apis/js-apis-file-picker.md b/en/application-dev/reference/apis/js-apis-file-picker.md index c61b79455e006756aa65993b1b0ebdf7da9d7b70..f08294549c59a444bd8b7f3d8d72e34533c9d59b 100644 --- a/en/application-dev/reference/apis/js-apis-file-picker.md +++ b/en/application-dev/reference/apis/js-apis-file-picker.md @@ -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. ## Modules to Import + ```js import picker from '@ohos.file.picker'; ``` diff --git a/en/application-dev/reference/apis/js-apis-file-securityLabel.md b/en/application-dev/reference/apis/js-apis-file-securityLabel.md index c564516e66c0119dbec070c4a9eab744350d130f..d0005ee159065701ec3f6e483817a095b08c65b9 100644 --- a/en/application-dev/reference/apis/js-apis-file-securityLabel.md +++ b/en/application-dev/reference/apis/js-apis-file-securityLabel.md @@ -4,8 +4,7 @@ The **securityLabel** module provides APIs for managing data security levels of > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> 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 @@ -60,9 +59,24 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t **Return value** -| Type | Description | -| ------------------- | ---------------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ------------------- | ---------------- | + | Promise<void> | 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** @@ -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**.| | callback | AsyncCallback<void> | 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** ```js @@ -119,6 +148,21 @@ Sets a security label for a file in synchronous mode. | 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**.| +**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** ```js @@ -136,15 +180,30 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------- | -| path | string | Yes | Path of the target file.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------- | + | path | string | Yes | Path of the target file.| **Return value** -| Type | Description | -| --------------------- | ------------ | -| Promise<string> | Security label obtained.| + | Type | Description | + | --------------------- | ------------ | + | Promise<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** @@ -167,10 +226,25 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------------- | -| path | string | Yes | Path of the target file. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the security label obtained.| + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | -------------------------- | + | path | string | Yes | Path of the target file. | + | callback | AsyncCallback<string> | 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** @@ -184,6 +258,7 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb } }); ``` + ## securityLabel.getSecurityLabelSync getSecurityLabelSync(path:string):string @@ -204,6 +279,21 @@ Obtains the security label of a file in synchronous mode. | ------ | ------------ | | 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** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-statvfs.md b/en/application-dev/reference/apis/js-apis-file-statvfs.md index b7809c5f9f10fa9904ec0f64367ff025e7aafc94..34282138f7bddeadb0b9e3e2de45dc600c65c5ff 100644 --- a/en/application-dev/reference/apis/js-apis-file-statvfs.md +++ b/en/application-dev/reference/apis/js-apis-file-statvfs.md @@ -4,14 +4,14 @@ The **statfs** module provides APIs for obtaining file system information, inclu > **NOTE** > -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```js import statvfs from '@ohos.file.statvfs'; ``` + ## statvfs.getFreeSize getFreeSize(path:string):Promise<number> @@ -32,6 +32,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo | --------------------- | -------------- | | Promise<number> | 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** ```js @@ -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.| | callback | AsyncCallback<number> | 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** ```js @@ -91,6 +99,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m | --------------------- | ------------ | | Promise<number> | 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** ```js @@ -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.| | callback | AsyncCallback<number> | 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** ```js diff --git a/en/application-dev/reference/apis/js-apis-file-storage-statistics.md b/en/application-dev/reference/apis/js-apis-file-storage-statistics.md index 716e0da462bf4e59d0cd969deb561e0adc23a351..01ffbea245309d4d2babf3ae81ec64e998dfeb67 100644 --- a/en/application-dev/reference/apis/js-apis-file-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-file-storage-statistics.md @@ -4,8 +4,8 @@ The **storageStatistics** module provides APIs for obtaining storage space infor > **NOTE** > -> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import ```js @@ -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. - **Parameters** | Name | Type | Mandatory| Description| @@ -37,6 +36,19 @@ Obtains the total size (in bytes) of the specified volume in an external storage | --------------------- | ---------------- | | Promise<number> | 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** ```js @@ -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. - **Parameters** | Name | Type | Mandatory| Description | @@ -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. | | callback | AsyncCallback<number> | 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** ```js @@ -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. - **Parameters** | Name | Type | Mandatory| Description| @@ -103,6 +126,19 @@ Obtains the available space (in bytes) of the specified volume in an external st | --------------------- | ------------------ | | Promise<number> | 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** ```js @@ -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. - **Parameters** | Name | Type | Mandatory| Description | @@ -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. | | callback | AsyncCallback<number> | 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** ```js @@ -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. - **Parameters** | Name | Type | Mandatory| Description | @@ -170,6 +217,19 @@ Obtains the space (in bytes) of an application. This API uses a promise to retur | ------------------------------------------ | -------------------------- | | Promise<[Bundlestats](#bundlestats9)> | 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** ```js @@ -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. - **Parameters** | Name | Type | Mandatory| Description | @@ -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.| | callback | AsyncCallback<[Bundlestats](#bundlestats9)> | 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** ```js @@ -225,6 +297,16 @@ Obtains the space (in bytes) of this third-party application. This API uses a pr | ------------------------------------------ | -------------------------- | | Promise<[Bundlestats](#bundlestats9)> | 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** ```js @@ -246,6 +328,16 @@ Obtains the space (in bytes) of this third-party application. This API uses an a | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | callback | AsyncCallback<[BundleStats](#bundlestats9)> | 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** ```js @@ -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. | | dataSize | number | Yes| No| Total data size of the application, in bytes.| - ## storageStatistics.getTotalSize9+ getTotalSize(): Promise<number> @@ -284,6 +375,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses a promi | --------------------- | ------------------ | | Promise<number> | 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** ```js @@ -309,6 +412,18 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn | -------- | ------------------------------------ | ---- | ------------------------ | | callback | AsyncCallback<number> | 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** ```js @@ -318,7 +433,6 @@ Obtains the total size (in bytes) of the built-in storage. This API uses an asyn }); ``` - ## storageStatistics.getFreeSize9+ getFreeSize(): Promise<number> @@ -337,6 +451,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses a | --------------------- | ------------------ | | Promise<number> | 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** ```js @@ -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)); ``` - ## storageStatistics.getFreeSize9+ getFreeSize(callback: AsyncCallback<number>): void @@ -363,6 +488,18 @@ Obtains the available space (in bytes) of the built-in storage. This API uses an | -------- | ------------------------------------ | ---- | ------------------------- | | callback | AsyncCallback<number> | 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** ```js @@ -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. - **Return value** | Type | Description | | --------------------- | ---------------- | | Promise<number> | 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** ```js @@ -419,6 +567,18 @@ Obtains the system data space, in bytes. This API uses an asynchronous callback | ---------- | ------------------------------------ | ---- | -------------------------- | | callback | AsyncCallback<number> | 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** ```js @@ -446,6 +606,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses a promise | --------------------- | ---------------- | | Promise<[StorageStats](#storagestats9)> | 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** ```js @@ -474,6 +646,18 @@ Obtains the storage statistics (in bytes) of this user. This API uses an asynchr | ---------- | ------------------------------------ | ---- | -------------------------- | | callback | AsyncCallback<[StorageStats](#storagestats9)> | 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** ```js @@ -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)); }); ``` + +## storageStatistics.getUserStorageStats9+ + getUserStorageStats(userId: number): Promise<StorageStats> 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 | --------------------- | ---------------- | | Promise<[StorageStats](#storagestats9)> | 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** ```js @@ -534,6 +734,19 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a | userId | number | Yes | User ID.| | callback | AsyncCallback<[StorageStats](#storagestats9)> | 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** ```js @@ -544,7 +757,6 @@ Obtains the storage statistics (in bytes) of the specified user. This API uses a }); ``` - ## StorageStats9+ **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics diff --git a/en/application-dev/reference/apis/js-apis-file-volumemanager.md b/en/application-dev/reference/apis/js-apis-file-volumemanager.md index c2628ce063d93233af5ee6f6641a422e1a163c37..bec02a0f6780883260a9e152441558f58039d59b 100644 --- a/en/application-dev/reference/apis/js-apis-file-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-file-volumemanager.md @@ -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 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 @@ -26,9 +25,21 @@ Obtains information about all volumes of this external storage device. This API **Return value** -| Type | Description | -| ---------------------------------- | -------------------------- | -| Promise<[Volume](#volume)[]> | Promise used to return information about all available volumes.| + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)[]> | 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** @@ -52,9 +63,21 @@ Obtains information about all volumes of this external storage device. This API **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return information about all available volumes.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------------------- | ---- | ------------------------------------ | + | callback | AsyncCallback<[Volume](#volume)[]> | 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** @@ -65,7 +88,6 @@ Obtains information about all volumes of this external storage device. This API }); ``` - ## volumemanager.mount mount(volumeId: string): Promise<void> @@ -78,15 +100,31 @@ Asynchronously mounts a volume. This API uses a promise to return the result. Cu **Parameters** -| Name | Type | Mandatory| Description| -| -------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| **Return value** -| Type | Description | -| ---------------------- | ---------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------- | ---------- | + | Promise<void> | 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** @@ -111,10 +149,26 @@ Asynchronously mounts a volume. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| volumeId | string | Yes | Volume ID. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------- | ---- | -------------------- | + | volumeId | string | Yes | Volume ID. | + | callback | AsyncCallback<void> | 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** @@ -137,15 +191,31 @@ Asynchronously unmounts a volume. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description| -| -------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| **Return value** -| Type | Description | -| ---------------------- | ---------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------- | ---------- | + | Promise<void> | 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** @@ -170,10 +240,26 @@ Asynchronously unmounts a volume. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| volumeId | string | Yes | Volume ID. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------- | ---- | -------------------- | + | volumeId | string | Yes | Volume ID. | + | callback | AsyncCallback<void> | 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** @@ -196,15 +282,28 @@ Obtains information about a volume based on the universally unique identifier (U **Parameters** -| Name | Type | Mandatory| Description| -| -------- | ------ | ---- | ---- | -| uuid | string | Yes | UUID of the volume.| + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| **Return value** -| Type | Description | -| ---------------------------------- | -------------------------- | -| Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | 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** @@ -229,10 +328,23 @@ Obtains information about a volume based on the UUID. This API uses an asynchron **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | -------------------- | -| uuid | string | Yes | UUID of the volume. | -| callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------------------ | ---- | -------------------- | + | uuid | string | Yes | UUID of the volume. | + | callback | AsyncCallback<[Volume](#volume)> | 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** @@ -255,15 +367,28 @@ Obtains information about a volume based on the volume ID. This API uses a promi **Parameters** -| Name | Type | Mandatory | Description| -| -------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| + | Name | Type | Mandatory | Description| + | -------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| **Return value** -| Type | Description | -| ---------------------------------- | -------------------------- | -| Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | 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** @@ -288,10 +413,23 @@ Obtains information about a volume based on the volume ID. This API uses an asyn **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| volumeId | string | Yes | Volume ID. | -| callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained. | + | Name | Type | Mandatory| Description | + | -------- | ------------------------- | ---- | ----------------------------- | + | volumeId | string | Yes | Volume ID. | + | callback | AsyncCallback<[Volume](#volume)> | 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** @@ -314,16 +452,31 @@ Sets volume description. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description| -| --------- | ------ | ---- | ---- | -| uuid | string | Yes | UUID of the volume.| -| description | string | Yes | Volume description to set.| + | Name | Type | Mandatory| Description| + | --------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| + | description | string | Yes | Volume description to set.| **Return value** -| Type | Description | -| ---------------------- | -------------------------- | -| Promise<void> | Promise that returns no value. | + | Type | Description | + | ---------------------- | -------------------------- | + | Promise<void> | 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** @@ -349,11 +502,26 @@ Sets volume description. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ---------------- | -| uuid | string | Yes | UUID of the volume. | -| description | string | Yes | Volume description to set. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + | Name | Type | Mandatory| Description | + | ---------- | --------------------------------------- | ---- | ---------------- | + | uuid | string | Yes | UUID of the volume. | + | description | string | Yes | Volume description to set. | + | callback | AsyncCallback<void> | 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** @@ -377,16 +545,31 @@ Formats a volume. This API uses a promise to return the result. Currently, only **Parameters** -| Name | Type | Mandatory| Description| -| ----------- | ------ | ---- | ---- | -| volumeId | string | Yes | Volume ID.| -| fsType | string | Yes | File system type, which can be VFAT or exFAT.| + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| + | fsType | string | Yes | File system type, which can be VFAT or exFAT.| **Return value** -| Type | Description | -| ---------------------- | ---------- | -| Promise<void> | Promise that returns no value.| + | Type | Description | + | ---------------------- | ---------- | + | Promise<void> | 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** @@ -412,11 +595,26 @@ Formats a volume. This API uses an asynchronous callback to return the result. C **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------------- | -| volumeId | string | Yes | Volume ID. | -| fsType | string | Yes | File system type, which can be VFAT or exFAT.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + | Name | Type | Mandatory| Description | + | -------- | ------------------------- | ---- | ----------------------------- | + | volumeId | string | Yes | Volume ID. | + | fsType | string | Yes | File system type, which can be VFAT or exFAT.| + | callback | AsyncCallback<void> | 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** @@ -440,16 +638,29 @@ Partitions a disk. This API uses a promise to return the result. The system supp **Parameters** -| Name | Type | Mandatory| Description| -| ----------- | ------ | ---- | ---- | -| diskId | string | Yes | ID of the disk to partition.| -| type | number | Yes | Partition type. | + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | diskId | string | Yes | ID of the disk to partition.| + | type | number | Yes | Partition type. | **Return value** -| Type | Description | -| --------------------- | ----------------------- | -| Promise<void> | Promise used to return the result. | + | Type | Description | + | --------------------- | ----------------------- | + | Promise<void> | 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** @@ -475,11 +686,24 @@ Asynchronously partitions a disk. This API uses a callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ---------------- | -| diskId | string | Yes | ID of the disk to partition. | -| type | number | Yes | Partition type. | -| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + | Name | Type | Mandatory| Description | + | -------- | --------------------------------------- | ---- | ---------------- | + | diskId | string | Yes | ID of the disk to partition. | + | type | number | Yes | Partition type. | + | callback | AsyncCallback<void> | 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** diff --git a/en/application-dev/reference/apis/js-apis-fileShare.md b/en/application-dev/reference/apis/js-apis-fileShare.md index b99d2d029bc8f9abf2d6df865a0023140e8b25c0..3908fbf3996f1d87ccc0aa51efb326241c63080e 100644 --- a/en/application-dev/reference/apis/js-apis-fileShare.md +++ b/en/application-dev/reference/apis/js-apis-fileShare.md @@ -1,6 +1,6 @@ # @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** > @@ -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.| | 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).
**wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION**: permission to read the file.
**wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION**: permission to write the file.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Error codes** @@ -44,7 +44,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod | 401 | The input parameter is invalid | | 143000001 | IPC error | - **Example** ```js @@ -66,7 +65,6 @@ try { } ``` - ## fileShare.grantUriPermission grantUriPermission(uri: string, bundleName: string, mode: number): Promise<void> @@ -89,10 +87,9 @@ Grants permissions on a user file by the URI to an application. This API uses a **Return value** -| Type | Description | -| ---------------------------- | ---------- | -| Promise<void> | Promise that returns no value.| - + | Type | Description | + | ---------------------------- | ---------- | + | Promise<void> | Promise that returns no value.| **Error codes** @@ -105,7 +102,6 @@ For details about the error codes, see [File Management Error Codes](../errorcod | 401 | The input parameter is invalid | | 143000001 | IPC error | - **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 17f012a1af194cfbb0ebb93dc319a5691c3b5913..f2569456cc3430e9a72189e6a6fe5b3ce06ea8a3 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -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'. | | method | string | Yes | Name of the API to call. | | arg | string | Yes | Parameter to pass in. | -| extras | [PacMap](js-apis-inner-application-pacMap.md) | Yes | Key-value pair parameter. | -| callback | AsyncCallback\<[PacMap](js-apis-inner-application-pacMap.md)> | Yes| Callback used to return the result. | +| extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Yes | Key-value pair parameter. | +| callback | AsyncCallback\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | Yes| Callback used to return the result. | **Example** @@ -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'. | | method | string | Yes | Name of the API to call. | | 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** | 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** @@ -998,3 +998,13 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi }); ``` + +## PacMap + +[key: string]: number | string | boolean | Array\ | null; + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name| Type| Mandatory| Description| +| ------ | ------ | ------ | ------ | +| [key: string] | number \| string \| boolean \| Array\ \| null | Yes| Data stored in key-value pairs.| \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md index f8823b905ffe42199ec68fb57b052bd0af65e08e..7e6211f628986e02503c8c130614770b57656b74 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -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). diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index fc1fe9ef77b77ef0eaae619f5c0f630b39a6bb40..146996b85330695f1f3a9392a62fff3136e8387e 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -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. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 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** @@ -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. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 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** @@ -226,7 +234,7 @@ Installs a bundle. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | hapFilePaths | Array\ | 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** @@ -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. | | 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. | | 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** @@ -310,6 +322,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700004 | The specified user ID is not found. | | 17700020 | The specified bundle is pre-installed 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** @@ -367,6 +380,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700001 | The specified bundle name is not found. | | 17700020 | The specified bundle is pre-installed 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** @@ -407,7 +421,7 @@ Uninstalls a bundle. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | 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** @@ -422,9 +436,10 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | | 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. | | 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. | +| 17700045 | Failed to uninstall because enterprise device management disallow uninstall. | **Example** ```ts @@ -577,7 +592,7 @@ Rolls back a bundle to the initial installation state. This API uses a promise t | Name | Type | Mandatory| Description | | ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | | 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** @@ -755,12 +770,12 @@ Defines the parameters that need to be specified for bundle installation, uninst | 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.| -| installFlag | number | No | Installation flag. The value **0** means initial installation and **1** means overwrite installation.| -| isKeepData | boolean | No | Whether to retain the data directory during bundle uninstall.| -| hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. | -| crowdtestDeadline| number | No |End date of crowdtesting.| -| sharedBundleDirPaths10+ | Array\ | No|Paths of the shared bundle files.| +| 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. The default value is **0**.| +| isKeepData | boolean | No | Whether to retain the data directory during bundle uninstall. The default value is **false**.| +| hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. By default, no value is passed. | +| crowdtestDeadline| number | No |End date of crowdtesting. The default value is **-1**.| +| sharedBundleDirPaths10+ | Array\ | No|Paths of the shared bundle files. By default, no value is passed.| ## UninstallParam10+ @@ -773,4 +788,4 @@ Defines the parameters required for the uninstallation of a shared bundle. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | | 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.| diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 1075dd58f8f78bd7597903806a51d0c6ca5c2955..f7f5b2b9362ed875d776c645be7d596de2755bfd 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -767,7 +767,7 @@ Defines the **TagInfo** object, which provides information about the tag technol | uid9+ | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| | technology9+ | 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).| -| extrasData9+ | [PacMap](js-apis-inner-application-pacMap.md)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| | tagRfDiscId9+ | number | Yes| No| ID allocated when the tag is discovered.
**System API**: This is a system API.| | remoteTagService9+ | [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.
**System API**: This is a system API.| diff --git a/en/application-dev/reference/apis/js-apis-overlay.md b/en/application-dev/reference/apis/js-apis-overlay.md index 30c46bad02c997e7915e5595a6308446a2f5d722..f96550cca0b1c21388ec02bc0d2f63d9879b7b21 100644 --- a/en/application-dev/reference/apis/js-apis-overlay.md +++ b/en/application-dev/reference/apis/js-apis-overlay.md @@ -52,11 +52,11 @@ try { overlay.setOverlayEnabled(moduleName, isEnabled) .then(() => { console.info('setOverlayEnabled success'); - }).catch((error) => { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }).catch((err) => { + console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message); }); -} catch (error) { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message); } ``` @@ -92,15 +92,15 @@ var moduleName = "feature"; var isEnabled = false; try { - overlay.setOverlayEnabled(moduleName, isEnabled, (error, data) => { - if (error) { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + overlay.setOverlayEnabled(moduleName, isEnabled, (err, data) => { + if (err) { + console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message); return; } console.info('setOverlayEnabled success'); }); -} catch (error) { - console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + 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 ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; var isEnabled = false; try { overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled) .then((data) => { console.info('setOverlayEnabledByBundleName successfully'); - }).catch((error) => { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + }).catch((err) => { + console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message); }); -} catch (error) { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + 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 ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; var isEnabled = false; try { - overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (error, data) => { - if (error) { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); + overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (err, data) => { + if (err) { + console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message); return; } console.info('setOverlayEnabledByBundleName successfully'); }); -} catch (error) { - console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message); +} catch (err) { + 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 **Example** ```ts -var moduleName = "feature" +var moduleName = "feature"; (async() => { try { let overlayModuleInfo = await overlay.getOverlayModuleInfo(moduleName); console.log('overlayModuleInfo is ' + JSON.stringify(overlayModuleInfo)); } 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 | ID| Error Message | | ------ | -------------------------------------- | | 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. | **Example** ```ts -var moduleName = "feature" +var moduleName = "feature"; try { - overlay.getOverlayModuleInfo(moduleName, (error, data) => { - if (error) { - console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getOverlayModuleInfo(moduleName, (err, data) => { + if (err) { + console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + 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 **Example** ```ts -var targetModuleName = "feature" +var targetModuleName = "feature"; (async() => { try { let overlayModuleInfos = await overlay.getTargetOverlayModuleInfos(targetModuleName); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); } 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 **Example** ```ts -var targetModuleName = "feature" +var targetModuleName = "feature"; try { - overlay.getTargetOverlayModuleInfos(targetModuleName, (error, data) => { - if (error) { - console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getTargetOverlayModuleInfos(targetModuleName, (err, data) => { + if (err) { + console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + 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 | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | 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** @@ -424,14 +424,14 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; (async() => { try { let overlayModuleInfos = await overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); } 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 ```ts var bundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; try { - overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (error, data) => { - if (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (err, data) => { + if (err) { + console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + 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 | ID| Error Message | | ------ | -------------------------------------- | | 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. | -| 17700033 | The specified module is not an overlay module. | **Example** @@ -522,15 +520,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc var bundleName = "com.example.myapplication_xxxxx"; try { - overlay.getOverlayModuleInfoByBundleName(bundleName, (error, data) => { - if (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getOverlayModuleInfoByBundleName(bundleName, (err, data) => { + if (err) { + console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + 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 | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | 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** @@ -574,21 +572,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var targetBundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; (async() => { try { let overlayModuleInfos = await overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName); console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos)); } 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 -getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback\>): void; +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback<Array<OverlayModuleInfo>>): 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. @@ -621,24 +619,24 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts var targetBundleName = "com.example.myapplication_xxxxx"; -var moduleName = "feature" +var moduleName = "feature"; try { - overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (error, data) => { - if (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (err, data) => { + if (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` ## overlay.getTargetOverlayModuleInfosByBundleName -getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback\>): void; +getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback<Array<OverlayModuleInfo>>): 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. @@ -662,8 +660,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | | 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. | **Example** @@ -672,15 +668,15 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc var targetBundleName = "com.example.myapplication_xxxxx"; try { - overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (error, data) => { - if (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); + overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (err, data) => { + if (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); return; } console.log('overlayModuleInfo is ' + JSON.stringify(data)); }); -} catch (error) { - console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message); +} catch (err) { + console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index cf918a571c7121bdb5b9c5f51cb7a93ce782968d..3066cbef6e6a7c36bb6828c82eec5756ba54b532 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -51,10 +51,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -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<number>): void @@ -99,10 +99,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -125,7 +125,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er ``` -## backgroundTaskManager.getRemainingDelayTime:promise +## backgroundTaskManager.getRemainingDelayTime getRemainingDelayTime(requestId: number): Promise<number> @@ -155,10 +155,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -200,10 +200,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9900001 | Caller information verification failed for a transient task. | -| 9900002 | Transient task verification failed. | +| 9900001 | Caller information verification failed. | +| 9900002 | Background task verification failed. | **Example** @@ -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<void>): void @@ -246,9 +246,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -297,7 +297,7 @@ export default class EntryAbility extends UIAbility { }; ``` -## backgroundTaskManager.startBackgroundRunning:promise +## backgroundTaskManager.startBackgroundRunning startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> @@ -329,9 +329,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -376,7 +376,7 @@ export default class EntryAbility extends UIAbility { }; ``` -## backgroundTaskManager.stopBackgroundRunning:callback +## backgroundTaskManager.stopBackgroundRunning stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void @@ -399,9 +399,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -430,7 +430,7 @@ export default class EntryAbility extends UIAbility { }; ``` -## backgroundTaskManager.stopBackgroundRunning:promise +## backgroundTaskManager.stopBackgroundRunning stopBackgroundRunning(context: Context): Promise<void> @@ -460,9 +460,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 9800005 | Continuous task verification failed. | +| 9800005 | Background task verification failed. | | 9800006 | Notification verification failed. | | 9800007 | Task storage failed. | @@ -513,9 +513,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 18700001 | Caller information verification failed when applying for efficiency resources. | +| 18700001 | Caller information verification failed. | **Example** @@ -556,9 +556,9 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er | ---- | --------------------- | | 9800001 | Memory operation failed. | | 9800002 | Parcel operation failed. | -| 9800003 | IPC failed. | | +| 9800003 | Inner transact failed. | | | 9800004 | System service operation failed. | -| 18700001 | Caller information verification failed when applying for efficiency resources. | +| 18700001 | Caller information verification failed. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index 01fa04dc18f59bf47d49248681d5f46fba32d187..ae4decd405b23cfc87452846558533448a86563f 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -1549,10 +1549,10 @@ Provides the usage duration information of an application. | Name | Type | Mandatory | Description | | ------------------------ | ------ | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityPrevAccessTime | number | Yes | Last time when the application was used. | -| abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. | -| id | number | No | User ID.| +| bundleName | string | No | Bundle name of the application. | +| abilityPrevAccessTime | number | No | Last time when the application was used. | +| abilityInFgTotalTime | number | No | Total time that the application runs in the foreground. | +| id | number | Yes | User ID.| | abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.| | abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.| | fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.| @@ -1570,9 +1570,9 @@ Provides information about an application event. | Name | Type | Mandatory | Description | | --------------------- | ------ | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| eventId | number | Yes | Application event type. | -| eventOccurredTime | number | Yes | Timestamp when the application event occurs. | +| bundleName | string | No | Bundle name of the application. | +| eventId | number | No | Application event type. | +| eventOccurredTime | number | No | Timestamp when the application event occurs. | | appGroup | number | No | Usage priority group of the application.| | indexOfLink | string | No | Shortcut ID.| | nameOfClass | string | No | Class name.| @@ -1587,7 +1587,7 @@ Provides the usage duration information of an application. | Name | Type | Mandatory | Description | | ------------------------------ | ---------------------------------------- | ---- | -------------- | -| [key: string]: BundleStatsInfo | [key: string]: [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| +| [key: string] | [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| ## DeviceEventStats diff --git a/en/application-dev/reference/apis/js-apis-system-sensor.md b/en/application-dev/reference/apis/js-apis-system-sensor.md index ccf4be2ce7e5a660ef1622e90bce2c204634906e..945be8c89d79e74cb6bc284e90089edad1709b4e 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -89,7 +89,7 @@ Subscribes to data changes of the compass sensor. If this API is called multiple ```js sensor.subscribeCompass({ success: function(ret) { - console.log('get data direction:' + ret.direction); + console.log('Get data direction:' + ret.direction); }, fail: function(data, code) { 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 ```js sensor.subscribeProximity({ success: function(ret) { - console.log('get data distance:' + ret.distance); + console.log('Get data distance:' + ret.distance); }, fail: function(data, code) { 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 ```js sensor.subscribeLight({ success: function(ret) { - console.log('get data intensity:' + ret.intensity); + console.log('Get data intensity:' + ret.intensity); }, fail: function(data, code) { 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 ```js sensor.subscribeStepCounter({ success: function(ret) { - console.log('get step value:' + ret.steps); + console.log('Get step value:' + ret.steps); }, fail: function(data, code) { 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 ```js sensor.subscribeBarometer({ success: function(ret) { - console.log('get data value:' + ret.pressure); + console.log('Get data value:' + ret.pressure); }, fail: function(data, code) { 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 ```js sensor.subscribeHeartRate({ success: function(ret) { - console.log('get heartrate value:' + ret.heartRate); + console.log('Get heartrate value:' + ret.heartRate); }, fail: function(data, code) { 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 ```js sensor.subscribeOnBodyState({ 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) { console.log('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -409,7 +409,7 @@ Obtains the wearing state of a wearable device. ```js sensor.getOnBodyState({ success: function(ret) { - console.log('on body state: ' + ret.value); + console.log('On body state: ' + ret.value); }, fail: function(data, code) { console.log('Subscription failed. Code: ' + code + '; Data: ' + data); @@ -710,7 +710,7 @@ Defines the wearing state. | 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.| | complete | Function | No | Called when the API call is complete.| diff --git a/en/application-dev/reference/apis/js-apis-userFileManager.md b/en/application-dev/reference/apis/js-apis-userFileManager.md index c783b02f46c014a12ddba60432e1fe182cb93b42..a676fb1f3b86439ee314feceace04810bb5052da 100644 --- a/en/application-dev/reference/apis/js-apis-userFileManager.md +++ b/en/application-dev/reference/apis/js-apis-userFileManager.md @@ -4,8 +4,8 @@ The **userFileManager** module provides user data management capabilities, inclu > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs provided by this module are system APIs. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -49,11 +49,8 @@ let mgr = userFileManager.getUserFileMgr(context); getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; - Obtains image and video assets. This API uses an asynchronous callback to return the result. - - **System capability**: SystemCapability.FileManagement.UserFileManager.Core **Required permissions**: ohos.permission.READ_IMAGEVIDEO @@ -92,7 +89,6 @@ async function example() { } ``` - ### getPhotoAssets getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; @@ -141,6 +137,7 @@ async function example() { } } ``` + ### createPhotoAsset createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback<FileAsset>): void; @@ -261,7 +258,6 @@ async function example() { getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; - Obtains image and video albums. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -352,7 +348,6 @@ async function example() { getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; - Obtains the system album. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -424,7 +419,6 @@ async function example() { getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; - Obtains audio assets. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -469,7 +463,6 @@ async function example() { getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; - Obtains audio assets. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -515,6 +508,7 @@ async function example() { } } ``` + ### delete delete(uri: string, callback: AsyncCallback<void>): void; @@ -564,6 +558,7 @@ async function example() { }); } ``` + ### delete delete(uri: string): Promise<void>; @@ -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 - **System capability**: SystemCapability.FileManagement.UserFileManager.Core **Parameters** @@ -1923,6 +1917,7 @@ async function example() { }); } ``` + ### getPhotoAssets getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; @@ -2106,6 +2101,7 @@ async function example() { } ``` + ### getPhotoAssets getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; @@ -2147,6 +2143,7 @@ async function example() { console.info('fetchResult.count = ', count); } ``` + ### delete delete(uri: string, callback: AsyncCallback<void>): void; @@ -2190,6 +2187,7 @@ async function example() { }); } ``` + ### delete delete(uri: string): Promise<void>; @@ -2280,6 +2278,7 @@ async function example() { }); } ``` + ### recover recover(uri: string): Promise<void>; @@ -2335,9 +2334,9 @@ Enumerates the member types. | Name | Type| Readable | Writable | Description | | ----- | ---- | ---- | ---- | ---- | -| number | number | Yes| Yes| The member is a number.| -| string | string | Yes| Yes| The member is a string.| -| boolean | boolean | Yes| Yes| The member is a Boolean value.| +| number | number | Yes| Yes| The member is a number.| +| string | string | Yes| Yes| The member is a string.| +| boolean | boolean | Yes| Yes| The member is a Boolean value.| ## ChangeEvent @@ -2366,7 +2365,6 @@ Defines information about a registered device. | networkId | string | Yes | No | Network ID of the registered device.| | isOnline | boolean | Yes | No | Whether the registered device is online. | - ## FileType Enumerates media file types. @@ -2390,8 +2388,6 @@ Enumerates the system album types. | TYPE_FAVORITE | 0 | Favorites.| | TYPE_TRASH | 1 | Recycle bin.| - - ## AudioKey Defines the key information about an audio file. @@ -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_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 Defines the options for fetching media files. diff --git a/en/application-dev/reference/errorcodes/errorcode-bundle.md b/en/application-dev/reference/errorcodes/errorcode-bundle.md index f86c810b07e06b53797010d3b95080b5a7ca258d..8f7f78de3cd348f9cd0df3c393c4303bb18666bb 100644 --- a/en/application-dev/reference/errorcodes/errorcode-bundle.md +++ b/en/application-dev/reference/errorcodes/errorcode-bundle.md @@ -586,11 +586,11 @@ The version of shared bundle is dependent on other applications. **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** -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. -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. +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 uninstall, meaning that all versions of the shared library will be uninstalled, and the shared library is depended on by other applications. **Solution** 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. The shared library to uninstall does not exist. **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. **Solution** @@ -649,3 +649,118 @@ During application uninstall, the bundle name of an inter-application shared lib **Solution** 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. + +## 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**. diff --git a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md index 4f45c7d0057984677b67f5a494667462e4a3fedb..219f56460536de918a7bf5b631000e562ce2e507 100644 --- a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md +++ b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md @@ -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). -The error codes of the file management subsystem consist of the following:
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- 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 @@ -49,6 +54,7 @@ The process does not exist. **Solution** 1. Check whether the process is killed unexpectedly. + 2. Check whether the service related to the process has started. ### 13900004 System Call Interrupted @@ -64,6 +70,7 @@ The system call is interrupted by another thread. **Solution** 1. Check the multi-thread code logic. + 2. Invoke the system call again. ### 13900005 I/O Error @@ -161,7 +168,9 @@ Out of memory A memory overflow occurs. **Solution** + 1. Check the memory overhead. + 2. Control the memory overhead. ### 13900012 Permission Denied @@ -172,13 +181,14 @@ Permission denied **Possible Causes** - - 1. You do not have the permission to operate the file. + 2. The file sandbox path is incorrect. **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. ### 13900013 Incorrect Address @@ -375,7 +385,7 @@ Seek is used in pipe or FIFO. **Solution** -Check the use of seek. +Check the use of **seek()**. ### 13900027 Read-Only File System @@ -460,6 +470,7 @@ The specified directory is not empty. **Solution** 1. Check the directory. + 2. Ensure that the directory is empty. ### 13900033 Too Many Symbol Links @@ -516,7 +527,7 @@ The device pointed to by the file descriptor is not a character stream device. **Solution** -Check whether the file descriptor points to a stream device. +Check whether the file descriptor points to a stream. ### 13900037 No Data Available @@ -599,7 +610,9 @@ Unknown error The error is unidentified. **Solution** + 1. Call the API again. + 2. Restart the service. ## User Data Management Error Codes @@ -636,7 +649,7 @@ Use the obtained URI. **Error Message** -Invalid file extension +Invalid file name extension **Possible Causes** @@ -660,7 +673,7 @@ The file is moved to the Recycle Bin. Check whether the file is in the Recycle Bin. -## Spatial Statistics Error Codes +## Space Statistics Error Codes ### 13600001 IPC Failed @@ -680,7 +693,7 @@ Check whether the service is started. **Error Message** -Not supported file system +Not supported filesystem **Possible Causes** @@ -767,11 +780,15 @@ Check whether the specified directory or node exists. No such object **Possible Causes** + 1. The specified volume ID is incorrect. + 2. The specified bundle name is incorrect. **Solution** + 1. Check whether the specified volume exists. + 2. Check whether the specified bundle name exists. ### 13600009 Invalid User ID @@ -799,6 +816,7 @@ IPC error **Possible Causes** 1. The server service does not exist. + 2. The extension mechanism is abnormal. **Solution** @@ -854,7 +872,9 @@ Check the data returned by the server. Fail to register notification **Possible Causes** + 1. The server service does not exist. + 2. The extension mechanism is abnormal. **Solution** @@ -868,7 +888,9 @@ Check that the server service exists. Fail to remove notification **Possible Causes** + 1. The server service does not exist. + 2. The extension mechanism is abnormal. **Solution** @@ -896,47 +918,11 @@ Check whether the specified Notify agent is registered. Fail to notify agent **Possible Causes** + 1. The service does not exist. + 2. The extension mechanism is abnormal. **Solution** 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); -} -``` diff --git a/en/application-dev/website.md b/en/application-dev/website.md index c405c879240a79a9511ef8bd29ee8cb75a672c47..b0467126d53d2757607b249734ddc940bfd95150 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -1,4 +1,5 @@ # Application Development + - [Application Development Overview](application-dev-guide.md) - Quick Start - Getting Started @@ -19,6 +20,16 @@ - [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md) - [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md) - [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md) + - [Application 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 File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md) - [app.json5 Configuration File](quick-start/app-configuration-file.md) @@ -31,15 +42,40 @@ - [Resource Categories and Access](quick-start/resource-categories-and-access.md) - Learning ArkTS - [Getting Started with ArkTS](quick-start/arkts-get-started.md) - - ArkTS Syntax (Declarative UI) - - [Basic UI Description](quick-start/arkts-basic-ui-description.md) - - State Management - - [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md) - - [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md) - - [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md) - - [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md) - - [Rendering Control](quick-start/arkts-rendering-control.md) - - [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md) + - Basic Syntax + - [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 Overview](quick-start/arkts-state-management-overview.md) + - Component State Management + - [\@State: State Owned by Component](quick-start/arkts-state.md) + - [\@Prop: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md) + - [\@Link: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.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 - Application Models - Application Model Overview @@ -59,11 +95,35 @@ - ExtensionAbility Component - [ExtensionAbility Component Overview](application-models/extensionability-overview.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) + - [EnterpriseAdminExtensionAbility](application-models/enterprise-extensionAbility.md) - [InputMethodExtensionAbility](application-models/inputmethodextentionability.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) - [Context](application-models/application-context-stage.md) - Want @@ -78,22 +138,29 @@ - [Continuation Overview](application-models/inter-device-interaction-hop-overview.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) - - IPC - - [Process Model](application-models/process-model-stage.md) + - [Subscribing to System Environment Variable Changes](application-models/subscribe-system-environment-variable-changes.md) + - Process Model + - [Process Model Overview](application-models/process-model-stage.md) - Common Events - [Introduction to Common Events](application-models/common-event-overview.md) - - [Subscribing to Common Events](application-models/common-event-subscription.md) + - Common Event Subscription + - [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) - [Publishing Common Events](application-models/common-event-publish.md) - - [Unsubscribing from Common Events](application-models/common-event-unsubscription.md) + - [Removing Sticky Common Events](application-models/common-event-remove-sticky.md) - [Background Services](application-models/background-services.md) - - Inter-Thread Communication - - [Thread Model](application-models/thread-model-stage.md) + - Thread Model + - [Thread Model Overview](application-models/thread-model-stage.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) - Mission Management - [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) + - [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 Overview](application-models/fa-model-development-overview.md) - FA Mode Application Components @@ -129,14 +196,16 @@ - [Widget Development](application-models/widget-development-fa.md) - [Context](application-models/application-context-fa.md) - [Want](application-models/want-fa.md) - - IPC - - [Process Model](application-models/process-model-fa.md) + - [Component Startup Rules (FA Model)](application-models/component-startup-rules-fa.md) + - Process Model + - [Process Model Overview](application-models/process-model-fa.md) - [Common Events](application-models/common-event-fa.md) - [Background Services](application-models/rpc.md) - - Inter-Thread Communication - - [Thread Model](application-models/thread-model-fa.md) + - Thread Model + - [Thread Model Overview](application-models/thread-model-fa.md) - [Inter-Thread Communication](application-models/itc-fa-overview.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 - [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) @@ -172,32 +241,64 @@ - [Storage Switching](application-models/storage-switch.md) - UI Development - [ArkUI Overview](ui/arkui-overview.md) - - ArkTS-based Declarative Development Paradigm - - [Overview](ui/ui-ts-overview.md) - - [Declarative UI Development Guidelines](ui/ui-ts-developing-intro.md) - - Declarative UI Development Examples - - [Creating a Simple Page](ui/ui-ts-creating-simple-page.md) - - Building a Comprehensive Example - - [Building a Food Data Model](ui/ui-ts-building-data-model.md) - - [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md) - - [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md) - - [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md) - - Adding a Splash Screen Animation - - [Using the Drawing Feature](ui/ui-ts-drawing-feature.md) - - [Using the Animation Feature](ui/ui-ts-animation-feature.md) - - [Common Components](ui/ui-ts-components-intro.md) - - Common Layout Development - - Adaptive Layouts - - [Linear Layout](ui/ui-ts-layout-linear.md) - - [Statck Layout](ui/ui-ts-layout-stack.md) - - [Flex Layout](ui/ui-ts-layout-flex.md) - - [Grid Layout](ui/ui-ts-layout-grid.md) - - Responsive Layouts - - [Grid Layout](ui/ui-ts-layout-grid-container-new.md) - - [Media Query](ui/ui-ts-layout-mediaquery.md) - - [Custom Component Lifecycle Callbacks](ui/ui-ts-custom-component-lifecycle-callbacks.md) - - [Web Component Development](ui/ui-ts-components-web.md) - - [Recommendations for Improving Performance](ui/ui-ts-performance-improvement-recommendation.md) + - UI Development (ArkTS-based Declarative Development Paradigm) + - [UI Development (ArkTS-based Declarative Development Paradigm) Overview](ui/arkts-ui-development-overview.md) + - Layout Development + - [Layout Overview](ui/arkts-layout-development-overview.md) + - Building a Layout + - [Linear Layout](ui/arkts-layout-development-linear.md) + - [Stack Layout](ui/arkts-layout-development-stack-layout.md) + - [Flex Layout](ui/arkts-layout-development-flex-layout.md) + - [Relative Layout](ui/arkts-layout-development-relative-layout.md) + - [Responsive Grid Layout](ui/arkts-layout-development-grid-layout.md) + - [Media Query](ui/arkts-layout-development-media-query.md) + - [Creating a List](ui/arkts-layout-development-create-list.md) + - [Creating a Grid](ui/arkts-layout-development-create-grid.md) + - [Creating a Swiper](ui/arkts-layout-development-create-looping.md) + - [Improving Layout Performance](ui/arkts-layout-development-performance-boost.md) + - Adding a Component + - Adding a Common Component + - [Button](ui/arkts-common-components-button.md) + - [Radio Button](ui/arkts-common-components-radio-button.md) + - [Toggle](ui/arkts-common-components-switch.md) + - [Progress Indicator](ui/arkts-common-components-progress-indicator.md) + - [Text Display](ui/arkts-common-components-text-display.md) + - [Text Input](ui/arkts-common-components-text-input.md) + - [Custom Dialog Box](ui/arkts-common-components-custom-dialog.md) + - [Video Playback](ui/arkts-common-components-video-player.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 - [Overview](ui/ui-js-overview.md) - Framework @@ -270,10 +371,27 @@ - [Animation Effect](ui/ui-js-animate-dynamic-effects.md) - [Animation Frame](ui/ui-js-animate-frame.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 Overview](notification/notification-overview.md) - [Notification Subscription (for System Applications Only)](notification/notification-subscription.md) - [Enabling Notification](notification/notification-enable.md) + - [Notification Badge](notification/notification-badge.md) - Publishing a Notification - [Publishing a Basic Notification](notification/text-notification.md) - [Publishing a Progress Notification](notification/progress-bar-notification.md) @@ -287,30 +405,64 @@ - [WebGL Overview](webgl/webgl-overview.md) - [WebGL Development](webgl/webgl-guidelines.md) - Media + - [Media Application Overview](media/media-application-overview.md) - Audio and Video - - [Audio Overview](media/audio-overview.md) - - [Audio Rendering Development](media/audio-renderer.md) - - [Audio Stream Management Development](media/audio-stream-manager.md) - - [Audio Capture Development](media/audio-capturer.md) - - [OpenSL ES Audio Playback Development](media/opensles-playback.md) - - [OpenSL ES Audio Recording Development](media/opensles-capture.md) - - [Audio Interruption Mode Development](media/audio-interruptmode.md) - - [Volume Management Development](media/audio-volume-manager.md) - - [Audio Routing and Device Management Development](media/audio-routing-manager.md) - - [AVPlayer Development (Recommended)](media/avplayer-playback.md) - - [AVRecorder Development (Recommended)](media/avrecorder.md) - - [Audio Playback Development (To Be Deprecated Soon)](media/audio-playback.md) - - [Audio Recording Development (To Be Deprecated Soon)](media/audio-recorder.md) - - [Video Playback Development (To Be Deprecated Soon)](media/video-playback.md) - - [Video Recording Development (To Be Deprecated Soon)](media/video-recorder.md) - - AVSession + - [Audio and Video Overview](media/av-overview.md) + - [AVPlayer and AVRecorder](media/avplayer-avrecorder-overview.md) + - Audio Playback + - [Audio Playback Overview](media/audio-playback-overview.md) + - [Using AVPlayer for Audio Playback](media/using-avplayer-for-playback.md) + - [Using AudioRenderer for Audio Playback](media/using-audiorenderer-for-playback.md) + - [Using OpenSL ES for Audio Playback](media/using-opensl-es-for-playback.md) + - [Using TonePlayer for Audio Playback (for System Applications Only)](media/using-toneplayer-for-playback.md) + - [Audio Playback Concurrency Policy](media/audio-playback-concurrency.md) + - [Volume Management](media/volume-management.md) + - [Audio Playback Stream Management](media/audio-playback-stream-management.md) + - [Audio Output Device Management](media/audio-output-device-management.md) + - [Distributed Audio Playback (for System Applications Only)](media/distributed-audio-playback.md) + - Audio Recording + - [Audio Recording Overview](media/audio-recording-overview.md) + - [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 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 Development](media/image.md) - - Camera - - [Camera Development](media/camera.md) - - [Distributed Camera Development](media/remote-camera.md) + - [Image Overview](media/image-overview.md) + - [Image Decoding](media/image-decoding.md) + - Image Processing + - [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 - Access Control - [Access Control Overview](security/accesstoken-overview.md) @@ -323,6 +475,7 @@ - Key Management - [HUKS Overview](security/huks-overview.md) - [HUKS Development](security/huks-guidelines.md) + - [HUKS Cipher Algorithm Specifications](security/huks-appendix.md) - Crypto Framework - [Crypto Framework Overview](security/cryptoFramework-overview.md) - [Crypto Framework Development](security/cryptoFramework-guidelines.md) @@ -339,10 +492,10 @@ - [HTTP Data Request](connectivity/http-request.md) - [WebSocket Connection](connectivity/websocket-connection.md) - [Socket Connection](connectivity/socket-connection.md) - - [Network Policy Management](connectivity/net-policy-management.md) - [Network Sharing](connectivity/net-sharing.md) - [Ethernet Connection](connectivity/net-ethernet.md) - [Network Connection Management](connectivity/net-connection-manager.md) + - [MDNS Management](connectivity/net-mdns.md) - IPC & RPC - [IPC & RPC Overview](connectivity/ipc-rpc-overview.md) - [IPC & RPC Development](connectivity/ipc-rpc-development-guideline.md) @@ -352,30 +505,48 @@ - [Call Service Development](telephony/telephony-call.md) - [SMS Service Development](telephony/telephony-sms.md) - Data Management - - Distributed Data Service - - [Distributed Data Service Overview](database/database-mdds-overview.md) - - [Distributed Data Service Development](database/database-mdds-guidelines.md) - - Relational Database - - [RDB Overview](database/database-relational-overview.md) - - [RDB Development](database/database-relational-guidelines.md) - - Preferences - - [Preferences Overview](database/database-preference-overview.md) - - [Preferences Development](database/database-preference-guidelines.md) - - Distributed Data Object - - [Distributed Data Object Overview](database/database-distributedobject-overview.md) - - [Distributed Data Object Development](database/database-distributedobject-guidelines.md) - - Data Share - - [DataShare Overview](database/database-datashare-overview.md) - - [DataShare Development](database/database-datashare-guidelines.md) + - [Data Management Overview](database/data-mgmt-overview.md) + - Application Data Persistence + - [Overview of Application Data Persistence](database/app-data-persistence-overview.md) + - [Persisting Preferences Data](database/data-persistence-by-preferences.md) + - [Persisting KV Store Data](database/data-persistence-by-kv-store.md) + - [Persisting RDB Store Data](database/data-persistence-by-rdb-store.md) + - Distributed Application Data Synchronization + - [Distributed Application Data Synchronization Overview](database/sync-app-data-across-devices-overview.md) + - [Cross-Device Synchronization of KV Stores](database/data-sync-of-kv-store.md) + - [Cross-Device Synchronization of RDB Stores](database/data-sync-of-rdb-store.md) + - [Cross-Device Synchronization of Distributed Data Objects](database/data-sync-of-distributed-data-object.md) + - Data Reliability and Security + - [Data Reliability and Security Overview](database/data-reliability-security-overview.md) + - [Database Backup and Restoration](database/data-backup-and-restore.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 - - MediaLibrary - - [MediaLibrary Development Overview](file-management/medialibrary-overview.md) - - [Media Asset Management](file-management/medialibrary-resource-guidelines.md) - - [File Path Management](file-management/medialibrary-filepath-guidelines.md) - - [Album Management](file-management/medialibrary-album-guidelines.md) - - File Access Framework - - [File Access Framework Overview](file-management/file-access-framework-overview.md) - - [FilePicker Guide](file-management/filepicker-guidelines.md) + - [File Management Overview](file-management/file-management-overview.md) + - Application File + - [Application File Overview](file-management/app-file-overview.md) + - [Application Sandbox Directory](file-management/app-sandbox-directory.md) + - Application File Access and Management + - [Accessing Application Files](file-management/app-file-access.md) + - [Uploading and Downloading Application Files](file-management/app-file-upload-download.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 - [Background Task Management Overview](task-management/background-task-overview.md) @@ -414,9 +585,13 @@ - [Development of Application Event Logging](dfx/hiappevent-guidelines.md) - [Development of Performance Tracing](dfx/hitracemeter-guidelines.md) - [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md) + - [HiLog Development (Native)](dfx/hilog-guidelines.md) - Error Management - [Development of Error Manager](dfx/errormanager-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 Overview](internationalization/international-overview.md) - [Internationalization Development (intl)](internationalization/intl-guidelines.md) @@ -441,8 +616,10 @@ - Packing and Unpacking Tools - [Packing Tools](tools/packing-tool.md) - [Unpacking Tools](tools/unpacking-tool.md) - - [Common Event Manager](tools/anm-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 - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs) @@ -462,6 +639,7 @@ - [Mouse Event](reference/arkui-ts/ts-universal-mouse-key.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) + - [Custom Keyboard Shortcuts](reference/arkui-ts/ts-universal-events-keyboardshortcut.md) - Universal Attributes - [Size](reference/arkui-ts/ts-universal-attributes-size.md) - [Location](reference/arkui-ts/ts-universal-attributes-location.md) @@ -478,7 +656,6 @@ - [Transformation](reference/arkui-ts/ts-universal-attributes-transformation.md) - [Image Effect Configuration](reference/arkui-ts/ts-universal-attributes-image-effect.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) - [Gradient Color](reference/arkui-ts/ts-universal-attributes-gradient-color.md) - [Popup Control](reference/arkui-ts/ts-universal-attributes-popup.md) @@ -492,6 +669,11 @@ - [Hit Test Control](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md) - [Background Blur](reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.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 Binding Methods](reference/arkui-ts/ts-gesture-settings.md) - Basic Gestures @@ -503,6 +685,7 @@ - [SwipeGesture](reference/arkui-ts/ts-basic-gestures-swipegesture.md) - [Combined Gestures](reference/arkui-ts/ts-combined-gestures.md) - Basic Components + - [AlphabetIndexer](reference/arkui-ts/ts-container-alphabet-indexer.md) - [Blank](reference/arkui-ts/ts-basic-components-blank.md) - [Button](reference/arkui-ts/ts-basic-components-button.md) - [Checkbox](reference/arkui-ts/ts-basic-components-checkbox.md) @@ -514,6 +697,7 @@ - [Gauge](reference/arkui-ts/ts-basic-components-gauge.md) - [Image](reference/arkui-ts/ts-basic-components-image.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) - [Marquee](reference/arkui-ts/ts-basic-components-marquee.md) - [Menu](reference/arkui-ts/ts-basic-components-menu.md) @@ -549,7 +733,6 @@ - [XComponent](reference/arkui-ts/ts-basic-components-xcomponent.md) - Container Components - [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) - [Column](reference/arkui-ts/ts-container-column.md) - [ColumnSplit](reference/arkui-ts/ts-container-columnsplit.md) @@ -613,6 +796,7 @@ - [Time Picker Dialog Box](reference/arkui-ts/ts-methods-timepicker-dialog.md) - [Text Picker Dialog Box](reference/arkui-ts/ts-methods-textpicker-dialog.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) - [Pixel Units](reference/arkui-ts/ts-pixel-units.md) - [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md) @@ -722,39 +906,39 @@ - [Data Type Attributes](reference/arkui-js/js-appendix-types.md) - JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite) - Framework Overview - - [File Organization](js-framework-file.md) - - ["js" Tag](js-framework-js-tag.md) - - [app.js](js-framework-js-file.md) + - [File Organization](reference/arkui-js-lite/js-framework-file.md) + - ["js" Tag](reference/arkui-js-lite/js-framework-js-tag.md) + - [app.js](reference/arkui-js-lite/js-framework-js-file.md) - Syntax - - [HML](js-framework-syntax-hml.md) - - [CSS](js-framework-syntax-css.md) - - [JavaScript](js-framework-syntax-js.md) + - [HML](reference/arkui-js-lite/js-framework-syntax-hml.md) + - [CSS](reference/arkui-js-lite/js-framework-syntax-css.md) + - [JavaScript](reference/arkui-js-lite/js-framework-syntax-js.md) - Universal Component Information - - [Universal Events](js-common-events.md) - - [Universal Attributes](js-common-attributes.md) - - [Universal Styles](js-common-styles.md) - - [Animation Styles](js-components-common-animation.md) + - [Universal Events](reference/arkui-js-lite/js-common-events.md) + - [Universal Attributes](reference/arkui-js-lite/js-common-attributes.md) + - [Universal Styles](reference/arkui-js-lite/js-common-styles.md) + - [Animation Styles](reference/arkui-js-lite/js-components-common-animation.md) - Container Components - - [div](js-components-container-div.md) - - [list](js-components-container-list.md) - - [list-item](js-components-container-list-item.md) - - [stack](js-components-container-stack.md) - - [swiper](js-components-container-swiper.md) + - [div](reference/arkui-js-lite/js-components-container-div.md) + - [list](reference/arkui-js-lite/js-components-container-list.md) + - [list-item](reference/arkui-js-lite/js-components-container-list-item.md) + - [stack](reference/arkui-js-lite/js-components-container-stack.md) + - [swiper](reference/arkui-js-lite/js-components-container-swiper.md) - Basic Components - - [chart](js-components-basic-chart.md) - - [image](js-components-basic-image.md) - - [image-animator](js-components-basic-image-animator.md) - - [input](js-components-basic-input.md) - - [marquee](js-components-basic-marquee.md) - - [picker-view](js-components-basic-picker-view.md) - - [progress](js-components-basic-progress.md) - - [qrcode](js-components-basic-qrcode.md) - - [slider](js-components-basic-slider.md) - - [switch](js-components-basic-switch.md) - - [text](js-components-basic-text.md) + - [chart](reference/arkui-js-lite/js-components-basic-chart.md) + - [image](reference/arkui-js-lite/js-components-basic-image.md) + - [image-animator](reference/arkui-js-lite/js-components-basic-image-animator.md) + - [input](reference/arkui-js-lite/js-components-basic-input.md) + - [marquee](reference/arkui-js-lite/js-components-basic-marquee.md) + - [picker-view](reference/arkui-js-lite/js-components-basic-picker-view.md) + - [progress](reference/arkui-js-lite/js-components-basic-progress.md) + - [qrcode](reference/arkui-js-lite/js-components-basic-qrcode.md) + - [slider](reference/arkui-js-lite/js-components-basic-slider.md) + - [switch](reference/arkui-js-lite/js-components-basic-switch.md) + - [text](reference/arkui-js-lite/js-components-basic-text.md) - Canvas Components - - [canvas](js-components-canvas-canvas.md) - - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) + - [canvas](reference/arkui-js-lite/js-components-canvas-canvas.md) + - [CanvasRenderingContext2D](reference/arkui-js-lite/js-components-canvas-canvasrenderingcontext2d.md) - JS Service Widget UI Components - JS Service Widget UI Framework - [File Organization](reference/js-service-widget-ui/js-service-widget-file.md) @@ -812,8 +996,6 @@ - [@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.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 - [@ohos.ability.ability (Ability)](reference/apis/js-apis-ability-ability.md) - [@ohos.ability.featureAbility (FeatureAbility)](reference/apis/js-apis-ability-featureAbility.md) @@ -825,16 +1007,20 @@ - [@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.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.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.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.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.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.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) - [@ohos.ability.dataUriUtils (DataUriUtils)](reference/apis/js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode (ErrorCode)](reference/apis/js-apis-ability-errorCode.md) @@ -906,10 +1092,12 @@ - [continuationExtraParams](reference/apis/js-apis-continuation-continuationExtraParams.md) - [continuationResult](reference/apis/js-apis-continuation-continuationResult.md) - Common Event and Notification + - [System Common Events](reference/apis/commonEventManager-definitions.md) - [@ohos.commonEventManager (Common Event) (Recommended)](reference/apis/js-apis-commonEventManager.md) - [@ohos.events.emitter (Emitter)](reference/apis/js-apis-emitter.md) - [@ohos.notificationManager (NotificationManager) (Recommended)](reference/apis/js-apis-notificationManager.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.notification (Notification) (To Be Deprecated Soon)](reference/apis/js-apis-notification.md) - application @@ -928,6 +1116,10 @@ - [NotificationSlot](reference/apis/js-apis-inner-notification-notificationSlot.md) - [NotificationTemplate](reference/apis/js-apis-inner-notification-notificationTemplate.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 - [@ohos.bundle.appControl(appControl)](reference/apis/js-apis-appControl.md) - [@ohos.bundle.bundleManager (bundleManager)](reference/apis/js-apis-bundleManager.md) @@ -937,29 +1129,38 @@ - [@ohos.bundle.freeInstall (freeInstall)](reference/apis/js-apis-freeInstall.md) - [@ohos.bundle.installer (installer)](reference/apis/js-apis-installer.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) - bundleManager - [abilityInfo](reference/apis/js-apis-bundleManager-abilityInfo.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) - [BundlePackInfo](reference/apis/js-apis-bundleManager-BundlePackInfo.md) + - [BusinessAbilityInfo](reference/apis/js-apis-bundleManager-businessAbilityInfo.md) - [dispatchInfo](reference/apis/js-apis-bundleManager-dispatchInfo.md) - [elementName](reference/apis/js-apis-bundleManager-elementName.md) - [extensionAbilityInfo](reference/apis/js-apis-bundleManager-extensionAbilityInfo.md) - [hapModuleInfo](reference/apis/js-apis-bundleManager-hapModuleInfo.md) - [launcherAbilityInfo](reference/apis/js-apis-bundleManager-launcherAbilityInfo.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) - [remoteAbilityInfo](reference/apis/js-apis-bundleManager-remoteAbilityInfo.md) + - [SharedBundleInfo](reference/apis/js-apis-bundleManager-sharedBundleInfo.md) - [shortcutInfo](reference/apis/js-apis-bundleManager-shortcutInfo.md) - UI Page - [@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.matrix4 (Matrix Transformation)](reference/apis/js-apis-matrix4.md) - [@ohos.mediaquery (Media Query)](reference/apis/js-apis-mediaquery.md) - [@ohos.pluginComponent (PluginComponentManager)](reference/apis/js-apis-plugincomponent.md) - [@ohos.promptAction (Prompt)](reference/apis/js-apis-promptAction.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 - [@ohos.animation.windowAnimationManager (Window Animation Management)](reference/apis/js-apis-windowAnimationManager.md) - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](reference/apis/js-apis-application-windowExtensionAbility.md) @@ -989,6 +1190,8 @@ - [@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.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) + - application + - [WorkSchedulerExtensionContext](reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md) - Security - [@ohos.abilityAccessCtrl (Ability Access Control)](reference/apis/js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (Privacy Management)](reference/apis/js-apis-privacyManager.md) @@ -997,7 +1200,6 @@ - [@ohos.security.huks (HUKS)](reference/apis/js-apis-huks.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) - - [@system.cipher (Cipher Algorithm)](reference/apis/js-apis-system-cipher.md) - security - [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md) - Data Management @@ -1010,20 +1212,22 @@ - [@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.ValuesBucket](reference/apis/js-apis-data-valuesBucket.md) - - data/rdb - - [resultSet (Result Set)](reference/apis/js-apis-data-resultset.md) - 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.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.fileuri (File URI)](reference/apis/js-apis-file-fileuri.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.picker (File Picker)](reference/apis/js-apis-file-picker.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.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.storageStatistics (Application Storage Statistics)](reference/apis/js-apis-file-storage-statistics.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.multimedia.medialibrary (Media Library Management)](reference/apis/js-apis-medialibrary.md) + - [@ohos.fileShare (File Sharing)](reference/apis/js-apis-fileShare.md) - Telephony Service - [@ohos.contact (Contacts)](reference/apis/js-apis-contact.md) - [@ohos.telephony.call (Call)](reference/apis/js-apis-call.md) @@ -1036,12 +1240,14 @@ - [@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.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.socket (Socket Connection)](reference/apis/js-apis-socket.md) - [@ohos.net.webSocket (WebSocket Connection)](reference/apis/js-apis-webSocket.md) - [@ohos.request (Upload and Download)](reference/apis/js-apis-request.md) - Connectivity - [@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.nfc.cardEmulation (Standard NFC Card Emulation)](reference/apis/js-apis-cardEmulation.md) - [@ohos.nfc.controller (Standard NFC)](reference/apis/js-apis-nfcController.md) @@ -1087,6 +1293,7 @@ - [@ohos.batteryInfo (Battery Information)](reference/apis/js-apis-battery-info.md) - [@ohos.batteryStatistics (Battery Statistics)](reference/apis/js-apis-batteryStatistics.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.distributedHardware.deviceManager (Device Management)](reference/apis/js-apis-device-manager.md) - [@ohos.geoLocationManager (Geolocation Manager)](reference/apis/js-apis-geoLocationManager.md) @@ -1118,9 +1325,15 @@ - [@ohos.account.osAccount (OS Account Management)](reference/apis/js-apis-osAccount.md) - Customization - [@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.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.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 - [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md) - [@ohos.convertxml (XML-to-JavaScript Conversion)](reference/apis/js-apis-convertxml.md) @@ -1162,17 +1375,18 @@ - [@ohos.fileio (File Management)](reference/apis/js-apis-fileio.md) - [@ohos.geolocation (Geolocation)](reference/apis/js-apis-geolocation.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.reminderAgent (Reminder Agent)](reference/apis/js-apis-reminderAgent.md) - [@ohos.statfs (statfs)](reference/apis/js-apis-statfs.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.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.battery (Battery Information)](reference/apis/js-apis-system-battery.md) - [@system.bluetooth (Bluetooth)](reference/apis/js-apis-system-bluetooth.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.device (Device Information)](reference/apis/js-apis-system-device.md) - [@system.fetch (Data Request)](reference/apis/js-apis-system-fetch.md) @@ -1202,6 +1416,8 @@ - [PermissionDef](reference/apis/js-apis-bundle-PermissionDef.md) - [remoteAbilityInfo](reference/apis/js-apis-bundle-remoteAbilityInfo.md) - [shortcutInfo](reference/apis/js-apis-bundle-ShortcutInfo.md) + - data/rdb + - [resultSet](reference/apis/js-apis-data-resultset.md) - Error Codes - [Universal Error Codes](reference/errorcodes/errorcode-universal.md) - Ability Framework @@ -1253,7 +1469,15 @@ - [Telephony Error Codes](reference/errorcodes/errorcode-telephony.md) - Network Management - [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 + - [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) - [RPC Error Codes](reference/errorcodes/errorcode-rpc.md) - Basic Features @@ -1264,6 +1488,7 @@ - [HiDebug Error Codes](reference/errorcodes/errorcode-hiviewdfx-hidebug.md) - [Input Method Framework Error Codes](reference/errorcodes/errorcode-inputmethod-framework.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) - [Webview Error Codes](reference/errorcodes/errorcode-webview.md) - Account Management @@ -1293,10 +1518,7 @@ - [Native XComponent](reference/native-apis/_o_h___native_x_component.md) - [HiLog](reference/native-apis/_hi_log.md) - [NativeWindow](reference/native-apis/_native_window.md) - - [OH_NativeBuffer](reference/native-apis/_o_h___native_buffer.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) - [Rawfile](reference/native-apis/rawfile.md) - [MindSpore](reference/native-apis/_mind_spore.md) @@ -1324,10 +1546,7 @@ - [external_window.h](reference/native-apis/external__window_8h.md) - [image_pixel_map_napi.h](reference/native-apis/image__pixel__map__napi_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_vsync.h](reference/native-apis/native__vsync_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.h](reference/native-apis/raw__file_8h.md) @@ -1353,7 +1572,6 @@ - [native_huks_type.h](reference/native-apis/native__huks__type_8h.md) - Structs - [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_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) @@ -1387,33 +1605,39 @@ - [OH_Huks_ParamSet](reference/native-apis/_o_h___huks___param_set.md) - [OH_Huks_PubKeyInfo](reference/native-apis/_o_h___huks___pub_key_info.md) - [OH_Huks_Result](reference/native-apis/_o_h___huks___result.md) - - Standard Libraries Supported by Native APIs - - [Node_API](reference/native-lib/third_party_napi/napi.md) - - [libuv](reference/native-lib/third_party_libuv/libuv.md) - - [Native Standard Libraries Supported by Openharmony](reference/native-lib/third_party_libc/musl.md) - - Appendix - - [Native API Symbols Not Exported](reference/native-lib/third_party_libc/musl-peculiar-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) + - Standard Libraries Supported by Native APIs + - [Node_API](reference/native-lib/third_party_napi/napi.md) + - [libuv](reference/native-lib/third_party_libuv/libuv.md) + - [Native Standard Libraries Supported by Openharmony](reference/native-lib/third_party_libc/musl.md) + - Appendix + - [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) + - [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 - - [Guide to Switching to Full SDK](quick-start/full-sdk-switch-guide.md) - - [Programming Languages](faqs/faqs-language.md) + - [Full SDK Compilation Guide](faqs/full-sdk-compile-guide.md) + - [Guide to Switching to Full SDK](faqs/full-sdk-switch-guide.md) - [Ability Framework Development](faqs/faqs-ability.md) - - [Bundle Management Development](faqs/faqs-bundle.md) - - [ArkUI (ArkTS) Development](faqs/faqs-ui-ets.md) - - [ArkUI Web Component (ArkTS) Development](faqs/faqs-web-arkts.md) - - [ArkUI (JavaScript) Development](faqs/faqs-ui-js.md) + - ArkUI Framework Development (ArkTS) + - [ArkUI Development (ArkTS Syntax)](faqs/faqs-arkui-arkts.md) + - [Web Development](faqs/faqs-arkui-web.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) - [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) - - [Media Development](faqs/faqs-media.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) + - [Network Management Development](faqs/faqs-network-management.md) - [DFX Development](faqs/faqs-dfx.md) - - [Intl Development](faqs/faqs-international.md) - - [Native API Usage](faqs/faqs-native.md) - - [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-party-library.md) - - [IDE Usage](faqs/faqs-ide.md) - - [Development Board](faqs/faqs-development-board.md) - + - [Pan-Sensor Development](faqs/faqs-sensor.md) + - [Startup Development](faqs/faqs-startup.md) + - [Distributed Device Development](faqs/faqs-distributed-device-profile.md) + - [SDK Usage](faqs/faqs-sdk.md) + - [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-fourth-party-library.md) + + \ No newline at end of file diff --git a/en/contribute/OpenHarmony-Application-Typescript-JavaScript-coding-guide.md b/en/contribute/OpenHarmony-Application-Typescript-JavaScript-coding-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..bced977f51134c7f2ef05e659f219b38961c8e5d --- /dev/null +++ b/en/contribute/OpenHarmony-Application-Typescript-JavaScript-coding-guide.md @@ -0,0 +1,1016 @@ +# 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): string {} +``` + +**[Correct Example]** + +```javascript +const age: number = 17; +function greet(): string {} +function greet(param: Array): 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 = new Set(); +``` + +**[Correct Example]** + +```javascript +const x = 1; + +const x: Set = new Set(); +``` + +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 diff --git a/en/design/OpenHarmony-part-design.md b/en/design/OpenHarmony-part-design.md index 7e6db1f4564b9f2262f2365ebbac01054755ab0d..9aa56571f2f1228080ead84bf8c01934ecad69b7 100644 --- a/en/design/OpenHarmony-part-design.md +++ b/en/design/OpenHarmony-part-design.md @@ -1,118 +1,353 @@ -# 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 \_. 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** - -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 \_. 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: +> **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 (\_). -#### **Path** - -The part name must be in the format of //, for example, **foundation/filemanagement/storage_service**. +**Rule 1.10**: The component source code path must be in the format of //, for example, **foundation/filemanagement/storage_service**. -#### **Part Directory Structure** +**Rule 1.11** The component directory structure must be as follows: ```xml ├── interfaces # APIs │ ├── kits # Application APIs (optional) │ │ ├── js # JS APIs (optional) │ │ └── native # C/C++ APIs (optional) -│ └── inner_api # Internal APIs of parts -├── frameworks # Implementation of the part without independent processes (optional) +│ └── inner_api # Internal APIs of components +├── frameworks # Implementation of components without independent processes (optional) │ ├── native # C/C++ API implementation (optional) -│ └── js # JS API implementation (optional) +│ └── js # JS API implementation (optional) │ ├── napi # Native API implementation (optional) │ ├── builtin # Specific to LiteOS-M (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) ├── BUILD.gn # Entry to build (mandatory) -└── bundle.json # Part description file (mandatory) +└── bundle.json # Component description file (mandatory) ``` -## Adding, Deleting, or Modifying Parts +**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. -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: +5. A Required Product Compatibility ID (RPCID), a set of system capabilities required by the application, is automatically generated during application compilation and packaging. -1. Prepare the following part attribute review form. +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. -Table 1 Part attribute review form +7. In the ability continuation scenario, the system capabilities are synchronized between devices. -| Part Attribute | Description | -| ------------ | ------------------------------------------------------------ | -| 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. | +8. In the installation-free scenario, the system capabilities of a device can be queried on the cloud. +#### Using System Capabilities During Application Development -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. +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" + ] + } + } +} +``` + +**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: + +```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" +} +``` -> Note: +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 +``` + +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": [] + } + ] + }, + ... + ] +} +``` + +The compilation command is **./build.sh --product-name my_product**. + +### Determining Whether a Component Is Required + +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** +> +> 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. diff --git a/en/design/figures/Component-Definition.png b/en/design/figures/Component-Definition.png new file mode 100644 index 0000000000000000000000000000000000000000..7315ba6499270c4910fdd2f3ff815868104f1140 Binary files /dev/null and b/en/design/figures/Component-Definition.png differ diff --git a/en/design/figures/Component-Module.png b/en/design/figures/Component-Module.png new file mode 100644 index 0000000000000000000000000000000000000000..28dd092a067b644c7d5dea9fe493d9d96d068a50 Binary files /dev/null and b/en/design/figures/Component-Module.png differ diff --git a/en/design/figures/Component-SysCap.png b/en/design/figures/Component-SysCap.png new file mode 100644 index 0000000000000000000000000000000000000000..0ff5674d430bfb260acb867dc1716f85d2ecc4c3 Binary files /dev/null and b/en/design/figures/Component-SysCap.png differ diff --git a/en/device-dev/subsystems/Readme-EN.md b/en/device-dev/subsystems/Readme-EN.md index ee9395bf43e05bb96162763054bef034a971c3b0..3ffc19418a1e83b0e87abc59cbfc460dfca1a392 100644 --- a/en/device-dev/subsystems/Readme-EN.md +++ b/en/device-dev/subsystems/Readme-EN.md @@ -18,6 +18,10 @@ - [Configuring Parameters for Accelerating Local Build](subsys-build-reference.md) - [Viewing Ninja Build Information](subsys-build-reference.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) - [ArkCompiler Development](subsys-arkcompiler-guide.md) - [Distributed Remote Startup](subsys-remote-start.md) diff --git a/en/device-dev/subsystems/figures/bindgen_and_cxx_tools.png b/en/device-dev/subsystems/figures/bindgen_and_cxx_tools.png new file mode 100644 index 0000000000000000000000000000000000000000..655472225f3dd5581e5849e0af80ff89468094a1 Binary files /dev/null and b/en/device-dev/subsystems/figures/bindgen_and_cxx_tools.png differ diff --git a/en/device-dev/subsystems/figures/bindgen_test.png b/en/device-dev/subsystems/figures/bindgen_test.png new file mode 100644 index 0000000000000000000000000000000000000000..4c4d01b567e35fd07ce7a8a90256281cd9fcc165 Binary files /dev/null and b/en/device-dev/subsystems/figures/bindgen_test.png differ diff --git a/en/device-dev/subsystems/figures/cpp_call_rust.png b/en/device-dev/subsystems/figures/cpp_call_rust.png new file mode 100644 index 0000000000000000000000000000000000000000..49503982f893fb6c24d1e41c24ae54aa9681e2c6 Binary files /dev/null and b/en/device-dev/subsystems/figures/cpp_call_rust.png differ diff --git a/en/device-dev/subsystems/figures/rust_call_cpp.png b/en/device-dev/subsystems/figures/rust_call_cpp.png new file mode 100644 index 0000000000000000000000000000000000000000..eba899d0b111c71420b43c36c21e519228a06d54 Binary files /dev/null and b/en/device-dev/subsystems/figures/rust_call_cpp.png differ diff --git a/en/device-dev/subsystems/figures/test_rlib_cargo_crate.png b/en/device-dev/subsystems/figures/test_rlib_cargo_crate.png new file mode 100644 index 0000000000000000000000000000000000000000..86ade8272f625e6aa4336c713d52ee537918531c Binary files /dev/null and b/en/device-dev/subsystems/figures/test_rlib_cargo_crate.png differ diff --git a/en/device-dev/subsystems/figures/test_rlib_crate.png b/en/device-dev/subsystems/figures/test_rlib_crate.png new file mode 100644 index 0000000000000000000000000000000000000000..3df5877b7a3f583513527de1adcdabb80755961a Binary files /dev/null and b/en/device-dev/subsystems/figures/test_rlib_crate.png differ diff --git a/en/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md b/en/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..cd9bdd0db7b444dc30ed56b666a62d54e194fdcb --- /dev/null +++ b/en/device-dev/subsystems/subsys-build-bindgen-cxx-guide.md @@ -0,0 +1,421 @@ +# 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 + #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 + #include + + 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 + #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 + #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; + }; + + std::unique_ptr blobstore_client_new(); + } // namespace nsp_blobstore + } // namespace nsp_org + #endif + ``` + +2. Create the **client_blobstore.cpp** file. + + ```c++ + #include + #include + #include + #include + #include + #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 tags; + }; + std::unordered_map 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(res_chunk.data()), res_chunk.size()); + } + + // Insert into map and provide caller the handle. + auto res = std::hash {} (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 blobstore_client_new() + { + return std::make_unique(); + } + } // 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, + } + + // 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; + 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> 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>, + 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) diff --git a/en/device-dev/subsystems/subsys-build-cargo2gn-guide.md b/en/device-dev/subsystems/subsys-build-cargo2gn-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..fcf8a04804809485cbaed0cee49ca467272a4caf --- /dev/null +++ b/en/device-dev/subsystems/subsys-build-cargo2gn-guide.md @@ -0,0 +1,95 @@ +# 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 , Emilio Cobos Álvarez , Nick Fitzgerald , 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". diff --git a/en/device-dev/subsystems/subsys-build-module.md b/en/device-dev/subsystems/subsys-build-module.md index bc5ec28957f446b4b4ca8b221580467083d2963f..49f58da2bdc3b0b8577b178eb0b418cec59eb3d3 100644 --- a/en/device-dev/subsystems/subsys-build-module.md +++ b/en/device-dev/subsystems/subsys-build-module.md @@ -23,6 +23,17 @@ ohos_app_scope ohos_js_assets 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 # Configuration file ohos_prebuilt_etc @@ -33,7 +44,7 @@ ohos_sa_profile 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**. @@ -69,7 +80,7 @@ ohos_shared_library("helloworld") { cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check. cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI 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. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -91,12 +102,12 @@ ohos_shared_library("helloworld") { } ``` -**ohos_static_library** example: +**ohos_static_library** example ```shell import("//build/ohos.gni") ohos_static_library("helloworld") { - sources = ["file"] # Source code in .c format. + sources = ["file"] # .c files. include_dirs = ["dir"] # Directories to be included. configs = [] # Configuration. deps = [] # Define dependent modules that belong to the same component. @@ -114,11 +125,11 @@ ohos_static_library("helloworld") { # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. sanitize = { # 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. integer_overflow = [boolean] # Whether to enable the integer overflow check. - boundary_sanitize = [boolean] # Whether to enable the bounds check. - ubsan = [boolean] # Whether to enable some UBSAN options. + boundary_sanitize = [boolean] # Whether to enable the boundary check. + ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -139,7 +150,7 @@ ohos_static_library("helloworld") { ```shell import("//build/ohos.gni") ohos_executable("helloworld") { - configs = [] # Configuration. + configs = [] # Configuration. part_name = [string] # Component name. subsystem_name = [string] # Subsystem name. deps = [] # Define dependent modules that belong to the same component. @@ -153,10 +164,10 @@ ohos_executable("helloworld") { # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. sanitize = { # 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. 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. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -181,32 +192,32 @@ ohos_executable("helloworld") { } ``` -**ohos_source_set** example: +**ohos_source_set** example ```shell import("//build/ohos.gni") ohos_source_set("helloworld") { - sources = ["file"] # Source code in .c format. - include_dirs = [] # Directories to be included. - configs = [] # Configuration. - public = [] # Header files. + sources = ["file"] # .c files. + include_dirs = [] # Directories to be included. + configs = [] # Configuration. + public = [] # .h header files. defines = [] public_configs = [] - part_name = [string] # Component name. - subsystem_name = [string] # Subsystem name. - deps = [] # Define dependent modules that belong to the same component. + part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + deps = [] # Define dependent modules that belong to the same component. - external_deps = [ # Define dependent modules that belong to different components. - "part_name:module_name", # The value is in the Component_name:Module_name format. - ] # The dependent modules must be declared in inner_kits by the dependent component. + external_deps = [ # Define dependent modules that belong to different components. + "part_name:module_name", # The value is in the Component_name:Module_name format. + ] # The dependent modules must be declared in inner_kits by the dependent component. # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. sanitize = { # 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. 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. all_ubsan = [boolean] # Whether to enable all UBSAN options. ... @@ -226,72 +237,71 @@ ohos_source_set("helloworld") { } ``` -> **NOTE** -> -> - Only **sources** and **part_name** are mandatory. -> - For details about the Sanitizer configuration, see [Using Sanitizer](subsys-build-reference.md#using-sanitizer). +**NOTE**
+ - Only **sources** and **part_name** are mandatory. + - 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**. -**ohos_prebuilt_executable** example: +**ohos_prebuilt_executable** example ```shell import("//build/ohos.gni") ohos_prebuilt_executable("helloworld") { - sources = ["file"] # Source. + sources = ["file"] # Source. output = [] - install_enable = [boolean] + install_enable = [boolean] - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. public_configs = [] - subsystem_name = [string] # Subsystem name. - part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + part_name = [string] # Component name. testonly = [boolean] visibility = [] install_images = [] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. symlink_target_name = [] - license_file = [] # A .txt file. + license_file = [] # A .txt file. license_as_sources = [] } ``` -**ohos_prebuilt_shared_library** example: +**ohos_prebuilt_shared_library** example ```shell import("//build/ohos.gni") ohos_prebuilt_shared_library("helloworld") { - sources = ["file"] # .so files. + sources = ["file"] # .so files. output = [] install_enable = [boolean] - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. public_configs = [] - subsystem_name = [string] # Subsystem name. - part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + part_name = [string] # Component name. testonly = [boolean] visibility = [] install_images = [] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. symlink_target_name = [string] - license_file = [string] # A .txt file. + license_file = [string] # A .txt file. license_as_sources = [] } ``` -**ohos_prebuilt_static_library** example: +**ohos_prebuilt_static_library** example ```shell import("//build/ohos.gni") @@ -312,13 +322,15 @@ ohos_prebuilt_static_library("helloworld") { } ``` ->**NOTE**
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 -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 @@ -329,14 +341,14 @@ import("//build/ohos.gni") ohos_prebuilt_etc("helloworld") { # The most common attributes of the ohos_prebuilt_etc template. sources = ["file"] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - subsystem_name = [string] # Subsystem name. - part_name = [string] # (Mandatory) Component name. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + subsystem_name = [string] # Subsystem name. + part_name = [string] # (Mandatory) Component name. install_images = [] - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. # Uncommon attributes of the ohos_prebuilt_etc template: - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. testonly = [boolean] visibility = [] public_configs = [] @@ -357,7 +369,7 @@ ohos_sa_profile("helloworld") { } ``` -> **NOTE**
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 @@ -379,47 +391,49 @@ The following figure shows the logic for adding a module. Generally, you need to ```shell { - "name": "@ohos/, # HPM component name, in the "@Organization/Component_name" format. - "description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions. - "version": "3.1", # Version, which must be the same as the version of OpenHarmony. - "license": "MIT", # Component license. - "publishAs": "code-segment", # HPM package release mode. The default value is code-segment. + "name": "@ohos/, # HPM component name, in the "@Organization/Component_name" format. + "description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions. + "version": "3.1", # Version, which must be the same as the version of OpenHarmony. + "license": "MIT", # Component license. + "publishAs": "code-segment", # HPM package release mode. The default value is code-segment. "segment": { "destPath": "third_party/nghttp2" - }, # Code restoration path (source code path) set when publishAs is code-segment. - "dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty. - "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty. + }, # Code restoration path (source code path) set when publishAs is code-segment. + "dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty. + "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty. "licensePath": "COPYING", "readmePath": { "en": "README.rst" }, - "component": { # Component attributes. - "name": "", # Component name. - "subsystem": "", # Subsystem to which the component belongs. - "syscap": [], # System capabilities provided by the component for applications. - "features": [], # List of configurable features of the component. Generally, this parameter corresponds to sub_component in build. - "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, standard, or their combinations. - "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. - "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. + "component": { # Component attributes. + "name": "", # Component name. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of configurable features of the component. Generally, this parameter corresponds to sub_component in build. + "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, standard, or their combinations. + "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. + "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. "deps": { - "components": [ # Other components on which this component depends. - "third_party": [ # Third-party open-source software on which this component depends. + "components": [ # Other components on which this component depends. + "third_party": [ # Third-party open-source software on which this component depends. }, - "build": { # Build-related configuration. + "build": { # Build-related configuration. "sub_component": [ - "//foundation/arkui/napi:napi_packages", # Existing module 1. - "//foundation/arkui/napi:napi_packages_ndk"# Existing module 2. - "//foundation/arkui/napi:new" # Module to add. - ], # Component build entry. Configure the module here. - "inner_kits": [], # APIs between components. - "test": [] # Entry for building the component's test cases. + "//foundation/arkui/napi:napi_packages", # Existing module 1. + "//foundation/arkui/napi:napi_packages_ndk" # Existing module 2. + "//foundation/arkui/napi:new" # Module to add. + ], # Component build entry. Configure the module here. + "inner_kits": [], # APIs between components. + "test": [] # Entry for building the component's test cases. } } } ``` - > **NOTE**
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. @@ -429,16 +443,16 @@ 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. -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 "subsystems": [ { "subsystem": "Subsystem to which the component belongs", "components": [ - {"component": "Component 1 name", "features":[]}, # Existing component 1 in the subsystem - { "component": "Component 2 name", "features":[] }, # Existing component 2 in the subsystem - {"component": "New component name", "features":[]} # New component in the subsystem + {"component": "Component 1 name", "features":[]}, # Existing component 1 in the subsystem + { "component": "Component 2 name", "features":[] }, # Existing component 2 in the subsystem + {"component": "New component name", "features":[]} # New component in the subsystem ] }, . @@ -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. -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 "subsystems": [ @@ -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 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 ./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 ./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 ./build.sh --product-name hispark_taurus_standard --build-target musl --build-target Module_name --ccache diff --git a/en/device-dev/subsystems/subsys-build-rust-compilation.md b/en/device-dev/subsystems/subsys-build-rust-compilation.md new file mode 100644 index 0000000000000000000000000000000000000000..b02f52d3d27110bc29f29a3fc245e92af78ed0db --- /dev/null +++ b/en/device-dev/subsystems/subsys-build-rust-compilation.md @@ -0,0 +1,369 @@ +# 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 { + 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 | diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md index 42a3db4829466d03e219c919f7cb7f200734b108..f8f27e77b91602c5d1b54a8e7e5d06f7fabd69c5 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.10.5/changelogs-filemanagement.md @@ -2,11 +2,11 @@ ## 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** -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** @@ -24,11 +24,11 @@ import environment from '@ohos.file.environment'; ## 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** -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** @@ -58,11 +58,11 @@ The type of the **ino** attribute of **Stat** is changed from number to BigInt. ## 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** -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** @@ -80,11 +80,11 @@ import fileAccess from '@ohos.file.fileAccess'; ## 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** -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** @@ -102,11 +102,11 @@ import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; ## 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** -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** @@ -124,11 +124,11 @@ import storageStatistics from '@ohos.file.storageStatistics'; ## 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** -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** diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-ability.md b/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..5920a7cdf72d6f3b02f7fca84eafea67abbfcc1e --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_3.2.12.2/changelog-ability.md @@ -0,0 +1,34 @@ +# 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.| diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-bundlemanager.md b/en/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-bundlemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..f41df5b62252f03508110ed8931d47e6198b8b61 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.2.2/changelogs-bundlemanager.md @@ -0,0 +1,14 @@ +# 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**
+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**
+No API or component change is involved. + +**Adaptation Guide**
+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) diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md index 18c89d87f89719c70a87007b7abe72f5f10a913d..8e87141a86ae135fd6ea581b8666a2433caf3bf7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md @@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability'; | 名称 | 类型 | 描述 | | ----------- | -------------------- | ------------------------------------------------------------ | | 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二级模块。 | | DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | DataAbilityResult二级模块。 | | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | AbilityResult二级模块。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md index 9389a1a82f36d996ba87cc8e51fa87fe83923977..f5c71a99fb3f6683dd36c007e6bfd434e36253aa 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -1,6 +1,6 @@ # @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)对象提供获取当前测试参数的能力。 > **说明:** > diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md index 6b864a63ac5748aa57d97536d44f53b0ce0107ef..101320203d58556a56d6d5d742dd87d573148a05 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md @@ -26,7 +26,7 @@ import common from '@ohos.app.ability.common'; | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | FormExtensionContext二级模块。 | | ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | ServiceExtensionContext二级模块。 | | 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二级模块。 | | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | ConnectOptions二级模块。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-want.md b/zh-cn/application-dev/reference/apis/js-apis-application-want.md index 184d2ee6fe82c73a60046da37d1b83473491ae73..79ec55abac8102f1ede8c637a516988c1f31a1d3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-want.md @@ -130,6 +130,6 @@ import Want from '@ohos.application.Want'; }); ``` -- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want +- 更多详细说明和示例请参见: [应用模型](../../application-models/application-model-composition.md)的信息传递载体Want \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 083085edba4d8c32b28c5ba19c822918642ffbf5..d2c9e1e07f40c3545cea3b752e17ec9a3b2b729d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -865,8 +865,8 @@ call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCa | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | method | string | 是 | 指示被调用的方法名。 | | arg | string | 是 | 指示需传入的参数。 | -| extras | [PacMap](js-apis-inner-application-pacMap.md) | 是 | 指示扩展的键值对参数。 | -| callback | AsyncCallback\<[PacMap](js-apis-inner-application-pacMap.md)> | 是 | 指示数据操作的回调方法,返回操作结果。 | +| extras | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | 是 | 指示扩展的键值对参数。 | +| callback | AsyncCallback\<[PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)> | 是 | 指示数据操作的回调方法,返回操作结果。 | **示例:** @@ -901,13 +901,13 @@ call(uri: string, method: string, arg: string, extras: PacMap): Promise\ | uri | string | 是 | 指示待处理的DataAbility。例:'dataability:///com.example.xxx.xxxx' | | method | 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)> | 返回操作结果。 | **示例:** @@ -997,4 +997,14 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi console.error('executeBatch failed, error: ${error}'); }); -``` \ No newline at end of file +``` + +## PacMap + +[key: string]: number | string | boolean | Array\ | null; + +**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel + +| 参数名 | 参数类型 | 必填 | 说明 | +| ------ | ------ | ------ | ------ | +| [key: string] | number \| string \| boolean \| Array\ \| null | Yes| 数据存储在键值对中。| \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md index 5f0bb262f96daf1711bf7d55e9614be799194df5..97f8b12c1060d0a2ac1983c43e562666d2866fc2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -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 newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index 23c7178e3472d55228a76b70fbcd20fd70166316..c4e780a4596dcda7249993f943a084b354760290 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -358,9 +358,9 @@ Audio/Video播放demo可参考:[音频播放开发指导](../../media/using-av | 名称 | 类型 | 可读 | 可写 | 说明 | | --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| url9+ | string | 是 | 是 | 媒体URL,只允许在**idle**状态下设置,静态属性。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav)。
**支持路径示例**:
1. fd类型播放:fd://xx。
![](figures/zh-cn_image_url.png)
2. http网络播放: http://xx。
3. https网络播放: https://xx。
4. hls网络播放路径:http://xx或者https://xx。 | -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 媒体文件描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用中的媒体资源被连续存储在同一个文件中。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav)。
**使用示例**:
假设一个连续存储的媒体文件:
视频1(地址偏移:0,字节长度:100);
视频2(地址偏移:101,字节长度:50);
视频3(地址偏移:151,字节长度:150);
1. 播放视频1:AVFileDescriptor { fd = 资源句柄; offset = 0; length = 100; }。
2. 播放视频2:AVFileDescriptor { fd = 资源句柄; offset = 101; length = 50; }。
3. 播放视频3:AVFileDescriptor { fd = 资源句柄; offset = 151; length = 150; }。
假设是一个独立的媒体文件: 请使用src=fd://xx。 | -| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | 是 | 是 | 流式媒体资源描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用播放从远端下载到本地的文件,在应用未下载完整音视频资源时,提前播放已获取的资源文件。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav)。
**使用示例**:
假设用户正在从远端服务器获取音视频媒体文件,希望下载到本地的同时播放已经下载好的部分:
1.用户需要获取媒体文件的总大小size(单位为字节),获取不到时设置为-1。
2.用户需要实现回调函数func用于填写数据,如果size = -1,则func形式为:func(buffer: ArrayBuffer, length: number),此时播放器只会按照顺序获取数据;否则func形式为:func(buffer: ArrayBuffer, length: number, pos: number),播放器会按需跳转并获取数据。
3.用户设置AVDataSrcDescriptor {fileSize = size, callback = func}。
**注意事项**:
如果播放的是mp4/m4a格式用户需要保证moov字段(媒体信息字段)在mdat字段(媒体数据字段)之前,或者moov之前的字段小于10M,否则会导致解析失败无法播放。 | +| url9+ | string | 是 | 是 | 媒体URL,只允许在**idle**状态下设置,静态属性。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。
**支持路径示例**:
1. fd类型播放:fd://xx。
![](figures/zh-cn_image_url.png)
2. http网络播放: http://xx。
3. https网络播放: https://xx。
4. hls网络播放路径:http://xx或者https://xx。 | +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 媒体文件描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用中的媒体资源被连续存储在同一个文件中。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。
**使用示例**:
假设一个连续存储的媒体文件:
视频1(地址偏移:0,字节长度:100);
视频2(地址偏移:101,字节长度:50);
视频3(地址偏移:151,字节长度:150);
1. 播放视频1:AVFileDescriptor { fd = 资源句柄; offset = 0; length = 100; }。
2. 播放视频2:AVFileDescriptor { fd = 资源句柄; offset = 101; length = 50; }。
3. 播放视频3:AVFileDescriptor { fd = 资源句柄; offset = 151; length = 150; }。
假设是一个独立的媒体文件: 请使用src=fd://xx。 | +| dataSrc10+ | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | 是 | 是 | 流式媒体资源描述,只允许在**idle**状态下设置,静态属性。
使用场景:应用播放从远端下载到本地的文件,在应用未下载完整音视频资源时,提前播放已获取的资源文件。
支持的视频格式(mp4、mpeg-ts、webm、mkv)。
支持的音频格式(m4a、aac、mp3、ogg、wav、flac)。
**使用示例**:
假设用户正在从远端服务器获取音视频媒体文件,希望下载到本地的同时播放已经下载好的部分:
1.用户需要获取媒体文件的总大小size(单位为字节),获取不到时设置为-1。
2.用户需要实现回调函数func用于填写数据,如果size = -1,则func形式为:func(buffer: ArrayBuffer, length: number),此时播放器只会按照顺序获取数据;否则func形式为:func(buffer: ArrayBuffer, length: number, pos: number),播放器会按需跳转并获取数据。
3.用户设置AVDataSrcDescriptor {fileSize = size, callback = func}。
**注意事项**:
如果播放的是mp4/m4a格式用户需要保证moov字段(媒体信息字段)在mdat字段(媒体数据字段)之前,或者moov之前的字段小于10M,否则会导致解析失败无法播放。 | | surfaceId9+ | string | 是 | 是 | 视频窗口ID,默认无窗口,只允许在**initialized**状态下设置,静态属性。
使用场景:视频播放的窗口渲染,纯音频播放不用设置。
**使用示例**:
[通过Xcomponent创建surfaceId](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid)。 | | loop9+ | boolean | 是 | 是 | 视频循环播放属性,默认'false',设置为'true'表示循环播放,动态属性。
只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。
直播场景不支持loop设置。 | | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式,默认VIDEO_SCALE_TYPE_FIT_CROP,动态属性。
只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md index c8ea47c3362685912a7ad6988523f9e3092d8733..b65f72de56095cce9f97b7cf9be04af2c439938e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @@ -767,7 +767,7 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 | uid9+ | number[] | 是 | 否 | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。 | | technology9+ | number[] | 是 | 否 | 支持的技术类型,每个number值表示所支持技术类型的常量值。 | | supportedProfiles | number[] | 是 | 否 | 支持的技术类型,从API9开始不支持,使用[tag.TagInfo#technology](#tagtaginfo)替代。 | -| extrasData9+ | [PacMap](js-apis-inner-application-pacMap.md)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。 | +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | 是 | 否 | 标签所支持技术的扩展属性值。
**系统接口:** 此接口为系统接口。 | | tagRfDiscId9+ | number | 是 | 否 | 标签发现时分配的ID值。
**系统接口:** 此接口为系统接口。 | | remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | 是 | 否 | NFC服务进程的远端对象,用于客户端和服务之间的接口通信。
**系统接口:** 此接口为系统接口。 | ## NdefRecord9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifi.md b/zh-cn/application-dev/reference/apis/js-apis-wifi.md index 6fceb9cc33fedadf690bf98388308890e4ce04bf..f9e36545ae735bcbf902e255006fd74eb85f3175 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifi.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifi.md @@ -33,14 +33,14 @@ enableWifi(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.enableWifi(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.enableWifi(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disableWifi @@ -63,14 +63,15 @@ disableWifi(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; + +try { + wifi.disableWifi(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} - try { - wifi.disableWifi(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } ``` ## wifi.isWifiActive @@ -91,15 +92,15 @@ isWifiActive(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let isActivate = wifi.isActivate(); - console.info("isActivate:" + isActivate); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let isActivate = wifi.isActivate(); + console.info("isActivate:" + isActivate); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.scan @@ -120,14 +121,14 @@ scan(): boolean **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.scan(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.scan(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getScanInfos @@ -164,46 +165,47 @@ getScanInfos(callback: AsyncCallback<Array<WifiScanInfo>>): void | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | 是 | 回调函数。当成功时,err为0,data为扫描到的热点;否则err为非0值,data为空。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - wifi.getScanInfos((err, result) => { - if (err) { - console.error("get scan info error"); - return; - } - - var len = Object.keys(result).length; - console.log("wifi received scan info: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("capabilities: " + result[i].capabilities); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("channelWidth: " + result[i].channelWidth); - console.info("timestamp: " + result[i].timestamp); - } - }); - - wifi.getScanInfos().then(result => { - var len = Object.keys(result).length; - console.log("wifi received scan info: " + len); - for (var i = 0; i < len; ++i) { - console.info("ssid: " + result[i].ssid); - console.info("bssid: " + result[i].bssid); - console.info("capabilities: " + result[i].capabilities); - console.info("securityType: " + result[i].securityType); - console.info("rssi: " + result[i].rssi); - console.info("band: " + result[i].band); - console.info("frequency: " + result[i].frequency); - console.info("channelWidth: " + result[i].channelWidth); - console.info("timestamp: " + result[i].timestamp); - } - }); - ``` + +```js +import wifi from '@ohos.wifi'; + +wifi.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } +}); + +wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } +}); +``` ## WifiScanInfo @@ -282,24 +284,24 @@ addDeviceConfig(config: WifiDeviceConfig): Promise<number> | **类型** | **说明** | | -------- | -------- | | Promise<number> | Promise对象。返回添加的网络配置ID,如果值为-1表示添加失败。 | - + **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addDeviceConfig(config).then(result => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } + wifi.addDeviceConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## WifiDeviceConfig @@ -378,21 +380,21 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>) **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addDeviceConfig(config,(error,result) => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } + wifi.addDeviceConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.addUntrustedConfig7+ @@ -415,23 +417,24 @@ addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> | **类型** | **说明** | | -------- | -------- | | Promise<boolean> | Promise对象。表示操作结果,true: 成功, false: 失败。 | + **示例:** -````` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addUntrustedConfig(config).then(result => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } -````` + wifi.addUntrustedConfig(config).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.addUntrustedConfig7+ @@ -451,22 +454,22 @@ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean& | callback | AsyncCallback<boolean> | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | **示例:** -````` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 0 - } - wifi.addUntrustedConfig(config,(error,result) => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 0 } -````` + wifi.addUntrustedConfig(config,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} +``` ## wifi.removeUntrustedConfig7+ @@ -489,18 +492,20 @@ removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> | **类型** | **说明** | | -------- | -------- | | Promise<boolean> | Promise对象。表示操作结果,true: 成功, false: 失败。 | - - ``` - import wifi from '@ohos.wifi'; - - try { - let networkId = 0; - wifi.removeUntrustedConfig(networkId).then(result => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } + +**示例:** + +```js +import wifi from '@ohos.wifi'; + +try { + let networkId = 0; + wifi.removeUntrustedConfig(networkId).then(result => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -522,17 +527,17 @@ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boole | callback | AsyncCallback<boolean> | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let networkId = 0; - wifi.removeUntrustedConfig(networkId,(error,result) => { - console.info("result:" + JSON.stringify(result)); - }); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let networkId = 0; + wifi.removeUntrustedConfig(networkId,(error,result) => { + console.info("result:" + JSON.stringify(result)); + }); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.connectToNetwork @@ -561,15 +566,15 @@ connectToNetwork(networkId: number): boolean **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let networkId = 0; - wifi.connectToNetwork(networkId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +```js +import wifi from '@ohos.wifi'; + +try { + let networkId = 0; + wifi.connectToNetwork(networkId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.connectToDevice @@ -598,20 +603,20 @@ connectToDevice(config: WifiDeviceConfig): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 3 - } - wifi.connectToDevice(config); - - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 } + wifi.connectToDevice(config); + +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disconnect @@ -634,14 +639,14 @@ disconnect(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.disconnect(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.disconnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getSignalLevel @@ -668,17 +673,17 @@ getSignalLevel(rssi: number, band: number): number | number | 信号强度,取值范围为[0, 4]。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let rssi = 0; - let band = 0; - let level = wifi.getSignalLevel(rssi,band); - console.info("lelvel:" + JSON.stringify(lelvel)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +```js +import wifi from '@ohos.wifi'; + +try { + let rssi = 0; + let band = 0; + let level = wifi.getSignalLevel(rssi,band); + console.info("lelvel:" + JSON.stringify(lelvel)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -716,23 +721,23 @@ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | 是 | 回调函数。当获取成功时,err为0,data表示WLAN连接信息。如果error为非0,表示处理出现错误。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - wifi.getLinkedInfo((err, data) => { - if (err) { - console.error("get linked info error"); - return; - } - console.info("get wifi linked info: " + JSON.stringify(data)); - }); - - wifi.getLinkedInfo().then(data => { - console.info("get wifi linked info: " + JSON.stringify(data)); - }).catch(error => { - console.info("get linked info error"); - }); - ``` +```js +import wifi from '@ohos.wifi'; + +wifi.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get wifi linked info: " + JSON.stringify(data)); +}); + +wifi.getLinkedInfo().then(data => { + console.info("get wifi linked info: " + JSON.stringify(data)); +}).catch(error => { + console.info("get linked info error"); +}); +``` ## WifiLinkedInfo @@ -877,16 +882,16 @@ isFeatureSupported(featureId: number): boolean | boolean | true:支持, false:不支持。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let featureId = 0; - let ret = wifi.isFeatureSupported(featureId); - console.info("isFeatureSupported:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +```js +import wifi from '@ohos.wifi'; + +try { + let featureId = 0; + let ret = wifi.isFeatureSupported(featureId); + console.info("isFeatureSupported:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -909,15 +914,15 @@ getDeviceMacAddress(): string[] | string[] | MAC地址。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let ret = wifi.getDeviceMacAddress(); - console.info("deviceMacAddress:" + JSON.stringify(ret)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let ret = wifi.getDeviceMacAddress(); + console.info("deviceMacAddress:" + JSON.stringify(ret)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` @@ -938,15 +943,15 @@ getIpInfo(): IpInfo | [IpInfo](#ipinfo7) | IP信息。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let info = wifi.getIpInfo(); - console.info("info:" + JSON.stringify(info)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let info = wifi.getIpInfo(); + console.info("info:" + JSON.stringify(info)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## IpInfo7+ @@ -983,15 +988,15 @@ getCountryCode(): string | string | 国家码。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let code = wifi.getCountryCode(); - console.info("code:" + code); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let code = wifi.getCountryCode(); + console.info("code:" + code); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.reassociate7+ @@ -1013,14 +1018,14 @@ reassociate(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.reassociate(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.reassociate(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.reconnect7+ @@ -1042,14 +1047,14 @@ reconnect(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.reconnect(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.reconnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getDeviceConfigs7+ @@ -1071,15 +1076,15 @@ getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> |  Array<[WifiDeviceConfig](#wifideviceconfig)> | 网络配置信息的数组。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let configs = wifi.getDeviceConfigs(); - console.info("configs:" + JSON.stringify(configs)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let configs = wifi.getDeviceConfigs(); + console.info("configs:" + JSON.stringify(configs)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.updateNetwork7+ @@ -1107,20 +1112,20 @@ updateNetwork(config: WifiDeviceConfig): number | number | 返回更新的网络配置ID,如果值为-1表示更新失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid : "****", - preSharedKey : "****", - securityType : 3 - } - let ret = wifi.updateNetwork(config); - console.error("ret:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid : "****", + preSharedKey : "****", + securityType : 3 } + let ret = wifi.updateNetwork(config); + console.error("ret:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disableNetwork7+ @@ -1148,15 +1153,15 @@ disableNetwork(netId: number): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let netId = 0; - wifi.disableNetwork(netId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let netId = 0; + wifi.disableNetwork(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.removeAllNetwork7+ @@ -1178,14 +1183,14 @@ removeAllNetwork(): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.removeAllNetwork(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.removeAllNetwork(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.removeDevice7+ @@ -1213,15 +1218,15 @@ removeDevice(id: number): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let id = 0; - wifi.removeDevice(id); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let id = 0; + wifi.removeDevice(id); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.enableHotspot7+ @@ -1243,14 +1248,14 @@ enableHotspot(): boolean | boolean | true:操作成功, false:操作失败。| **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.enableHotspot(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.enableHotspot(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.disableHotspot7+ @@ -1272,14 +1277,14 @@ disableHotspot(): boolean | boolean | true:操作成功, false:操作失败。| **示例:** -``` - import wifi from '@ohos.wifiManager'; +```js +import wifi from '@ohos.wifiManager'; - try { - wifiManager.disableHotspot(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifiManager.disableHotspot(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.isHotspotDualBandSupported7+ @@ -1301,15 +1306,15 @@ isHotspotDualBandSupported(): boolean | boolean | true:支持, false:不支持。| **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let ret = wifi.isHotspotDualBandSupported(); - console.info("result:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let ret = wifi.isHotspotDualBandSupported(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.isHotspotActive7+ @@ -1331,15 +1336,15 @@ isHotspotActive(): boolean | boolean | true:已使能, false:未使能。| **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let ret = wifi.isHotspotActive(); - console.info("result:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let ret = wifi.isHotspotActive(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.setHotspotConfig7+ @@ -1367,23 +1372,23 @@ setHotspotConfig(config: HotspotConfig): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - ssid: "****", - securityType: 3, - band: 0, - channel: 0, - preSharedKey: "****", - maxConn: 0 - } - let ret = wifi.setHotspotConfig(); - console.info("result:" + ret); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + ssid: "****", + securityType: 3, + band: 0, + channel: 0, + preSharedKey: "****", + maxConn: 0 } + let ret = wifi.setHotspotConfig(); + console.info("result:" + ret); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## HotspotConfig7+ @@ -1422,15 +1427,15 @@ getHotspotConfig(): HotspotConfig | [HotspotConfig](#hotspotconfig7) | 热点的配置信息。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let config = wifi.getHotspotConfig(); - console.info("result:" + JSON.stringify(config)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let config = wifi.getHotspotConfig(); + console.info("result:" + JSON.stringify(config)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.getStations7+ @@ -1452,15 +1457,15 @@ getStations():  Array<[StationInfo](#stationinfo7)> |  Array<[StationInfo](#stationinfo7)> | 连接的设备数组。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let stations = wifi.getStations(); - console.info("result:" + JSON.stringify(stations)); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let stations = wifi.getStations(); + console.info("result:" + JSON.stringify(stations)); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## StationInfo7+ @@ -1538,20 +1543,20 @@ getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 是 | 回调函数。当操作成功时,err为0,data表示P2P连接信息。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - wifi.getP2pLinkedInfo((err, data) => { - if (err) { - console.error("get p2p linked info error"); - return; - } - console.info("get wifi p2p linked info: " + JSON.stringify(data)); - }); +wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error("get p2p linked info error"); + return; + } + console.info("get wifi p2p linked info: " + JSON.stringify(data)); +}); - wifi.getP2pLinkedInfo().then(data => { - console.info("get wifi p2p linked info: " + JSON.stringify(data)); - }); +wifi.getP2pLinkedInfo().then(data => { + console.info("get wifi p2p linked info: " + JSON.stringify(data)); +}); ``` ## wifi.getCurrentGroup8+ @@ -1588,20 +1593,20 @@ getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - wifi.getCurrentGroup((err, data) => { - if (err) { - console.error("get current P2P group error"); - return; - } - console.info("get current P2P group: " + JSON.stringify(data)); - }); +wifi.getCurrentGroup((err, data) => { + if (err) { + console.error("get current P2P group error"); + return; + } + console.info("get current P2P group: " + JSON.stringify(data)); +}); - wifi.getCurrentGroup().then(data => { - console.info("get current P2P group: " + JSON.stringify(data)); - }); +wifi.getCurrentGroup().then(data => { + console.info("get current P2P group: " + JSON.stringify(data)); +}); ``` ## wifi.getP2pPeerDevices8+ @@ -1638,20 +1643,20 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 | **示例:** -``` - import wifi from '@ohos.wifiManager'; +```js +import wifi from '@ohos.wifiManager'; - wifi.getP2pPeerDevices((err, data) => { - if (err) { - console.error("get P2P peer devices error"); - return; - } - console.info("get P2P peer devices: " + JSON.stringify(data)); - }); +wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error("get P2P peer devices error"); + return; + } + console.info("get P2P peer devices: " + JSON.stringify(data)); +}); - wifi.getP2pPeerDevices().then(data => { - console.info("get P2P peer devices: " + JSON.stringify(data)); - }); +wifi.getP2pPeerDevices().then(data => { + console.info("get P2P peer devices: " + JSON.stringify(data)); +}); ``` ## WifiP2pDevice8+ @@ -1707,22 +1712,22 @@ createGroup(config: WifiP2PConfig): boolean | boolean | true:创建群组操作执行成功, false:创建群组操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; - - try { - let config = { - deviceAddress: "****", - netId: 0, - passphrase: "*****", - groupName: "****", - goBand: 0 - } - wifi.createGroup(config); - - }catch(error){ - console.error("failed:" + JSON.stringify(error)); +```js +import wifi from '@ohos.wifi'; + +try { + let config = { + deviceAddress: "****", + netId: 0, + passphrase: "*****", + groupName: "****", + goBand: 0 } + wifi.createGroup(config); + +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## WifiP2PConfig8+ @@ -1770,14 +1775,14 @@ removeGroup(): boolean | boolean | true:操作执行成功, false:操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.removeGroup(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.removeGroup(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.p2pConnect8+ @@ -1805,71 +1810,71 @@ p2pConnect(config: WifiP2PConfig): boolean **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pConnectionChangeFunc = result => { - console.info("p2p connection change receive event: " + JSON.stringify(result)); - wifi.getP2pLinkedInfo((err, data) => { - if (err) { - console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); - return; - } - console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); - }); - } - wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); - - var recvP2pDeviceChangeFunc = result => { - console.info("p2p device change receive event: " + JSON.stringify(result)); - } - wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); - - var recvP2pPeerDeviceChangeFunc = result => { - console.info("p2p peer device change receive event: " + JSON.stringify(result)); - wifi.getP2pPeerDevices((err, data) => { - if (err) { - console.error('failed to get peer devices: ' + JSON.stringify(err)); - return; - } - console.info("get peer devices: " + JSON.stringify(data)); - var len = Object.keys(data).length; - for (var i = 0; i < len; ++i) { - if (data[i].deviceName === "my_test_device") { - console.info("p2p connect to test device: " + data[i].deviceAddress); - var config = { - "deviceAddress":data[i].deviceAddress, - "netId":-2, - "passphrase":"", - "groupName":"", - "goBand":0, - } - wifi.p2pConnect(config); - } - } - }); - } - wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - - var recvP2pPersistentGroupChangeFunc = () => { - console.info("p2p persistent group change receive event"); - - wifi.getCurrentGroup((err, data) => { - if (err) { - console.error('failed to get current group: ' + JSON.stringify(err)); - return; - } - console.info("get current group: " + JSON.stringify(data)); - }); - } - wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - - setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); - setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); - console.info("start discover devices -> " + wifi.startDiscoverDevices()); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); +} +wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + +var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); +} +wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + +var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); +} +wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + +var recvP2pPersistentGroupChangeFunc = () => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); +} +wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); +setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); +console.info("start discover devices -> " + wifi.startDiscoverDevices()); +``` ## wifi.p2pCancelConnect8+ @@ -1888,14 +1893,14 @@ p2pCancelConnect(): boolean | boolean | true:操作执行成功, false:操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.p2pCancelConnect(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.p2pCancelConnect(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.startDiscoverDevices8+ @@ -1915,14 +1920,14 @@ startDiscoverDevices(): boolean | boolean | true:操作执行成功, false:操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.startDiscoverDevices(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.startDiscoverDevices(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.stopDiscoverDevices8+ @@ -1942,14 +1947,14 @@ stopDiscoverDevices(): boolean | boolean | true:操作执行成功,操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - wifi.stopDiscoverDevices(); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + wifi.stopDiscoverDevices(); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.deletePersistentGroup8+ @@ -1978,15 +1983,15 @@ deletePersistentGroup(netId: number): boolean | boolean | true:操作执行成功,操作执行失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let netId = 0; - wifi.deletePersistentGroup(netId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let netId = 0; + wifi.deletePersistentGroup(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## WifiP2pGroupInfo8+ @@ -2033,15 +2038,15 @@ setDeviceName(devName: string): boolean | boolean | true:操作成功, false:操作失败。 | **示例:** -``` - import wifi from '@ohos.wifi'; +```js +import wifi from '@ohos.wifi'; - try { - let name = "****"; - wifi.setDeviceName(netId); - }catch(error){ - console.error("failed:" + JSON.stringify(error)); - } +try { + let name = "****"; + wifi.setDeviceName(netId); +}catch(error){ + console.error("failed:" + JSON.stringify(error)); +} ``` ## wifi.on('wifiStateChange')7+ @@ -2089,19 +2094,19 @@ off(type: "wifiStateChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvPowerNotifyFunc = result => { - console.info("Receive power state change event: " + result); - } - - // Register event - wifi.on("wifiStateChange", recvPowerNotifyFunc); - - // Unregister event - wifi.off("wifiStateChange", recvPowerNotifyFunc); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); +} + +// Register event +wifi.on("wifiStateChange", recvPowerNotifyFunc); + +// Unregister event +wifi.off("wifiStateChange", recvPowerNotifyFunc); +``` ## wifi.on('wifiConnectionChange')7+ @@ -2147,20 +2152,20 @@ off(type: "wifiConnectionChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 连接状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvWifiConnectionChangeFunc = result => { - console.info("Receive wifi connection change event: " + result); - } - - // Register event - wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); - - // Unregister event - wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvWifiConnectionChangeFunc = result => { + console.info("Receive wifi connection change event: " + result); +} + +// Register event +wifi.on("wifiConnectionChange", recvWifiConnectionChangeFunc); + +// Unregister event +wifi.off("wifiConnectionChange", recvWifiConnectionChangeFunc); +``` + ## wifi.on('wifiScanStateChange')7+ on(type: "wifiScanStateChange", callback: Callback<number>): void @@ -2204,20 +2209,20 @@ off(type: "wifiScanStateChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvWifiScanStateChangeFunc = result => { - console.info("Receive Wifi scan state change event: " + result); - } - - // Register event - wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); - - // Unregister event - wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvWifiScanStateChangeFunc = result => { + console.info("Receive Wifi scan state change event: " + result); +} + +// Register event +wifi.on("wifiScanStateChange", recvWifiScanStateChangeFunc); + +// Unregister event +wifi.off("wifiScanStateChange", recvWifiScanStateChangeFunc); +``` + ## wifi.on('wifiRssiChange')7+ on(type: "wifiRssiChange", callback: Callback<number>): void @@ -2254,20 +2259,19 @@ off(type: "wifiRssiChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvWifiRssiChangeFunc = result => { - console.info("Receive wifi rssi change event: " + result); - } - - // Register event - wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); - - // Unregister event - wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvWifiRssiChangeFunc = result => { + console.info("Receive wifi rssi change event: " + result); +} + +// Register event +wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); + +// Unregister event +wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); +``` ## wifi.on('hotspotStateChange')7+ on(type: "hotspotStateChange", callback: Callback<number>): void @@ -2295,20 +2299,19 @@ on(type: "hotspotStateChange", callback: Callback<number>): void | 3 | 去激活中。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvHotspotStateChangeFunc = result => { - console.info("Receive hotspot state change event: " + result); - } - - // Register event - wifi.on("hotspotStateChange", recvHotspotStateChangeFunc); - - // Unregister event - wifi.off("hotspotStateChange", recvHotspotStateChangeFunc); - ``` +```js +import wifi from '@ohos.wifi'; +var recvHotspotStateChangeFunc = result => { + console.info("Receive hotspot state change event: " + result); +} + +// Register event +wifi.on("hotspotStateChange", recvHotspotStateChangeFunc); + +// Unregister event +wifi.off("hotspotStateChange", recvHotspotStateChangeFunc); +``` ## wifi.off('hotspotStateChange')7+ @@ -2371,21 +2374,21 @@ off(type: "p2pStateChange", callback?: Callback<number>): void | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pStateChange"字符串。 | | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | - + **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pStateChangeFunc = result => { - console.info("Receive p2p state change event: " + result); - } - - // Register event - wifi.on("p2pStateChange", recvP2pStateChangeFunc); - - // Unregister event - wifi.off("p2pStateChange", recvP2pStateChangeFunc); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pStateChangeFunc = result => { + console.info("Receive p2p state change event: " + result); +} + +// Register event +wifi.on("p2pStateChange", recvP2pStateChangeFunc); + +// Unregister event +wifi.off("p2pStateChange", recvP2pStateChangeFunc); +``` ## wifi.on('p2pConnectionChange')8+ @@ -2423,20 +2426,20 @@ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pConnectionChangeFunc = result => { - console.info("Receive p2p connection change event: " + result); - } - - // Register event - wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); - - // Unregister event - wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvP2pConnectionChangeFunc = result => { + console.info("Receive p2p connection change event: " + result); +} + +// Register event +wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + +// Unregister event +wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc); +``` + ## wifi.on('p2pDeviceChange')8+ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void @@ -2473,20 +2476,20 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pDeviceChangeFunc = result => { - console.info("Receive recv p2p device change event: " + result); - } - - // Register event - wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); - - // Unregister event - wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc); - ``` - +```js +import wifi from '@ohos.wifi'; + +var recvP2pDeviceChangeFunc = result => { + console.info("Receive recv p2p device change event: " + result); +} + +// Register event +wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + +// Unregister event +wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc); +``` + ## wifi.on('p2pPeerDeviceChange')8+ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void @@ -2523,19 +2526,19 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pPeerDeviceChangeFunc = result => { - console.info("Receive recv p2p peer device change event: " + result); - } - - // Register event - wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - - // Unregister event - wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pPeerDeviceChangeFunc = result => { + console.info("Receive recv p2p peer device change event: " + result); +} + +// Register event +wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + +// Unregister event +wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); +``` ## wifi.on('p2pPersistentGroupChange')8+ @@ -2571,22 +2574,22 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pPersistentGroupChange"字符串。 | | callback | Callback<void> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | - + **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pPersistentGroupChangeFunc = result => { - console.info("Receive recv p2p persistent group change event: " + result); - } - - // Register event - wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - - // Unregister event - wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); - - ``` +```js +import wifi from '@ohos.wifi'; + +var recvP2pPersistentGroupChangeFunc = result => { + console.info("Receive recv p2p persistent group change event: " + result); +} + +// Register event +wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +// Unregister event +wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + +``` ## wifi.on('p2pDiscoveryChange')8+ @@ -2631,16 +2634,16 @@ off(type: "p2pDiscoveryChange", callback?: Callback<number>): void | callback | Callback<number> | 否 | 状态改变回调函数。如果callback不填,将取消注册该事件关联的所有回调函数。 | **示例:** - ```js - import wifi from '@ohos.wifi'; - - var recvP2pDiscoveryChangeFunc = result => { - console.info("Receive recv p2p discovery change event: " + result); - } - - // Register event - wifi.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); - - // Unregister event - wifi.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); - ``` \ No newline at end of file +```js +import wifi from '@ohos.wifi'; + +var recvP2pDiscoveryChangeFunc = result => { + console.info("Receive recv p2p discovery change event: " + result); +} + +// Register event +wifi.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); + +// Unregister event +wifi.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md index 1ae043ea9a5ac0040c5a62f0c8f8d667fc7c4696..2783c0acf161f5da292bce06987bc9a23e477de9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -31,7 +31,7 @@ Text(content?: string | Resource) | 名称 | 参数类型 | 描述 | | ----------------------- | ----------------------------------- | ------------------------------------------- | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式。
默认值:TextAlign.Start
说明:
文本段落宽度占满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属性可控制内容在水平方向的位置。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
当`overflow`设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。设置TextOverflow.None与TextOverflow.Clip效果一样。当`overflow`设置为TextOverflow.Marquee时,文本在一行内滚动显示,设置`maxLines`属性不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。
默认值:{overflow: TextOverflow.Clip}
**说明:**
文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。
当`overflow`设置为TextOverflow.None、TextOverflow.Clip、TextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。设置TextOverflow.None与TextOverflow.Clip效果一样。当`overflow`设置为TextOverflow.Marquee时,文本在一行内滚动显示,设置`maxLines`及`copyOption`属性均不生效。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | maxLines | number | 设置文本的最大行数。
默认值:Infinity
**说明:**
默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过 `textOverflow`来指定截断方式。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | lineHeight | string \| number \| [Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。
从API version 9开始,该接口支持在ArkTS卡片中使用。 | | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | 设置文本装饰线样式及其颜色。
默认值:{
type: TextDecorationType.None,
color:Color.Black
}
从API version 9开始,该接口支持在ArkTS卡片中使用。| diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index f389bd0adc81576ba9abebfc79137c182f8d9c4e..0144f1e59af3472a5c005c0f671ed27225dcca33 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -42,7 +42,7 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | showPasswordIcon9+ | boolean | 密码输入模式时,输入框末尾的图标是否显示。
默认值:true | | style9+ | [TextInputStyle](#textinputstyle9枚举说明) | 设置输入框为默认风格或内联输入风格。
默认值:TextInputStyle.Default | | textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | 设置输入文本在输入框中的对齐方式。
默认值:TextAlign.Start | -| selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置文本选中底板颜色。 | +| selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | 设置文本选中底板颜色。
如果未设置透明度,默认为不透明(例如:“0x80000000”为50%透明度黑色)。 | | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | 设置光标风格。 | | caretPosition10+ | number | 设置光标位置。 | diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md b/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md index 94683a9fbed9f6eec70f4d2aa26907d7495fecdc..2ee8c54182533f715403a4a0cade66fc1fc7cc42 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md @@ -1,4 +1,4 @@ -# 键鼠穿越管理错误码 +# 键鼠穿越管理错误码(待停用) > **说明:** > diff --git a/zh-cn/application-dev/ui/arkts-layout-development-media-query.md b/zh-cn/application-dev/ui/arkts-layout-development-media-query.md index 513f2b77efe02908cd6d40005847fd918a41e993..4a6cce279eb35495e6e797f05652f526651b00fe 100644 --- a/zh-cn/application-dev/ui/arkts-layout-development-media-query.md +++ b/zh-cn/application-dev/ui/arkts-layout-development-media-query.md @@ -110,12 +110,12 @@ listener.on('change', onPortrait); | 类型 | 说明 | | ----------------- | ---------------------------------------- | -| height | 应用页面可绘制区域的高度。 | -| min-height | 应用页面可绘制区域的最小高度。 | -| max-height | 应用页面可绘制区域的最大高度。 | -| width | 应用页面可绘制区域的宽度。 | -| min-width | 应用页面可绘制区域的最小宽度。 | -| max-width | 应用页面可绘制区域的最大宽度。 | +| height | 应用页面可绘制区域的高度。 | +| min-height | 应用页面可绘制区域的最小高度。 | +| max-height | 应用页面可绘制区域的最大高度。 | +| width | 应用页面可绘制区域的宽度。 | +| min-width | 应用页面可绘制区域的最小宽度。 | +| max-width | 应用页面可绘制区域的最大宽度。 | | resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
- dpi表示每英寸中物理像素个数,1dpi ≈ 0.39dpcm;
- dpcm表示每厘米上的物理像素个数,1dpcm ≈ 2.54dpi;
- dppx表示每个px中的物理像素数(此单位按96px = 1英寸为基准,与页面中的px单位计算方式不同),1dppx = 96dpi。 | | min-resolution | 设备的最小分辨率。 | | max-resolution | 设备的最大分辨率。 | diff --git a/zh-cn/application-dev/ui/figures/landscape.jpg b/zh-cn/application-dev/ui/figures/landscape.jpg index f82c49f882a9cc7b7f0398d9a4ccdf2fe8a3a92a..15c7505cf9669ed6bf9af406dc341716430e8741 100644 Binary files a/zh-cn/application-dev/ui/figures/landscape.jpg and b/zh-cn/application-dev/ui/figures/landscape.jpg differ diff --git a/zh-cn/application-dev/ui/figures/portralit.jpg b/zh-cn/application-dev/ui/figures/portralit.jpg index f656f49433be7787f9d0fbd9106cf6c9d366f25c..9b60d0bf27ae95f0359550fb857d1d916983654c 100644 Binary files a/zh-cn/application-dev/ui/figures/portralit.jpg and b/zh-cn/application-dev/ui/figures/portralit.jpg differ diff --git a/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md b/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md deleted file mode 100644 index f73f6c9398ade014d335277d4744f20e7725f279..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/pre-installed-app-config-and-Install.md +++ /dev/null @@ -1,60 +0,0 @@ -# 预置应用配置与安装指导 - -预置应用是指随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 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md b/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md index 4e86032eb3c5af9189a946ecea2a11b6d85c02af..3a7303a2bce1fb9b415f14139a5d5838178bfe9e 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md @@ -68,18 +68,3 @@ 安装完成后,当界面输出“DevEco Device Tool successfully installed.”时,表示DevEco Device Tool安装成功。 ![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为例。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md b/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md index 7468669d72dd3a528a1f45312383448d841ae652..9ad6c874391abe700815cc390bef0e1faca87563 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md @@ -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**创建新工程。 ![zh-cn_image_0000001272258726](figures/zh-cn_image_0000001272258726.png) diff --git a/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md b/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md index 920b47ea9c60fdb3b23b46419991764370ecb019..eb4a809978709dfdfa008d2cf5f4b05f1b042a12 100755 --- a/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-preinstall-app-config-guide.md @@ -1,35 +1,73 @@ -# 预置应用配置指南 +# 预置应用配置与安装指导 -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/为例。 -### 应用预置到系统中的配置步骤 +``` +hdc shell param get const.cust.config_dir_layer +``` + +2. 在install_list.json中配置hap在设备上的路径。 -1. 在预置目录下创建应用的名称作为应用目录 -2. 将应用预置到应用目录下,如 /system/app/Hiworld/entry.hap -3. 添加应用目录到[install_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list.json),根据需求配置removable +``` +hdc shell mount -o rw,remount / +hdc file recv /system/etc/app/install_list.json . +``` -### 示例 +3. 按照json中的配置方式,配置对应的字段。 ``` { "install_list" : [ { - "app_dir" : "/system/app/Hiworld", - "removable" : false // 是否可卸载 + "app_dir":"system/app/xxxx/yyyy", // 设备上的hap路径,如果不存在,需要手动创建,并推送hap到此目录。 + "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,在该文件中配置后,则对应的预置应用不会安装。 -### 示例一 +## 示例一 ``` /system/etc/app/uninstall_list.json @@ -39,7 +77,7 @@ OpenHarmony支持在不同产品上对预置应用进行差异化配置,设备 } ``` -### 示例二 +## 示例二 ``` /system/etc/app/uninstall_list.json