diff --git a/CODEOWNERS b/CODEOWNERS
index 025c30e10317662d65ab6b1d45688bf87ef41817..a98eba13b7b574232201efd76d84579561a42ccd 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -85,14 +85,19 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin
-zh-cn/device-dev/subsystems/subsys-boot-overview.md @Austin23
-zh-cn/device-dev/subsystems/subsys-boot-init.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23
-zh-cn/device-dev/subsystems/subsys-boot-appspawn-standard.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23
-zh-cn/device-dev/subsystems/subsys-boot-syspara.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-cfg.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-service.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init-sysparam.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-init.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot-overview.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-ref.md @Austin23
+zh-cn/device-dev/subsystems/subsys-boot.md @Austin23
zh-cn/device-dev/subsystems/subsys-testguide-test.md @Austin23
zh-cn/device-dev/subsystems/subsys-dfx-overview.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-dfx-hilog-rich.md @duangavin123_admin
diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md
index c9eff6c8fe752a73cc4b8a2837ffe2a8ee7c0f0f..1331ac52206cf1980ce59a7def62bfd32c27e406 100644
--- a/en/OpenHarmony-Overview.md
+++ b/en/OpenHarmony-Overview.md
@@ -1,202 +1,205 @@
# OpenHarmony Project
-## Introduction
+## Introduction
-OpenHarmony is an open-source project incubated and operated by the OpenAtom Foundation. It is an open-source operating system with a framework and platform applicable to smart devices in all scenarios of a fully-connected world. It aims to promote the development of the Internet of Everything (IoE).
+OpenHarmony is an open-source project incubated and operated by the OpenAtom Foundation. The purpose of this project is to build an open-source, distributed operating system (OS) framework for smart devices in all scenarios of a fully-connected world.
-## Technical Architecture
+## Technical Architecture
-OpenHarmony is designed with a layered architecture, which from bottom to top, consists of the kernel layer, system service layer, framework layer, and application layer. System functions are expanded by levels, from system to subsystem, and further to module. In a multi-device deployment scenario, unnecessary modules can be excluded from the system as required. The following figure shows the technical architecture of OpenHarmony.
+OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are expanded by levels, from system to subsystem, and further to component. In a multi-device deployment scenario, unnecessary components can be excluded from the system as required. The following figure shows the technical architecture of OpenHarmony.

**Kernel layer**
-- Kernel subsystem: OpenHarmony uses a multi-kernel design \(Linux or LiteOS\) so that different kernels can be selected for devices with different resource limitations. The kernel abstraction layer \(KAL\) hides differences in kernel implementations and provides the upper layer with basic kernel capabilities, including process and thread management, memory management, file system, network management, and peripheral management.
+- Kernel subsystem: OpenHarmony uses a multi-kernel design (Linux or LiteOS) so that different kernels can be selected for devices with different resource limitations. The kernel abstraction layer (KAL) hides differences in kernel implementations and provides the upper layer with basic kernel capabilities, including process and thread management, memory management, file system, network management, and peripheral management.
-- Driver subsystem: Hardware Driver Foundation \(HDF\) lays the foundation for an open OpenHarmony hardware ecosystem. It allows for unified access from peripheral devices and provides foundation for driver development and management.
+- Driver subsystem: Hardware Driver Foundation (HDF) lays the foundation for an open OpenHarmony hardware ecosystem. It allows for unified access from peripheral devices and provides foundation for driver development and management.
**System service layer**
-The system service layer provides a complete set of capabilities essential for OpenHarmony to offer services for apps through the framework layer. This layer consists of the following parts:
+The system service layer provides a complete set of capabilities essential for OpenHarmony to offer services for applications through the framework layer. This layer consists of the following parts:
-- Basic system capability subsystem set: Implements distributed app running, scheduling, and migration across OpenHarmony devices. This subsystem set provides the following basic capabilities: Distributed Soft Bus (DSoftBus), distributed data management, Distributed Scheduler, Utils, multimodal input, graphics, security, and AI.
+- Basic system capability subsystem set: Implements distributed application running, scheduling, and migration across OpenHarmony devices. This subsystem set provides the following basic capabilities: Distributed Soft Bus (DSoftBus), distributed data management, Distributed Scheduler, Utils, multimodal input, graphics, security, and AI.
-- Basic software service subsystem set: Provides OpenHarmony with common universal software services, including common event and notification, telephony, multimedia, and Design For X \(DFX\).
+- Basic software service subsystem set: Provides OpenHarmony with common universal software services, including common event and notification, telephony, multimedia, and Design For X (DFX).
-- Enhanced software service subsystem set: Provides OpenHarmony with differentiated enhanced software services, including those dedicated to smart TVs, wearables, IoT devices, and more.
+- Enhanced software service subsystem set: Provides OpenHarmony with differentiated enhanced software services, including those dedicated to smart TVs, wearables, IoT devices, and more.
-- Hardware service subsystem set: Provides OpenHarmony with hardware services, including location, IAM, as well as those dedicated to wearables and IoT devices.
+- Hardware service subsystem set: Provides OpenHarmony with hardware services, including location, user IAM, as well as those dedicated to wearables and IoT devices.
-The basic software service, enhanced software service, and hardware service subsystem sets can be modified by the subsystems, and each subsystem can be modified by various functions, depending on the deployment scenario for a particular device form.
+The basic software service, enhanced software service, and hardware service subsystem sets can be tailored by subsystems, and each subsystem can be tailored by functions, depending on the deployment scenario for a particular device form.
**Framework layer**
-This layer provides with what you need to develop OpenHarmony apps: application framework and ability framework, specific to multiple languages \(like C, C++, and JS\), ArkUI framework, as well as multi-language APIs for hardware and software services. The APIs designed for different OpenHarmony devices can be modified based on various system components.
+This layer provides with what you need to develop OpenHarmony applications: application framework and ability framework specific to multiple languages (like C, C++, and JS), JS-specific ArkUI framework, as well as multi-language APIs for hardware and software services. The APIs designed for different OpenHarmony devices vary according to the components in use.
**Application layer**
-This layer consists of system apps and third-party apps. Each OpenHarmony app is powered by one or more Feature Abilities \(FAs\) or Particle Abilities \(PAs\). An FA provides a UI for user interaction. A PA has no UI and provides background task processing as well as data access. Apps developed based on FAs and PAs provide specific service characteristics and enable cross-device scheduling and distribution, delighting users with consistent and efficient experience.
+This layer consists of system applications and third-party applications. Each OpenHarmony application is powered by one or more Feature Abilities (FAs) or Particle Abilities (PAs). An FA provides a UI for user interaction. A PA has no UI and provides background task processing as well as data access. Applications developed based on FAs and PAs provide specific service characteristics and enable cross-device scheduling and distribution, delighting users with consistent and efficient experience.
-## Technical Features
+## Technical Features
**Hardware collaboration and resource sharing**
This feature is implemented through the following modules:
-- DSoftBus
+- DSoftBus
- DSoftBus is a unified base for seamless interconnection among devices. It powers OpenHarmony with distributed communication capabilities to quickly discover and connect devices, and efficiently transmit data.
+ DSoftBus is a unified base for seamless interconnection among devices. It powers OpenHarmony with distributed communication capabilities to quickly discover and connect devices, and efficiently transmit data.
-- Distributed data management
-
- DSoftBus manages apps and user data distributed across different devices. Under such management, user data is no longer bound to a single physical device, and service logic is decoupled from storage. As your apps are running across devices, their data is seamlessly transmitted from one device to another, creating a foundation for a user experience that is smooth and consistent.
-- Distributed Scheduler
-
- The Distributed Scheduler is designed based on technical features such as DSoftBus, distributed data management, and distributed profile. It builds a unified distributed service management mechanism \(including service discovery, synchronization, registration, and invocation\), and supports remote startup, remote invocation, binding/unbinding, and migration of apps across devices. This way, your app can select the most suitable device to perform distributed tasks based on the capabilities, locations, running status, and resource usage of different devices, as well as user habits and intentions.
+- Distributed data management
+
+ Distributed data management leverages DSoftBus to manage application data and user data distributed on different devices. Under such management, user data is no longer bound to a single physical device, and service logic is decoupled from storage. As your applications are running across devices, their data is seamlessly transmitted from one device to another, creating a foundation for a user experience that is smooth and consistent.
-- Device virtualization
-
- A distributed device virtualization platform enables cross-device resource convergence, device management, and data processing so that virtual peripherals can function as capability extensions of smartphones to form a super virtual terminal.
+
+- Distributed Scheduler
+
+ Distributed Scheduler is designed based on technical features such as DSoftBus, distributed data management, and distributed profile. It builds a unified distributed service management mechanism (including service discovery, synchronization, registration, and invocation), and supports remote startup, remote invocation, binding/unbinding, and migration of applications across devices. This way, your application can select the most suitable device to perform distributed tasks based on the capabilities, locations, running status, and resource usage of different devices, as well as user habits and intentions.
+
+
+- Device virtualization
+
+ A distributed device virtualization platform enables cross-device resource convergence, device management, and data processing so that virtual peripherals can function as capability extensions of smartphones to form a Super Device.
**One-time development for multi-device deployment**
-OpenHarmony provides you with the user application, ability, and UI frameworks. With these frameworks, you can develop your apps once, and then flexibly deploy them across a broad range of different devices.
+OpenHarmony provides you with the application, ability, and UI frameworks. With these frameworks, you can develop your applications once, and then flexibly deploy them across a broad range of different devices. One-time development for multi-device deployment
-Consistent APIs ensure the operational compatibility of apps across devices.
+Consistent APIs ensure the operational compatibility of applications across devices.
-- Adaptation of device capabilities \(including CPU, memory, peripheral, and software resources\) can be previewed.
-- Resources can be scheduled based on the compatibility between user apps and the software platform.
+- Adaptation of device capabilities (including CPU, memory, peripheral, and software resources) can be previewed.
+- Resources can be scheduled based on the compatibility between applications and the software platform.
**A unified OS for flexible deployment**
OpenHarmony enables hardware resources to be scaled with its component-based and small-scale designs. It can be deployed on demand for a diverse range of devices, including ARM, RISC-V, and x86 architectures, and providing RAM volumes ranging from hundreds of KiB to GiB.
-## OS Types
+## System Types
-OpenHarmony supports the following types:
+OpenHarmony supports the following system types:
-- Mini system
+- Mini system
- A mini system runs on the devices whose memory is greater than or equal to 128 KiB and that are equipped with MCU processors such as Arm Cortex-M and 32-bit RISC-V. This system provides multiple lightweight network protocols and graphics frameworks, and a wide range of read/write components for the IoT bus. Typical products include connection modules, sensors, and wearables for smart home.
+ A mini system fits into devices that come with Micro Controller Units (MCUs), such as Arm Cortex-M and 32-bit RISC-V processors, and memory greater than or equal to 128 KiB. This system provides multiple lightweight network protocols, a lightweight graphics framework, and a wide range of read/write components with the IoT bus. Typical products include connection modules, sensors, and wearables for smart home.
-- Small system
+- Small system
- A small system runs on the devices whose memory is greater than or equal to 1 MiB and that are equipped with application processors such as Arm Cortex-A. This system provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, routers, and event data recorders \(EDRs\) for smart travel.
+ A small system runs on devices whose memory is greater than or equal to 1 MiB and that are equipped with application processors such as Arm Cortex-A. This system provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders (EDRs) for easy travel.
-- Standard system
+- Standard system
- A standard system runs on the devices whose memory is greater than or equal to 128 MiB and that are equipped with application processors such as Arm Cortex-A. This system provides a complete application framework supporting the enhanced interaction, 3D GPU, hardware composer, diverse components, and rich animations. This system applies to high-end refrigerator displays.
+ A standard system runs on devices whose memory is greater than or equal to 128 MiB and that are equipped with application processors such as Arm Cortex-A. This system provides a complete application framework supporting the enhanced interaction, 3D GPU, hardware composer, diverse components, and rich animations. This system applies to high-end refrigerator displays.
-## Subsystems
+## Subsystems
You need to understand the following basic concepts related to OpenHarmony:
-- Subsystem
+- Subsystem
- OpenHarmony is designed with a layered architecture, which from bottom to top consists of the kernel layer, system service layer, framework layer, and application layer. System functions are expanded by levels, from system to subsystem, and further to module. In a multi-device deployment scenario, unnecessary modules can be excluded from the system as required. A subsystem is a logical concept and is a flexible combination of functions.
+ OpenHarmony is designed with a layered architecture, which consists of the kernel layer, system service layer, framework layer, and application layer from the bottom up. System functions are expanded by levels, from system to subsystem, and further to component. In a multi-device deployment scenario, unnecessary components can be excluded from the system as required. A subsystem, as a logical concept, consists of the least required components.
-- Module
+- Components
- A module is a reusable software binary unit that contains source code, configuration files, resource files, and build scripts. A module can be built independently, integrated in binary mode, and then tested independently.
+ A component is a reusable software binary unit that contains source code, configuration files, resource files, and build scripts. A component can be built independently, integrated in binary mode, and then tested independently.
-The following table describes the subsystems of OpenHarmony. For details about the readme files of these subsystems, see [https://gitee.com/openharmony/docs/tree/master/en/readme](https://gitee.com/openharmony/docs/tree/master/en/readme).
+The following table describes the subsystems of OpenHarmony. For details about the readme files of these subsystems, see [https://gitee.com/openharmony/docs/tree/master/en/readme](https://gitee.com/openharmony/docs/tree/master/en/readme).
-| Subsystem| Description| Applicable To|
+
+| Subsystem | Description | Application Scope |
| -------- | -------- | -------- |
-| Kernel| Supports small-sized LiteOS kernels that provide high performance and low power consumption for embedded devices and devices with limited resources, and supports Linux kernels that are applicable to the standard system.| Small system
Standard system |
-| Distributed File System | Provides APIs for synchronizing local JS files. | Standard system |
-| Graphics | Consists of user interface (UI) components, layout, animator, font, input event, window management, and rendering and drawing modules. It is an application framework that can be built on the LiteOS to develop OpenHarmony applications for Internet of Things (IoT) devices with limited hardware resources or on the standard OS to develop OpenHarmony applications for standard- and large-system devices (for example, tablet and lite smart devices). | All systems |
-| Driver | Constructed using the C object-oriented programming (OOP) language. It provides a unified driver platform and is compatible with different kernels by means of platform decoupling and kernel decoupling. This unified driver platform is designed to provide a more precise and efficient development environment, where you develop a driver that can be deployed on different systems supporting HDF. | All systems |
-| Power Management | Provides the following functions: restarting the system, managing running locks, managing and querying the system power status, querying and reporting the charging and battery status, and turning on/off the device screen, including adjusting the screen brightness. | Standard system |
-| Pan-sensor | Contains sensors and misc devices. A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another electronic device. Misc devices, including vibrators and LED lights, are used to send signals externally. You can call APIs to control the vibration of vibrators and lighting-on and lighting-off of LED lights. | Small system |
-| Multimodal Input | OpenHarmony provides a Natural User Interface (NUI) for you to interact with your users. Unlike conventional categorization of input methods, OpenHarmony combines input methods of different dimensions into multimodal inputs, so you can easily arm your app with multi-dimensional, natural interaction features by using the application framework and system built-in UI components or APIs. Specifically, OpenHarmony currently supports traditional input methods such as key and touch inputs. | Standard system |
-| Startup | Starts the OS middle layer between the time the kernel is started and the time apps are started. In addition, you can query and modify system attributes and restore factory settings. | All systems |
-| Update | Supports over the air (OTA) update of OpenHarmony devices. | Standard system |
-| Account | Provides interconnection with vendors' cloud account apps on the device side, and query and update of the cloud account login status. | Standard system |
-| Compilation and Building | Provides a compilation and building framework based on Generate Ninja (GN) and Ninja. | All systems |
-| Test | The test-driven development mode is used during the development process. You can develop new cases or modify existing cases to test new or enhanced system features. The test helps you develop high-quality code in the development phase. | All systems |
-| Data Management | Provides local data management and distributed data management:
- Local app data management for lightweight preference databases and relational databases
- Distributed data service to provide apps with the capability to store data in the databases of different devices | Standard system |
-| Programming Language Runtime | Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools. | All systems |
-| Distributed Scheduler | Starts, registers, queries, and manages system services. | All systems |
-| JS UI framework | OpenHarmony UI development framework that supports web-development-like paradigm. | All systems |
-| Multimedia | Provides easy-to-use APIs for developing multimedia components such as audio, video, and camera, and enables apps to use multimedia resources of the system. | All systems |
-| Common Event and Notification | Provides the common event management capabilities that allow apps to subscribe to, unsubscribe from, publish, and receive common events (such as screen-on/off events and USB device attachment/detachment events). | Standard system |
-| Misc Services | Provides the function of setting the time. | Standard system |
-| Bundle management | Provides bundle installation, uninstall, update, and query capabilities. | All systems |
-| Telephony | Provides basic communication capabilities of the cellular network, such as SIM cards, network search, cellular data, cellular calls, SMS, and MMS, as well as easy-to-use APIs for you to manage multiple types of calls and data network connections. | Standard system |
-| Utils | Stores basic OpenHarmony components, which can be used by OpenHarmony subsystems and upper-layer apps. | All systems |
-| Development Tools | Provides a performance profiler platform for you to analyze system issues such as memory and performance, including hdc used for device debugging, APIs for performance tracing, and a performance profiler framework. | Standard system |
-| DSoftBus | Provides cross-process or cross-device communication capabilities for the OpenHarmony system and consists of the DSoftBus and IPC modules. The DSoftBus module enables distributed communication between near-field devices and provides device discovery, connection, networking, and data transmission functions, regardless of the communication mode. The IPC module enables communication between processes on a device or across devices. | All systems |
-| XTS | Provides a set of OpenHarmony compatibility test suites, including the currently supported application compatibility test suite (ACTS) and the device compatibility test suite (DCTS) that will be supported in the future. | All systems |
-| System Apps | Provides system apps that are applicable to the OpenHarmony standard system, such as Launcher, SystemUI, and Settings. It also provides specific examples for you to build standard-system apps, which can be installed on all devices running the standard system. | Standard system |
-| DFX | Provides non-functional capabilities of OpenHarmony. It provides a logging system, app and system event logging APIs, the event log subscription service, and fault information generation and collection capabilities. | All systems |
-| Globalization | If OpenHarmony devices and apps need to be used globally, they must meet the requirements of users in different regions on languages and cultures. The Globalization subsystem provides multi-language and multi-cultural capabilities for global use, including resource management and internationalization (i18n). | All systems |
-| Security | Provides system, data, and app security capabilities to protect system and user data of OpenHarmony. Its functions include app integrity verification, app permission management, device authentication, and key management. | All systems |
-
-## Supported Development Boards
-
-Currently, OpenHarmony supports the development boards listed in the following table.
-
-| System Type| Board Model| Chip Model| Function Description| Application Scenario| Code Repository and Daily Build|
+| Kernel | Supports small-sized LiteOS kernels that provide high performance and low power consumption for embedded devices and devices with limited resources, and supports Linux kernels that are applicable to the standard system.| Small System
Standard System|
+| Distributed File System | Provides APIs for synchronizing local JS files. | Standard system |
+| Graphics | Consists of user interface (UI) components, layout, animator, font, input event, window management, and rendering modules. It is an application framework that can be built on the LiteOS to develop OpenHarmony applications for IoT devices with limited hardware resources or on the standard OS to develop OpenHarmony applications for standard- and large-system devices (for example, tablet and lite smart devices).| All systems |
+| Driver | Constructed using the C object-oriented programming (OOP) language. It provides a unified driver platform and is compatible with different kernels by means of platform decoupling and kernel decoupling. This unified driver platform is designed to provide a more precise and efficient development environment, where you develop a driver that can be deployed on different systems supporting HDF.| All systems |
+| Power Management | Provides the following functions: restarting the system, managing running locks, managing and querying the system power status, querying and reporting the charging and battery status, and turning on/off the device screen, including adjusting the screen brightness.| Standard system |
+| Pan-sensor | Contains sensors and misc devices. A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another electronic device. Misc devices, including vibrators and LED lights, are used to send signals externally. You can call APIs to control the vibration of vibrators and lighting-on and lighting-off of LED lights.| Small system |
+| Multimodal Input | OpenHarmony provides a Natural User Interface (NUI) for you to interact with your users. Unlike conventional categorization of input methods, OpenHarmony combines input methods of different dimensions into multimodal inputs, so you can easily arm your application with multi-dimensional, natural interaction features by using the application framework and system built-in UI components or APIs. Specifically, OpenHarmony currently supports traditional input methods such as key and touch inputs.| Standard system |
+| Startup | Starts the OS middle layer between the time the kernel is started and the time applications are started. In addition, you can query and modify system attributes and restore factory settings.| All systems |
+| Update | Supports over the air (OTA) update of OpenHarmony devices. | Standard system |
+| Account | Provides interconnection with vendors' cloud account applications on the device side, and query and update of the cloud account login status.| Standard system |
+| Build | Provides a compilation and building framework based on Generate Ninja (GN) and Ninja. | All systems |
+| Test | The test-driven development mode is used during the development process. You can develop new cases or modify existing cases to test new or enhanced system features. The test helps you develop high-quality code in the development phase.| All systems |
+| Data Management | Provides local data management and distributed data management:
- Local application data management for lightweight preference databases and relational databases
- Distributed data service to provide applications with the capability to store data in the databases of different devices| Standard system |
+| Programming Language Runtime| Provides the compilation and execution environment for programs developed with JavaScript or C/C++, basic libraries that support the runtime, and the runtime-associated APIs, compilers, and auxiliary tools.| All systems |
+| Distributed Scheduler| Starts, registers, queries, and manages system services. | All systems |
+| JS UI Framework | OpenHarmony JS UI framework supports web-development-like paradigm. | All systems |
+| Multimedia | Provides easy-to-use APIs for developing multimedia components such as audio, video, and camera, and enables applications to use multimedia resources of the system.| All systems |
+| Common Event and Notification | Provides the common event management capabilities that allow applications to subscribe to, unsubscribe from, publish, and receive common events (such as screen-on/off events and USB device attachment/detachment events).| Standard system |
+| Misc Services | Provides the function of setting the time. | Standard system |
+| Bundle Management | Provides bundle installation, uninstall, update, and query capabilities. | All systems |
+| Telephony | Provides basic communication capabilities of the cellular network, such as SIM cards, network search, cellular data, cellular calls, SMS, and MMS, as well as easy-to-use APIs for you to manage multiple types of calls and data network connections.| Standard system |
+| Utils | Stores basic components of OpenHarmony, which can be used by OpenHarmony subsystems and upper-layer applications.| All systems |
+| Development Tools | Provides a performance profiler platform for you to analyze system issues such as memory and performance, including hdc used for device debugging, APIs for performance tracing, and a performance profiler framework.| Standard system |
+| DSoftBus | Provides cross-process or cross-device communication capabilities for the OpenHarmony system and consists of the DSoftBus and IPC modules. The DSoftBus module enables distributed communication between near-field devices and provides device discovery, connection, networking, and data transmission functions, regardless of the communication mode. The IPC module enables communication between processes on a device or across devices.| All systems |
+| XTS | Provides a set of OpenHarmony compatibility test suites, including the currently supported application compatibility test suite (ACTS) and the device compatibility test suite (DCTS) that will be supported in the future.| All systems |
+| System Apps | Provides system apps that are applicable to the OpenHarmony standard system, such as Home Screen, SystemUI, and Settings. It also provides specific examples for you to build standard-system applications, which can be installed on all devices running the standard system.| Standard system |
+| DFX | Provides non-functional capabilities of OpenHarmony. It provides a logging system, application and system event logging APIs, the event log subscription service, and fault information generation and collection capabilities.| All systems |
+| Globalization | If OpenHarmony devices and applications need to be used globally, they must meet the requirements of users in different regions on languages and cultures. The Globalization subsystem provides multi-language and multi-cultural capabilities for global use, including resource management and internationalization (i18n).| All systems |
+| Security | Provides system, data, and application security capabilities to protect system and user data of OpenHarmony. Its functions include application integrity verification, application permission management, device authentication, and key management.| All systems |
+
+## Supported Development Boards
+
+Currently, the OpenHarmony community supports 17 types of development boards, which are listed in [Development Boards Supported](device-dev/dev-board-on-the-master.md). The following table describes three of them, which are the first three integrated into the OpenHarmony master. You can visit http://ci.openharmony.cn/dailys/dailybuilds to obtain daily builds.
+
+| System Type| Board Model| Chip Model|
Function Description and Use Case
| Application Scenario| Code Repository |
| -------- | -------- | -------- | -------- | -------- | -------- |
-| Standard system| Hi3516DV300 | Hi3516DV300 | Hi3516D V300 is a the next-generation system on chip (SoC) for smart HD IP cameras. It integrates the next-generation image signal processor (ISP), H.265 video compression encoder, and high-performance NNIE engine, and delivers exceptional performance in terms of low bit rate, high image quality, intelligent processing and analysis, and low power consumption.| Devices with screens, such as refrigerators and head units.| Code repositories:
[device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)
[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
-| Standard system| Runhe HH-SCDAYU200| RK3568 | Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates a dual-core GPU and high-efficiency NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, WiFi, audio, video, and camera features, with a wide range of expansion ports as well as video input and output ports. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.| Video and audio entertainment, smart travel, and smart home, such as kitchen hoods, ovens, and treadmills.| Code repositories:
[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
-| Lightweight| Goodix GR5515-STARTER-KIT| GR5515 | The GR5515-STARTER-KIT development board is a Bluetooth 5.1-capable single-mode Bluetooth low energy (BLE) SoC and comes with multifunctional keys and LED indicators.| Smart hardware, such as watches, wristbands, and price tags.| Code repositories:
[device_soc_goodix](https://gitee.com/openharmony/device_soc_goodix)
[device_board_goodix](https://gitee.com/openharmony/device_board_goodix)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
-| Lightweight| Langguo LANGO200| ASR582X | The LANGO200 IoT development board integrates the high-performance WiFi-BLE dual-mode chip ASR5822, external storage chip, voice playing chip, and analog-to-digital converter. It supports common peripheral interfaces like SPI, and can be connected to an external OLED display and infrared remote control.| Connection modules for smart home products.| Code repositories:
[device_soc_asrmicro](https://gitee.com/openharmony/device_soc_asrmicro)
[device_board_lango](https://gitee.com/openharmony/device_board_lango)
[vendor_asrmicro](https://gitee.com/openharmony/vendor_asrmicro)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
-| Lightweight| Fn-Link multi-modal V200ZR| BES2600 | The multi-modal V200Z-R development board is a high-performance, multi-functional, and cost-effective AIoT SoC powered by the BES2600WM chip of Bestechnic. It integrates a quad-core Arm processor with a frequency of up to 1 GHz as well as dual-mode WiFi and dual-mode Bluetooth. The board supports the 802.11 a/b/g/n/ and BT/BLE 5.2 standards. It is able to accommodate RAM of up to 42 MB and flash memory of up to 32 MB, and supports the MIPI display serial interface (DSI) and camera serial interface (CSI). It is applicable to various AIoT multi-modal VUI and GUI interaction scenarios.| Smart hardware with screens, such as speakers and watches.| Code repositories:
[device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)
[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)
[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
-| Lightweight| BearPi-HM_Nano| Hi3861 | The BearPi-HM_Nano development board is specially designed for OpenHarmony. It is equipped with the highly integrated 2.4 GHz WiFi SoC chip Hi3861, near field communication (NFC) circuits, and standard E53 interfaces, which can be used to connect to smart humidifiers, smart desk lamps, smart security facilities, and intelligent smoke detectors.| Connection devices like smart street lamps, smart logistics sensors, and human body infrared sensors.| Code repositories:
[device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_bearpi](https://gitee.com/openharmony/device_board_bearpi)
[vendor_bearpi](https://gitee.com/openharmony/vendor_bearpi)
Daily build:
http://ci.openharmony.cn/dailys/dailybuilds |
+| Standard system| Runhe HH-SCDAYU200| RK3568 | Function description:
Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates the dual-core GPU and efficient NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, Wi-Fi, audio, video, and camera features, with a wide range of expansion ports to accommodate various video input and outputs. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.
Use case:
[DAYU200 Use Case](device-dev/porting/porting-dayu200-on_standard-demo.md)
| Entertainment, easy travel, and smart home, such as kitchen hoods, ovens, and treadmills.| [device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
|
+| Small system| Hispark_Taurus | Hi3516DV300 | Function Description:
Hi3516D V300 is the next-generation system on chip (SoC) for smart HD IP cameras. It integrates the next-generation image signal processor (ISP), H.265 video compression encoder, and high-performance NNIE engine, and delivers high performance in terms of low bit rate, high image quality, intelligent processing and analysis, and low power consumption.
| Smart device with screens, such as refrigerators with screens and head units.| [device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)
[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon)
|
+| Mini system| Multi-modal V200Z-R | BES2600 | Function description:
The multi-modal V200Z-R development board is a high-performance, multi-functional, and cost-effective AIoT SoC powered by the BES2600WM chip of Bestechnic. It integrates a quad-core ARM processor with a frequency of up to 1 GHz as well as dual-mode Wi-Fi and dual-mode Bluetooth. The board supports the 802.11 a/b/g/n/ and BT/BLE 5.2 standards. It is able to accommodate RAM of up to 42 MB and flash memory of up to 32 MB, and supports the MIPI display serial interface (DSI) and camera serial interface (CSI). It is applicable to various AIoT multi-modal VUI and GUI interaction scenarios.
Use case:
[Multi-modal V200Z-R Use Case](device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md)
| Smart hardware, and smart devices with screens, such as speakers and watches.| [device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)
[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)
[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic)
|
-## Getting Started
+## Getting Started
- [Getting Started for Device Development](device-dev/quick-start/quickstart-ide-lite-overview.md)
- [Getting Started for Application Development](application-dev/quick-start/start-overview.md)
-## Code Repository Addresses
-OpenHarmony project: [https://gitee.com/openharmony](https://gitee.com/openharmony)
-OpenHarmony SIG: [https://gitee.com/openharmony-sig](https://gitee.com/openharmony-sig)
+## Code Repository Addresses
+
+OpenHarmony project: [https://gitee.com/openharmony](https://gitee.com/openharmony)
+
+OpenHarmony SIGs: [https://gitee.com/openharmony-sig](https://gitee.com/openharmony-sig)
-OpenHarmony third-party components: [https://gitee.com/openharmony-tpc](https://gitee.com/openharmony-tpc)
+OpenHarmony third-party components: [https://gitee.com/openharmony-tpc](https://gitee.com/openharmony-tpc)
-OpenHarmony archived projects: [https://gitee.com/openharmony-retired](https://gitee.com/openharmony-retired)
+OpenHarmony archived projects: [https://gitee.com/openharmony-retired](https://gitee.com/openharmony-retired)
-## OpenHarmony Documentation
+## OpenHarmony Documentation
-[Chinese version](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme.md)
+[Chinese version](https://gitee.com/openharmony/docs/tree/master/zh-cn)
-[English version](https://gitee.com/openharmony/docs/blob/master/en/readme.md)
+[English version](https://gitee.com/openharmony/docs/tree/master/en)
-## Source Code Downloading
+## Source Code Downloading
-For details about how to obtain the source code of OpenHarmony, see [Source Code Acquisition](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/sourcecode-acquire.md).
+For details about how to obtain the source code of OpenHarmony, see [Source Code Acquisition](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/sourcecode-acquire.md)
-## Hands-On Tutorials
+## Hands-On Tutorials
[Samples](https://gitee.com/openharmony/app_samples)
[Codelabs](https://gitee.com/openharmony/codelabs)
-## How to Participate
+## How to Participate
-For details about how to join in the OpenHarmony community, see [OpenHarmony Community](https://gitee.com/openharmony/community/blob/master/README-EN.md).
+For details about how to join in the OpenHarmony community, see [OpenHarmony Community](https://gitee.com/openharmony/community/blob/master/README-EN.md)
-For details about how to contribute, see [How to Contribute](contribute/how-to-contribute.md).
+For details about how to contribute, see [How to contribute](contribute/how-to-contribute.md).
-## License Agreement
+## License Agreement
OpenHarmony complies with Apache License Version 2.0. For details, see the LICENSE in each repository.
-OpenHarmony uses third-party open-source software and licenses. For details, see [Third-Party Open-Source Software](https://gitee.com/openharmony/docs/blob/master/en/contribute/third-party-open-source-software-and-license-notice.md).
+OpenHarmony uses third-party open-source software and licenses. For details, see [Third-Party Open-Source Software](https://gitee.com/openharmony/docs/blob/master/en/contribute/third-party-open-source-software-and-license-notice.md).
-## Contact Info
+## Contact Info
Website:
diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability/ability-brief.md
index 187064a1c67d7bd21c823a945cca79366428d3f8..9943d4d697fa787db084fc14848d37abdad90fe9 100644
--- a/en/application-dev/ability/ability-brief.md
+++ b/en/application-dev/ability/ability-brief.md
@@ -4,8 +4,8 @@ An ability is the abstraction of a functionality that an application can provide
The ability framework model has two forms.
-- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
-- Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
+- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
+- Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
diff --git a/en/application-dev/ability/figures/fa-package-info.png b/en/application-dev/ability/figures/fa-package-info.png
deleted file mode 100644
index 86da707408da8fdb149ea62d92298fed605132ca..0000000000000000000000000000000000000000
Binary files a/en/application-dev/ability/figures/fa-package-info.png and /dev/null differ
diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md
index c07f787d38091637215907537e54812c397a417e..7065480d1c4a12bd0984f4916d678c1bed7a4997 100644
--- a/en/application-dev/application-dev-guide.md
+++ b/en/application-dev/application-dev-guide.md
@@ -54,8 +54,14 @@ To make you better understand how functions work together and jumpstart your app
API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively.
They are organized as follows:
-- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
-- Native APIs
- - [Standard Library](reference/native-lib/third_party_libc/musl.md)
- - [Node_API](reference/native-lib/third_party_napi/napi.md)
+
+- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
+
+- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
+
+- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md)
+
+- Native APIs
+ - [Standard Library](reference/native-lib/third_party_libc/musl.md)
+ - [Node_API](reference/native-lib/third_party_napi/napi.md)
diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md
index 3d541e4832aa72a585972d327e2fb2f31a077fa6..1fddf868604e564e4b6a6701f8d3a8088c4d8326 100644
--- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md
+++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md
@@ -8,37 +8,11 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
**Table 1** Native IPC APIs
-
-Class/Interface
- |
-Function
- |
-Description
- |
-
-
-IRemoteBroker
- |
-sptr<IRemoteObject> AsObject()
- |
-Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of IRemoteBroker. If you call this method on the stub, the RemoteObject is returned; if you call this method on the proxy, the proxy object is returned.
- |
-
-IRemoteStub
- |
-virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
- |
-Called to process a request from the proxy and return the result. Derived classes need to override this method.
- |
-
-IRemoteProxy
- |
- |
-Service proxy classes are derived from the IRemoteProxy class.
- |
-
-
-
+| Class/Interface | Function | Description |
+| --------------- | -------- | ----------- |
+| IRemoteBroker | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. |
+| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. |
+| IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. |
## How to Develop
diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md
index fa70738556ec7992c33fd8bcf3e74fbd6145fcb6..8d9365d6bbba940bb85d9ac7493b7069c48845eb 100755
--- a/en/application-dev/connectivity/subscribe-remote-state.md
+++ b/en/application-dev/connectivity/subscribe-remote-state.md
@@ -1,25 +1,30 @@
-# Subscribing to State Changes of a Remote Object
+# Subscribing to State Changes of a Remote Object
-IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. You can also unsubscribe from the state changes if they are no longer needed. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **IRemoteObject.DeathRecipient** interface and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
+IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** callback and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network.
-**Development Using Native APIs**
+Note that the proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
-The following APIs are used to add a recipient for death notifications of a remote stub object, remove such a recipient, and perform subsequent operations upon receiving a death notification of the remote stub object:
-```
-bool AddDeathRecipient(const sptr &recipient);
-bool RemoveDeathRecipient(const sptr &recipient);
-void OnRemoteDied(const wptr &object);
-```
-The sample code is as follows:
+
+## **Development Using Native APIs**
+
+| API| Description|
+| -------- | -------- |
+| AddDeathRecipient(const sptr\ &recipient); | Adds a recipient for death notifications of a remote stub object.|
+| RemoveDeathRecipient(const sptr\ &recipient); | Removes the recipient for death notifications of a remote stub object.|
+| OnRemoteDied(const wptr\ &object); | Called when the remote stub object dies.|
+
+
+## Sample Code
+
```
class TestDeathRecipient : public IRemoteObject::DeathRecipient {
public:
virtual void OnRemoteDied(const wptr& remoteObject);
}
-sptr deathRecipient (new TestDeathRecipient()); // Construct a death notification recipient.
-bool result = proxy->AddDeathRecipient(deathRecipient); // Add the recipient to the proxy.
-result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient.
+sptr deathRecipient (new TestDeathRecipient());// Construct a death notification recipient.
+bool result = proxy->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications.
+result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications.
```
diff --git a/en/application-dev/connectivity/websocket-connection.md b/en/application-dev/connectivity/websocket-connection.md
index 01f5f38fad74e234c8a9fb483ee4a11ae2a8c7a7..b68d537fc5ad96f3ab60b53e2e75a96d7b555f76 100644
--- a/en/application-dev/connectivity/websocket-connection.md
+++ b/en/application-dev/connectivity/websocket-connection.md
@@ -3,7 +3,7 @@
## Use Cases
-You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket** API to create a **WebSocket** object and then use the **connect** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
+You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
@@ -18,14 +18,14 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
| connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. |
| close() | Closes a WebSocket connection. |
-| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
-| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
-| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
-| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
-| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
-| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
-| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
-| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
+| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
+| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
+| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
+| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
+| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
+| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
+| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
+| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
## How to Develop
@@ -50,9 +50,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => {
if (!err) {
- console.log("send success");
+ console.log("Message sent successfully");
} else {
- console.log("send fail, err:" + JSON.stringify(err));
+ console.log("Failed to send the message. Err:" + JSON.stringify(err));
}
});
});
@@ -62,9 +62,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
if (value === 'bye') {
ws.close((err, value) => {
if (!err) {
- console.log("close success");
+ console.log("Connection closed successfully");
} else {
- console.log("close fail, err is " + JSON.stringify(err));
+ console.log("Failed to close the connection. Err: " + JSON.stringify(err));
}
});
}
@@ -77,9 +77,9 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
- console.log("connect success");
+ console.log("Connected successfully");
} else {
- console.log("connect fail, err:" + JSON.stringify(err));
+ console.log("Connection failed. Err:" + JSON.stringify(err));
}
});
```
diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md
index 53bba062801ec1b8bcf1f65cdc4119fa53757f10..b56401dbedca72e76af3b15efdd63883885bf3d6 100644
--- a/en/application-dev/database/database-relational-guidelines.md
+++ b/en/application-dev/database/database-relational-guidelines.md
@@ -100,7 +100,7 @@ The RDB provides **RdbPredicates** for you to set database operation conditions.
| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
-| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
+| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md
index e1d4cddeb2ff96c8a07a6df84382ad0b8d22464c..54199719cd93a523d8f2b0af14c12578997a02a2 100644
--- a/en/application-dev/dfx/hiappevent-guidelines.md
+++ b/en/application-dev/dfx/hiappevent-guidelines.md
@@ -2,13 +2,13 @@
## When to Use
-The event logging function helps applications log various information generated during running.
+The event logging function helps applications to log various information generated during running.
## Available APIs
JS application event logging APIs are provided by the **hiAppEvent** module.
-**APIs for Event Logging**
+**Table 1** APIs for event logging
| API | Return Value | Description |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
@@ -17,7 +17,7 @@ JS application event logging APIs are provided by the **hiAppEvent** module.
When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes).
-**APIs for Event Logging Configuration**
+**Table 2** APIs for event logging configuration
| API | Return Value | Description |
| ------------------------------ | ------------ | ------------------------------------------------------------ |
diff --git a/en/application-dev/dfx/hiappevent-overview.md b/en/application-dev/dfx/hiappevent-overview.md
index 403aec02035c965da4633e8667be6803031ddf60..2a5e36f879a922f3d6bf845e700068c2a299b337 100644
--- a/en/application-dev/dfx/hiappevent-overview.md
+++ b/en/application-dev/dfx/hiappevent-overview.md
@@ -2,8 +2,10 @@
HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
+The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
+
## Basic Concepts
-The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
+- **Logging**
-**Logging**: Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
+ Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md
index de4f037bab24fd90b7196b5cc89e56cb1b771a06..316ee1b07898a24721b81625c2e9193ae08aa85f 100644
--- a/en/application-dev/dfx/hitracemeter-guidelines.md
+++ b/en/application-dev/dfx/hitracemeter-guidelines.md
@@ -8,7 +8,7 @@ HiTraceMeter provides APIs for system performance tracing. You can call the APIs
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
-**APIs for performance tracing**
+**Table 1** APIs for performance tracing
| API| Return Value| Description|
| ---------------------------------------------------------------------------- | --------- | ------------ |
diff --git a/en/application-dev/dfx/hitracemeter-overview.md b/en/application-dev/dfx/hitracemeter-overview.md
index 3683092b34fcd23a65245303406934b3fb8acad5..649fa7704dd566ab8bc02776de6f62756d7f26a6 100644
--- a/en/application-dev/dfx/hitracemeter-overview.md
+++ b/en/application-dev/dfx/hitracemeter-overview.md
@@ -15,4 +15,4 @@ hiTraceMeter is a tool for you to trace service processes and monitor system per
## Constraints
-- Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
+Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md
index 66b002200fc1c1965f1d3e741739685ae97236e6..0e34d66d523abea51e259bbcea5d7be08e755e3e 100644
--- a/en/application-dev/internationalization/i18n-guidelines.md
+++ b/en/application-dev/internationalization/i18n-guidelines.md
@@ -23,57 +23,64 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop
-1. Obtain the system language.
+1. Obtain the system language.
+
Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module).
- ```
+ ```js
var language = i18n.getSystemLanguage();
```
-2. Obtain the system region.
+2. Obtain the system region.
+
Call the **getSystemRegion** method to obtain the system region.
- ```
+ ```js
var region = i18n.getSystemRegion();
```
-3. Obtain the system locale.
+3. Obtain the system locale.
+
Call the **getSystemLocale** method to obtain the system locale.
- ```
+ ```js
var locale = i18n.getSystemLocale();
```
-4. Check whether the locale's language is RTL.
+4. Check whether the locale's language is RTL.
+
Call the **isRTL** method to check whether the locale's language is RTL.
- ```
+ ```js
var rtl = i18n.isRTL("zh-CN");
```
-5. Check whether the system uses a 24-hour clock.
+5. Check whether the system uses a 24-hour clock.
+
Call the **is24HourClock** method to check whether the system uses a 24-hour clock.
- ```
+ ```js
var hourClock = i18n.is24HourClock();
```
-6. Obtain the localized display of a language.
+6. Obtain the localized display of a language.
+
Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
- ```
+ ```js
var language = "en";
var locale = "zh-CN";
var sentenceCase = false;
var localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase);
```
-7. Obtain the localized display of a country.
+7. Obtain the localized display of a country.
+
Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
- ```
+ ```js
var country = "US";
var locale = "zh-CN";
var sentenceCase = false;
@@ -106,70 +113,78 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop
-1. Instantiate a **Calendar** object.
+1. Instantiate a **Calendar** object.
+
Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used.
- ```
+ ```js
var calendar = i18n.getCalendar("zh-CN", "gregory);
```
-2. Set the time for the **Calendar** object.
+2. Set the time for the **Calendar** object.
+
Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT.
- ```
+ ```js
var date1 = new Date();
calendar.setTime(date1);
var date2 = 1000;
calendar.setTime(date2);
```
-3. Set the year, month, day, hour, minute, and second for the **Calendar** object.
+3. Set the year, month, day, hour, minute, and second for the **Calendar** object.
+
Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object.
- ```
+ ```js
calendar.set(2021, 12, 21, 6, 0, 0)
```
-4. Set and obtain the time zone for the **Calendar** object.
+4. Set and obtain the time zone for the **Calendar** object.
+
Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set.
- ```
+ ```js
calendar.setTimeZone("Asia/Shanghai");
var timezone = calendar.getTimeZone();
```
-5. Set and obtain the first day of a week for the **Calendar** object.
+5. Set and obtain the first day of a week for the **Calendar** object.
+
Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.
- ```
+ ```js
calendar.setFirstDayOfWeek(1);
var firstDayOfWeek = calendar.getFirstDayOfWeek();
```
-6. Set and obtain the minimum count of days in the first week for the **Calendar** object.
+6. Set and obtain the minimum count of days in the first week for the **Calendar** object.
+
Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object.
- ```
+ ```js
calendar.setMinimalDaysInFirstWeek(3);
var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek();
```
-7. Obtain the localized display of the **Calendar** object.
+7. Obtain the localized display of the **Calendar** object.
+
Call the **getDisplayName** method to obtain the localized display of the **Calendar** object.
- ```
+ ```js
var localizedName = calendar.getDisplayName("zh-CN");
```
-8. Check whether a date is a weekend.
+8. Check whether a date is a weekend.
+
Call the **isWeekend** method to determine whether the input date is a weekend.
- ```
+ ```js
var date = new Date();
var weekend = calendar.isWeekend(date);
```
@@ -191,25 +206,26 @@ You can use APIs provided in the following table to obtain the system language a
### How to Develop
-1. Instantiate a **PhoneNumberFormat** object.
+1. Instantiate a **PhoneNumberFormat** object.
+
Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**.
- ```
+ ```js
var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"});
```
2. Check whether the phone number format is correct.
Call the **isValidNumber** method to check whether the format of the input phone number is correct.
- ```
+ ```js
var validNumber = phoneNumberFormat.isValidNumber("15812341234");
```
3. Format a phone number.
Call the **format** method of **PhoneNumberFormat** to format the input phone number.
- ```
+ ```js
var formattedNumber = phoneNumberFormat.format("15812341234");
```
@@ -232,7 +248,7 @@ The **unitConvert** API is provided to help you implement measurement conversion
Call the [unitConvert](../reference/apis/js-apis-intl.md) method to convert a measurement unit and format the display result.
- ```
+ ```js
var fromUnit = {unit: "cup", measureSystem: "US"};
var toUnit = {unit: "liter", measureSystem: "SI"};
var number = 1000;
@@ -259,32 +275,36 @@ The **unitConvert** API is provided to help you implement measurement conversion
### How to Develop
-1. Instantiate an **IndexUtil** object.
+1. Instantiate an **IndexUtil** object.
+
Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale.
- ```
+ ```js
var indexUtil = getInstance("zh-CN");
```
-2. Obtain the index list.
+2. Obtain the index list.
+
Call the **getIndexList** method to obtain the alphabet index list of the current locale.
- ```
+ ```js
var indexList = indexUtil.getIndexList();
```
-3. Add an index.
+3. Add an index.
+
Call the **addLocale** method to add the alphabet index of a new locale to the current index list.
- ```
+ ```js
indexUtil.addLocale("ar")
```
-4. Obtain the index of a string.
+4. Obtain the index of a string.
+
Call the **getIndex** method to obtain the alphabet index of a string.
- ```
+ ```js
var text = "access index";
indexUtil.getIndex(text);
```
@@ -313,38 +333,42 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
### How to Develop
-1. Instantiate a **BreakIterator** object.
+1. Instantiate a **BreakIterator** object.
+
Call the **getLineInstance** method to instantiate a **BreakIterator** object.
- ```
+ ```js
var locale = "en-US"
var breakIterator = i18n.getLineInstance(locale);
```
-2. Set and access the text that requires line breaking.
+2. Set and access the text that requires line breaking.
+
Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking.
- ```
+ ```js
var text = "Apple is my favorite fruit";
breakIterator.setLineBreakText(text);
var breakText = breakIterator.getLineBreakText();
```
-3. Obtain the current position of the **BreakIterator** object.
+3. Obtain the current position of the **BreakIterator** object.
+
Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed.
- ```
+ ```js
var pos = breakIterator.current();
```
-4. Set the position of a **BreakIterator** object.
+4. Set the position of a **BreakIterator** object.
+
The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed.
- ```
+ ```js
var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text.
var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end.
// Move a BreakIterator object forward or backward by a certain number of break points.
@@ -356,10 +380,11 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
var followingPos = breakIterator.following(10);
```
-5. Determine whether a position is a break point.
+5. Determine whether a position is a break point.
+
Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position.
- ```
+ ```js
var isboundary = breakIterator.isBoundary(5);
```
diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md
index 34d2d1b19aea81ee810c472b7ffaf297b0478091..44748056f7886d4817cda2d9d0504f6966c32700 100644
--- a/en/application-dev/internationalization/intl-guidelines.md
+++ b/en/application-dev/internationalization/intl-guidelines.md
@@ -3,7 +3,8 @@
This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402.
The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
-> **NOTE**
+> **NOTE**
+>
> In the code snippets in this document, **intl** refers to the name of the imported module.
## Setting Locale Information
@@ -24,7 +25,8 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
### How to Develop
-1. Instantiate a **Locale** object.
+1. Instantiate a **Locale** object.
+
Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list.
A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-).
@@ -42,30 +44,33 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
| kf | Whether upper case or lower case is considered when sorting or comparing strings.|
- ```
+ ```js
var locale = "zh-CN";
var options = {caseFirst: false, calendar: "chinese", collation: pinyin};
var localeObj = new intl.Locale(locale, options);
```
-2. Obtain the string representing a **Locale** object.
+2. Obtain the string representing a **Locale** object.
+
Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options.
- ```
+ ```js
var localeStr = localeObj.toString();
```
-3. Maximize locale information.
+3. Maximize locale information.
+
Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information.
- ```
+ ```js
var maximizedLocale = localeObj.maximize();
```
-4. Minimize locale information.
+4. Minimize locale information.
+
Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information.
- ```
+ ```js
var minimizedLocale = localeObj.minimize();
```
@@ -88,42 +93,46 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
### How to Develop
-1. Instantiate a **DateTimeFormat** object.
+1. Instantiate a **DateTimeFormat** object.
+
Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object.
- ```
+ ```js
var dateTimeFormat = new intl.DateTimeFormat();
```
Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var options = {dateStyle: "full", timeStyle: "full"};
var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options);
```
-2. Format the date and time.
+2. Format the date and time.
+
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
- ```
+ ```js
Date date = new Date();
var formatResult = dateTimeFormat.format(date);
```
-3. Format a period.
+3. Format a period.
+
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
- ```
+ ```js
Date startDate = new Date();
Date endDate = new Date();
var formatResult = dateTimeFormat.formatRange(startDate, endDate);
```
-4. Obtain attributes of the **DateTimeFormat** object.
+4. Obtain attributes of the **DateTimeFormat** object.
+
Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object.
- ```
+ ```js
var options = dateTimeFormat.resolvedOptions();
```
@@ -145,33 +154,36 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
### How to Develop
-1. Instantiate a **NumberFormat** object.
+1. Instantiate a **NumberFormat** object.
+
Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object.
- ```
+ ```js
var numberFormat = new intl.NumberFormat();
```
Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var options = {compactDisplay: "short", notation: "compact"};
var numberFormat = new intl.NumberFormat("zh-CN", options);
```
-2. Format a number.
+2. Format a number.
+
Call the **format** method to format a number. A string is returned as the formatting result.
- ```
+ ```js
var number = 1234.5678
var formatResult = numberFormat.format(number);
```
-3. Obtain attributes of the **NumberFormat** object.
+3. Obtain attributes of the **NumberFormat** object.
+
Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object.
- ```
+ ```js
var options = numberFormat.resolvedOptions();
```
@@ -193,33 +205,36 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
### How to Develop
-1. Instantiate a **Collator** object.
+1. Instantiate a **Collator** object.
+
Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object.
- ```
+ ```js
var collator = new intl.Collator();
```
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md).
+ ```js
+ var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"});
```
- var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"};
- ```
-2. Compare two strings.
+2. Compare two strings.
+
Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths.
- ```
+ ```js
var str1 = "first string";
var str2 = "second string";
var compareResult = collator.compare(str1, str2);
```
-3. Obtain attributes of the **Collator** object.
+3. Obtain attributes of the **Collator** object.
+
Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object.
- ```
+ ```js
var options = collator.resolvedOptions();
```
@@ -240,24 +255,26 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
### How to Develop
-1. Instantiate a **PluralRules** object.
+1. Instantiate a **PluralRules** object.
+
Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object.
- ```
+ ```js
var pluralRules = new intl.PluralRules();
```
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md).
- ```
- var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"};
+ ```js
+ var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
```
-2. Determine the singular-plural type.
+2. Determine the singular-plural type.
+
Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**.
- ```
+ ```js
var number = 1234.5678
var categoryResult = plurals.select(number);
```
@@ -281,41 +298,45 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
### How to Develop
-1. Instantiate a **RelativeTimeFormat** object.
+1. Instantiate a **RelativeTimeFormat** object.
+
Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object.
- ```
+ ```js
var relativeTimeFormat = new intl.RelativeTimeFormat();
```
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
```
-2. Format the relative time.
+2. Format the relative time.
+
Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result.
- ```
+ ```js
var number = 2;
var unit = "year"
var formatResult = relativeTimeFormat.format(number, unit);
```
-3. Obtain each part of the relative time format.
+3. Obtain each part of the relative time format.
+
Upon obtaining each part of the relative time format, customize the relative time formatting result.
- ```
+ ```js
var number = 2;
var unit = "year"
var formatResult = relativeTimeFormat.formatToParts(number, unit);
```
-4. Obtain attributes of the **RelativeTimeFormat** object.
+4. Obtain attributes of the **RelativeTimeFormat** object.
+
Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md).
- ```
+ ```js
var options = numberFormat.resolvedOptions();
```
diff --git a/en/application-dev/media/audio-interruptmode.md b/en/application-dev/media/audio-interruptmode.md
index 9f9355f68c326ec9b6ae8140a6579114bfaefcc3..8be8a00cedd10ff4ecd08ee46d746d9803b3c71a 100644
--- a/en/application-dev/media/audio-interruptmode.md
+++ b/en/application-dev/media/audio-interruptmode.md
@@ -48,7 +48,7 @@ For details about the APIs, see [AudioRenderer in Audio Management](../reference
```js
var mode_ = audio.InterruptMode.SHARE_MODE;
- await this.audioRenderer.setInterruptMode(mode_).then(()=>{
+ await this.audioRenderer.setInterruptMode(mode_).then(() => {
console.log('[JSAR] [SetInterruptMode] Setting: '+ (mode_ == 0? " share mode":"independent mode") + "success");
});
```
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png
new file mode 100644
index 0000000000000000000000000000000000000000..048b8e07817272b759781df104c1dd4526685d61
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128939.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128939.png
new file mode 100644
index 0000000000000000000000000000000000000000..606ce3a0eab0a39f166029182bcc2f70291740d6
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655128939.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png
new file mode 100644
index 0000000000000000000000000000000000000000..d044d5d829ab1ad805f4ffcda19837f867b976fc
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png
new file mode 100644
index 0000000000000000000000000000000000000000..2dd664a2b25751cc32bd81927b30036d5cc4f351
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png
new file mode 100644
index 0000000000000000000000000000000000000000..7d3222667d7bffe89a148dc3b08861a86c43713e
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129264.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129264.png
new file mode 100644
index 0000000000000000000000000000000000000000..c188c864c051f68984ecc0c4c64be83f0dd6e1e9
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129264.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png
new file mode 100644
index 0000000000000000000000000000000000000000..b42f2e3896d334d86e89b867cf3428782f88d600
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129372.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129372.png
new file mode 100644
index 0000000000000000000000000000000000000000..8541c80810d3f3dfb7180fede34a51221dc56106
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129372.png differ
diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png
new file mode 100644
index 0000000000000000000000000000000000000000..2dda1a5cfca8d75d70e40b8bc0d555faade04583
Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png differ
diff --git a/en/application-dev/quick-start/full-sdk-switch-guide.md b/en/application-dev/quick-start/full-sdk-switch-guide.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c20e429bdef97ab0503614d01f1807e56eedb13
--- /dev/null
+++ b/en/application-dev/quick-start/full-sdk-switch-guide.md
@@ -0,0 +1,98 @@
+# Guide to Switching to Full SDK
+
+Both the public SDK and full SDK are toolkits for application development.
+
+The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
+
+The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs.
+
+The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps.
+
+## Downloading the Full SDK (of 3.1.1 Release in this example)
+
+Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md).
+
+
+
+
+
+
+## Checking the Local SDK Location
In this example, an eTS project is used. For a JS project, replace **ets** with **js**.
+
+In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK.
+
+
+
+
+
+
+## Replacing the SDK
+
+1. Make sure the downloaded SDK is a full SDK.
+
+ a. Verify that the name of the downloaded file contains **sdk-full**.
+
+ 
+
+ b. Verify that the SDK contains system APIs (such as APIs defined in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, and **@ohos.bluetooth.d.ts**).
+
+ Note: The criteria for identifying system APIs are subject to the released API documentation.
+
+
+
+2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example.
+
+
+
+ a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip`
+
+ 
+
+ b. Replace the SDK files.
+
+ Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.)
+
+ Go to the obtained location of the local installed SDK and back up the files therein.
+
+ 
+
+ Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**.
+
+ 
+
+ The configuration in the **oh-uni-package.json** file is as follows:
+
+ ```
+ {
+ "apiVersion": "8",
+ "displayName": "Ets",
+ "meta": {
+ "metaVersion": "3.0.0"
+ },
+ "path": "ets",
+ "releaseType": "Release",
+ "version": "3.1.6.6"
+ }
+ ```
+
+ **Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten.
+
+
+
+ Copy the full SDK to the location of the local SDK.
+
+ Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK.
+
+ Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number.
+
+
+
+ In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package.
+
+ 
+
+
+
+ c. Check for system APIs.
+
+ 
diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md
index fb8f943cea9d605b242f3ecb85d587a997ad581e..6b5bbc8aa3d671c4cf0b01316db441d33c0f189f 100644
--- a/en/application-dev/reference/apis/Readme-EN.md
+++ b/en/application-dev/reference/apis/Readme-EN.md
@@ -32,6 +32,7 @@
- [@ohos.ability.errorCode](js-apis-ability-errorCode.md)
- [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md)
- [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md)
+ - [@ohos.application.abilityManager](js-apis-application-abilityManager.md)
- [@ohos.application.appManager](js-apis-appmanager.md)
- [@ohos.application.Configuration](js-apis-configuration.md)
- [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md)
@@ -43,6 +44,8 @@
- [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.application.Want](js-apis-application-Want.md)
+ - [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md)
+ - [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md)
- [@ohos.wantAgent](js-apis-wantAgent.md)
- application/[abilityDelegator](js-apis-application-abilityDelegator.md)
- application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md)
@@ -52,7 +55,7 @@
- application/[MissionSnapshot](js-apis-application-MissionSnapshot.md)
- application/[ProcessRunningInfo](js-apis-processrunninginfo.md)
- application/[shellCmdResult](js-apis-application-shellCmdResult.md)
-
+ - continuation/[ContinuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification
- [@ohos.commonEvent](js-apis-commonEvent.md)
diff --git a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md
index e79d761f6a6792096d19b06cabab447af9ed8dac..098f4ebba840a13d1f37d6e14256fcc9695f2a8d 100644
--- a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md
+++ b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md
@@ -25,9 +25,9 @@ abilitymanager.getAbilityRunningInfos((err,data) => {
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
-| ability | ElementName | Yes| No| Information that matches an ability. |
-| pid | number | Yes| No| Process ID.|
-| uid | number | Yes| No| User ID. |
-| processName | string | Yes| No| Process name. |
-| startTime | number | Yes| No| Ability start time. |
-| abilityState | [abilityManager.AbilityState](js-apis-abilityManager.md#abilityState) | Yes| No| Ability state. |
+| ability | ElementName | Yes| No| Information that matches an ability. |
+| pid | number | Yes| No| Process ID.|
+| uid | number | Yes| No| User ID. |
+| processName | string | Yes| No| Process name. |
+| startTime | number | Yes| No| Ability start time. |
+| abilityState | [abilityManager.AbilityState](js-apis-application-abilityManager.md#abilitystate) | Yes| No| Ability state. |
diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md
index 17ef631d0f7207b676177a59d0903cc77dcd1045..f9d286cbd34296fa43596032fe89f2ecdd6e5d93 100644
--- a/en/application-dev/reference/apis/js-apis-accessibility.md
+++ b/en/application-dev/reference/apis/js-apis-accessibility.md
@@ -1,6 +1,9 @@
# Accessibility
-> **NOTE**
+The **Accessibility** module implements the accessibility functions, including obtaining the accessibility application list, accessibility application enabled status, and captions configuration.
+
+> **NOTE**
+>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
@@ -13,162 +16,162 @@ import accessibility from '@ohos.accessibility';
Enumerates the states of an accessibility application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | enable | The accessibility application is enabled. |
- | disable | The accessibility application is disabled. |
- | install | The accessibility application has been installed. |
+| Name| Description|
+| -------- | -------- |
+| enable | The accessibility application is enabled.|
+| disable | The accessibility application is disabled.|
+| install | The accessibility application has been installed.|
## AbilityType
Enumerates the types of accessibility applications.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | audible | The accessibility application provides audible feedback. |
- | generic | The accessibility application provides generic feedback. |
- | haptic | The accessibility application provides haptic feedback. |
- | spoken | The accessibility application provides spoken feedback. |
- | visual | The accessibility application provides visual feedback. |
+| Name| Description|
+| -------- | -------- |
+| audible | The accessibility application provides audible feedback.|
+| generic | The accessibility application provides generic feedback.|
+| haptic | The accessibility application provides haptic feedback.|
+| spoken | The accessibility application provides spoken feedback.|
+| visual | The accessibility application provides visual feedback.|
+| all9+ | All the preceding types.|
## AccessibilityAbilityInfo
Provides information about an accessibility application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | id | number | Yes | No | Ability ID. |
- | name | string | Yes | No | Ability name. |
- | bundleName | string | Yes | No | Bundle name. |
- | abilityTypes | Array<[AbilityType](#abilitytype)> | Yes | No | Accessibility application type. |
- | capabilities | Array<[Capability](#capability)> | Yes | No | Capabilities list of the accessibility application. |
- | description | string | Yes | No | Description of the accessibility application. |
- | eventTypes | Array<[EventType](#eventtype)> | Yes | No | List of events that the accessibility application focuses on. |
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| id | number | Yes| No| Ability ID.|
+| name | string | Yes| No| Ability name.|
+| bundleName | string | Yes| No| Bundle name.|
+| targetBundleNames9+ | Array<string> | Yes| No| Name of the target bundle.|
+| abilityTypes | Array<[AbilityType](#abilitytype)> | Yes| No| Accessibility application type.|
+| capabilities | Array<[Capability](#capability)> | Yes| No| Capabilities list of the accessibility application.|
+| description | string | Yes| No| Description of the accessibility application.|
+| eventTypes | Array<[EventType](#eventtype)> | Yes| No| List of events that the accessibility application focuses on.|
## Action
Describes the target action supported by an accessibility application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
-
- | Name | Description |
- | -------- | -------- |
- | click | Clicking. |
- | longClick | Long pressing. |
- | scrollForward | Scrolling forward. |
- | scrollBackward | Scrolling backward. |
- | focus | Obtaining focus. |
- | clearFocus | Clearing focus. |
- | clearSelection | Clearing selection. |
- | accessibilityFocus | Obtaining the accessibility focus. |
- | clearAccessibilityFocus | Clearing the accessibility focus. |
- | cut | Cut. |
- | copy | Copy. |
- | paste | Paste. |
- | select | Select. |
- | setText | Setting the text. |
- | delete | Delete. |
- | setSelection | Setting the selection. |
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
+
+| Name| Description|
+| -------- | -------- |
+| click | Clicking.|
+| longClick | Long pressing.|
+| scrollForward | Scrolling forward.|
+| scrollBackward | Scrolling backward.|
+| focus | Obtaining focus.|
+| clearFocus | Clearing focus.|
+| clearSelection | Clearing selection.|
+| accessibilityFocus | Obtaining the accessibility focus.|
+| clearAccessibilityFocus | Clearing the accessibility focus.|
+| cut | Cut.|
+| copy | Copy.|
+| paste | Paste.|
+| select | Select.|
+| setText | Setting the text.|
+| delete | Delete.|
+| setSelection | Setting the selection.|
## Capability
Enumerates the capabilities of an auxiliary application.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | retrieve | Capability to retrieve the window content. |
- | touchGuide | Capability of touch guide mode. |
- | keyEventObserver | Capability to filter key events. |
- | zoom | Capability to control the display zoom level. |
- | gesture | Capability to perform gesture actions. |
+| Name| Description|
+| -------- | -------- |
+| retrieve | Capability to retrieve the window content.|
+| touchGuide | Capability of touch guide mode.|
+| keyEventObserver | Capability to filter key events.|
+| zoom | Capability to control the display zoom level.|
+| gesture | Capability to perform gesture actions.|
## CaptionsFontEdgeType8+
-Enumerates the caption font edge type.
+Enumerates the font edge types of captions.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Description |
- | -------- | -------- |
- | none | No effect. |
- | raised | Raised effect. |
- | depressed | Depressed effect. |
- | uniform | Uniform effect. |
- | dropShadow | Drop shadow effect. |
+| Name| Description|
+| -------- | -------- |
+| none | No effect.|
+| raised | Raised effect.|
+| depressed | Depressed effect.|
+| uniform | Uniform effect.|
+| dropShadow | Drop shadow effect.|
## CaptionsFontFamily8+
-Enumerates the caption font families.
+Enumerates the font families of captions.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Description |
- | -------- | -------- |
- | default | Default font family. |
- | monospacedSerif | Monospaced Serif fonts, which use the same width for each character. |
- | serif | Serif fonts. |
- | monospacedSansSerif | Monospaced Sans Serif fonts, which use the same width for each character. |
- | sansSerif | Sans Serif fonts. |
- | casual | Casual fonts. |
- | cursive | Cursive fonts. |
- | smallCapitals | Small caps fonts. |
+| Name| Description|
+| -------- | -------- |
+| default | Default font family.|
+| monospacedSerif | Monospaced Serif fonts, which use the same width for each character.|
+| serif | Serif fonts.|
+| monospacedSansSerif | Monospaced Sans Serif fonts, which use the same width for each character.|
+| sansSerif | Sans Serif fonts.|
+| casual | Casual fonts.|
+| cursive | Cursive fonts.|
+| smallCapitals | Small caps fonts.|
## CaptionsStyle8+
-Describes the caption style.
+Describes the style of captions.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes | No | Font family of the captions. |
- | fontScale | number | Yes | No | Font scale of the captions. |
- | fontColor | number \ | string | Yes | No | Font color of the captions. |
- | fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes | No | Font edge type of the captions. |
- | backgroundColor | number \ | string | Yes | No | Background color of the captions. |
- | windowColor | number \ | string | Yes | No | Window color of the captions. |
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes| No| Font family of captions.|
+| fontScale | number | Yes| No| Font scale of captions.|
+| fontColor | number \| string | Yes| No| Font color of captions.|
+| fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes| No| Font edge type of captions.|
+| backgroundColor | number \| string | Yes| No| Background color of captions.|
+| windowColor | number \| string | Yes| No| Window color of captions.|
## CaptionsManager8+
-Implements caption configuration management.
+Implements configuration management for captions.
-### Attributes
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | enabled | boolean | Yes | No | Whether to enable caption configuration. |
- | style | [CaptionsStyle](#captionsstyle8) | Yes | No | Caption style. |
+### Attributes
-### Methods
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| enabled | boolean | Yes| No| Whether to enable captions configuration.|
+| style | [CaptionsStyle](#captionsstyle8) | Yes| No| Style of captions.|
-In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) method to obtain a **captionsManager** instance, and then call the methods using the obtained instance.
+In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **captionsManager** instance, and then call the methods using the obtained instance.
-#### on('enableChange')
+### on('enableChange')
on(type: 'enableChange', callback: Callback<boolean>): void;
-Enables listening for enable status changes of caption configuration.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Enables listening for enabled status changes of captions configuration.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **enableChange** in this API. |
- | callback | Callback<boolean> | Yes | Callback invoked when the enable status of caption configuration changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.|
+ | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.|
-- Example
+- **Example**
```typescript
captionsManager.on('enableChange',(data) => {
@@ -176,22 +179,20 @@ Enables listening for enable status changes of caption configuration.
})
```
-#### on('styleChange')
+### on('styleChange')
on(type: 'styleChange', callback: Callback<CaptionsStyle>): void;
-Enables listening for caption style changes.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Enables listening for captions style changes.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **styleChange** in this API. |
- | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes | Callback invoked when the caption style changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.|
+ | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.|
-- Example
+- **Example**
```typescript
captionsManager.on('styleChange',(data) => {
@@ -199,43 +200,39 @@ Enables listening for caption style changes.
})
```
-#### off('enableChange')
+### off('enableChange')
off(type: 'enableChange', callback?: Callback<boolean>): void;
-Disables listening for enable status changes of caption configuration.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Disables listening for enabled status changes of captions configuration.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **enableChange** in this API. |
- | callback | Callback<boolean> | No | Callback invoked when the enable status of caption configuration changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.|
+ | callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.|
-- Example
+- **Example**
```typescript
captionsManager.off('enableChange')
```
-#### off('styleChange')
+### off('styleChange')
off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void;
-Disables listening for caption style changes.s is removed.
-
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+Disables listening for captions style changes.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for, which is set to **styleChange** in this API. |
- | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No | Callback invoked when the caption style changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.|
+ | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.|
-- Example
+- **Example**
```typescript
captionsManager.off('styleChange')
@@ -245,80 +242,92 @@ Disables listening for caption style changes.s is removed.
Describes a GUI change event.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
- | Name | Type | Readable | Writable | Description |
- | -------- | -------- | -------- | -------- | -------- |
- | type | [EventType](#eventtype) | Yes | Yes | Accessibility event type. |
- | windowUpdateType | [WindowUpdateType](#windowupdatetype) | Yes | Yes | Window update type. |
- | bundleName | string | Yes | Yes | Target application name. |
- | componentType | string | Yes | Yes | Type of the event source component, for example, button or chart. |
- | pageId | number | Yes | Yes | Page ID of the event source. |
- | description | string | Yes | Yes | Event description. |
- | triggerAction | [Action](#action) | Yes | Yes | Action that triggers the event. |
- | textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes | Yes | Text movement unit. |
- | contents | Array<string> | Yes | Yes | Array of contents. |
- | lastContent | string | Yes | Yes | Latest content. |
- | beginIndex | number | Yes | Yes | Sequence number of the first item displayed on the page. |
- | currentIndex | number | Yes | Yes | Sequence number of the current item. |
- | endIndex | number | Yes | Yes | Sequence number of the last item displayed on the page. |
- | itemCount | number | Yes | Yes | Total number of items. |
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| type | [EventType](#eventtype) | Yes| Yes| Accessibility event type.|
+| windowUpdateType | [WindowUpdateType](#windowupdatetype) | Yes| Yes| Window update type.|
+| bundleName | string | Yes| Yes| Target application name.|
+| componentType | string | Yes| Yes| Type of the event source component, for example, button or chart.|
+| pageId | number | Yes| Yes| Page ID of the event source.|
+| description | string | Yes| Yes| Event description.|
+| triggerAction | [Action](#action) | Yes| Yes| Action that triggers the event.|
+| textMoveUnit | [TextMoveUnit](#textmoveunit) | Yes| Yes| Text movement unit.|
+| contents | Array<string> | Yes| Yes| Array of contents.|
+| lastContent | string | Yes| Yes| Latest content.|
+| beginIndex | number | Yes| Yes| Sequence number of the first item displayed on the page.|
+| currentIndex | number | Yes| Yes| Sequence number of the current item.|
+| endIndex | number | Yes| Yes| Sequence number of the last item displayed on the page.|
+| itemCount | number | Yes| Yes| Total number of items.|
+
+### constructor
+
+constructor(jsonObject)
+
+Implements a constructor.
+
+- **Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | jsonObject | string | Yes| JSON string required for creating an object.|
+
+- **Example**
+
+ ```typescript
+ let eventInfo = new accessibility.EventInfo({"type":"click","bundleName":"com.example.MyApplication","triggerAction":"click"})
+ ```
## EventType
Enumerates accessibility event types.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
-
- | Name | Description |
- | -------- | -------- |
- | click | Event of clicking a component. |
- | longClick | Event of long-pressing a component. |
- | select | Event of selecting a component. |
- | focus | Event indicating that the component obtains the focus. |
- | textUpdate | Event indicating that the component text has been updated. |
- | hoverEnter | Event indicating that the hover enters a component. |
- | hoverExit | Event indicating that the hover exits a component. |
- | scroll | Event of the scroll view. |
- | textSelectionUpdate | Event indicating that the selected text has been updated. |
- | accessibilityFocus | Event indicating that the accessibility focus has been obtained. |
- | accessibilityFocusClear | Event indicating that the accessibility focus has been cleared. |
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
+
+| Name| Description|
+| -------- | -------- |
+| click | Event of clicking a component.|
+| longClick | Event of long-pressing a component.|
+| select | Event of selecting a component.|
+| focus | Event indicating that the component obtains the focus.|
+| textUpdate | Event indicating that the component text has been updated.|
+| hoverEnter | Event indicating that the hover enters a component.|
+| hoverExit | Event indicating that the hover exits a component.|
+| scroll | Event of the scroll view.|
+| textSelectionUpdate | Event indicating that the selected text has been updated.|
+| accessibilityFocus | Event indicating that the accessibility focus has been obtained.|
+| accessibilityFocusClear | Event indicating that the accessibility focus has been cleared.|
## TextMoveUnit
Enumerates the movement units for traversing the node text.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- | Name | Description |
- | -------- | -------- |
- | char | The movement unit for traversing the node text is by character. |
- | word | The movement unit for traversing the node text is by word. |
- | line | The movement unit for traversing the node text is by line. |
- | page | The movement unit for traversing the node text is by page. |
- | paragraph | The movement unit for traversing the node text is by paragraph. |
+| Name| Description|
+| -------- | -------- |
+| char | The movement unit for traversing the node text is by character.|
+| word | The movement unit for traversing the node text is by word.|
+| line | The movement unit for traversing the node text is by line.|
+| page | The movement unit for traversing the node text is by page.|
+| paragraph | The movement unit for traversing the node text is by paragraph.|
## WindowUpdateType
Enumerates window update types.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
-
- | Name | Description |
- | -------- | -------- |
- | add | Window adding. |
- | remove | Window deletion. |
- | title | Window title change. |
- | bounds | Window boundary change. |
- | layer | Window layer change. |
- | active | Window activity change. |
- | focus | Window focus change. |
- | accessibilityFocus | Window accessibility focus change. |
- | parent | Parent window change. |
- | children | Child window change. |
- | pip | Picture-in-picture (PIP) mode change. |
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
+
+| Name| Description|
+| -------- | -------- |
+| add | Window adding.|
+| remove | Window deletion.|
+| bounds | Window boundary change.|
+| active | Window activity change.|
+| focus | Window focus change.|
## accessibility.getAbilityLists
@@ -326,22 +335,22 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<A
Obtains the accessibility application list. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type. |
- | stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.|
+ | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.|
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.|
-- Example
+- **Example**
```typescript
accessibility.getAbilityLists("spoken", "enable")
@@ -369,17 +378,17 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: Asyn
Obtains the accessibility application list. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | abilityType | [AbilityType](#abilitytype) | Yes | Accessibility application type. |
- | stateType | [AbilityState](#abilitystate) | Yes | Accessibility application status. |
- | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes | Callback used to return the accessibility application list. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.|
+ | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.|
+ | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.|
-- Example
+- **Example**
```typescript
accessibility.getAbilityLists("visual", "enable", (err, data) => {
@@ -406,17 +415,17 @@ Obtains the accessibility application list. This API uses an asynchronous callba
getCaptionsManager(): CaptionsManager
-Obtains the accessibility caption configuration.
+Obtains the captions configuration.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing
+**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | [CaptionsManager](#captionsmanager8) | Accessibility caption configuration. |
+ | Type| Description|
+ | -------- | -------- |
+ | [CaptionsManager](#captionsmanager8) | Captions configuration.|
-- Example
+- **Example**
```typescript
captionsManager = accessibility.getCaptionsManager()
@@ -430,12 +439,12 @@ Enables listening for the accessibility application or touch guide mode status c
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | Yes | Type of the event to listen for.
- **accessibilityStateChange** means to listen for enable status changes of the accessibility application.
**System capability**: SystemCapability.Barrierfree.Accessibility.Core
- **touchGuideStateChange** means to listen for enable status changes of the touch guide mode.
**System capability**: SystemCapability.Barrierfree.Accessibility.Vision |
- | callback | Callback<boolean> | Yes | Callback invoked when the enable status changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision|
+ | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.|
-- Example
+- **Example**
```typescript
accessibility.on('accessibilityStateChange',(data) => {
@@ -447,18 +456,16 @@ Enables listening for the accessibility application or touch guide mode status c
off(type: 'accessibilityStateChange ' | 'touchGuideStateChange', callback?: Callback<boolean>): void
-Disables listening for the accessibility application or touch guide mode status changes.
-
-
+Disables listening for the accessibility application or touch guide mode status changes.
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | type | string | No | Type of the event to listen for.
- **accessibilityStateChange** means to listen for enable status changes of the accessibility application.
**System capability**: SystemCapability.Barrierfree.Accessibility.Core
- **touchGuideStateChange** means to listen for enable status changes of the touch guide mode.
**System capability**: SystemCapability.Barrierfree.Accessibility.Vision |
- | callback | Callback<boolean> | No | Callback invoked when the enable status changes. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | No| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision|
+ | callback | Callback<boolean> | No| Callback invoked when the enabled status changes.|
-- Example
+- **Example**
```typescript
accessibility.off('accessibilityStateChange',(data) => {
@@ -472,15 +479,15 @@ isOpenAccessibility(): Promise<boolean>
Checks whether accessibility is enabled. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenAccessibility()
@@ -497,15 +504,15 @@ isOpenAccessibility(callback: AsyncCallback<boolean>): void
Checks whether accessibility is enabled. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
-- Parameters
+- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenAccessibility((err, data) => {
@@ -523,15 +530,15 @@ isOpenTouchGuide(): Promise<boolean>
Checks whether touch guide mode is enabled. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Vision
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenTouchGuide()
@@ -548,15 +555,15 @@ isOpenTouchGuide(callback: AsyncCallback<boolean>): void
Checks whether touch guide mode is enabled. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Vision
-- Parameters
+- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.|
-- Example
+- **Example**
```typescript
accessibility.isOpenTouchGuide((err, data) => {
@@ -574,21 +581,21 @@ sendEvent(event: EventInfo): Promise<void>
Sends an accessibility event. This API uses a promise to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | event | [EventInfo](#eventinfo) | Yes | Accessibility event. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | event | [EventInfo](#eventinfo) | Yes| Accessibility event.|
-- Return value
+- **Return value**
- | Type | Description |
- | -------- | -------- |
- | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise. |
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.|
-- Example
+- **Example**
```typescript
accessibility.sendEvent(this.eventInfo)
@@ -605,16 +612,16 @@ sendEvent(event: EventInfo, callback: AsyncCallback<void>): void
Sends an accessibility event. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Barrierfree.Accessibility.Core
+**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **Parameters**
- | Name | Type | Mandatory | Description |
- | -------- | -------- | -------- | -------- |
- | event | [EventInfo](#eventinfo) | Yes | Accessibility event. |
- | callback | AsyncCallback<void> | Yes | Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise. |
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | event | [EventInfo](#eventinfo) | Yes| Accessibility event.|
+ | callback | AsyncCallback<void> | Yes| Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.|
-- Example
+- **Example**
```typescript
accessibility.sendEvent(this.eventInfo,(err, data) => {
diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md
index 2a3dc0d9e34fd7ba2dd3e37c018292bec6da8be9..f216c6b08806daa6c5bc87471a3effd749130094 100644
--- a/en/application-dev/reference/apis/js-apis-appAccount.md
+++ b/en/application-dev/reference/apis/js-apis-appAccount.md
@@ -1956,6 +1956,7 @@ Defines OAuth token information.
| -------- | ------ | ---- | -------- |
| authType | string | Yes | Authentication type.|
| token | string | Yes | Value of the token. |
+| account9+ | AppAccountInfo | No | Account information of the token. |
## AuthenticatorInfo8+
diff --git a/en/application-dev/reference/apis/js-apis-application-StartOptions.md b/en/application-dev/reference/apis/js-apis-application-StartOptions.md
index dd0c20515c460318c629a1e197353b28fe7002dc..d1d7416500d37ab61523633f3880670ad8b98779 100644
--- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md
+++ b/en/application-dev/reference/apis/js-apis-application-StartOptions.md
@@ -19,5 +19,5 @@ import StartOptions from '@ohos.application.StartOptions';
| Name| Readable| Writable| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | -------- |
-| windowMode | Yes| No| number | No| Window mode.|
+| [windowMode](js-apis-application-abilityConstant.md#AbilityConstant.WindowMode) | Yes| No| number | No| Window mode.|
| displayId | Yes| No| number | No| Display ID.|
diff --git a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md
new file mode 100644
index 0000000000000000000000000000000000000000..8a366b1e21bb988c608ba0a5e57251f2bd237d75
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md
@@ -0,0 +1,137 @@
+# Window Extension Ability
+**WindowExtensionAbility** inherits from **ExtensionAbility**. The content in a **WindowExtensionAbility** object can be displayed as an ability component in other application windows.
+
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+>
+> The APIs provided by this module are system APIs.
+>
+> The APIs of this module can be used only in the stage model.
+
+## Modules to Import
+
+```ts
+import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility';
+```
+
+## Attributes
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name | Type| Readable| Writable| Description |
+| --------- | -------- | ---- | ---- | ------------------------- |
+| context | [ExtensionContext](js-apis-extension-context.md) | Yes | No | Context of an Extension ability. |
+
+## WindowExtensionAbility.onConnect
+
+onConnect(want: Want): rpc.RemoteObject
+
+Called when this Window Extension ability is connected to an ability for the first time.
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. |
+
+**Return value**
+| Type | Description |
+| ----------------------------------------------- | -------------------- |
+| [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Proxy of this Window Extension ability.|
+
+**Example**
+
+```ts
+import rpc from '@ohos.rpc';
+
+class StubTest extends rpc.RemoteObject {
+ constructor(des) {
+ super(des);
+ }
+ onRemoteRequest(code, data, reply, option) {
+ return true;
+ }
+ queryLocalInterface(descriptor) {
+ return null;
+ }
+ getInterfaceDescriptor() {
+ return "";
+ }
+ sendRequest(code, data, reply, options) {
+ return null;
+ }
+ getCallingPid() {
+ return 1;
+ }
+ getCallingUid() {
+ return 1;
+ }
+ attachLocalInterface(localInterface, descriptor){}
+}
+
+export default class MyWindowExtensionAbility extends WindowExtensionAbility {
+
+ onConnect(want): rpc.RemoteObject {
+ console.info('WindowExtAbility onConnect ' + want.abilityName);
+ return new StubTest("test");
+ }
+
+}
+```
+
+## WindowExtensionAbility.onDisconnect
+
+onDisconnect(want: Want): void
+
+Called when this Window Extension ability is disconnected from all connected abilities.
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. |
+
+
+**Example**
+
+```ts
+export default class MyWindowExtensionAbility extends WindowExtensionAbility {
+
+ onDisconnect(want) {
+ console.info('WindowExtAbility onDisconnect ' + want.abilityName);
+ }
+
+}
+```
+
+
+## WindowExtensionAbility.onWindowReady
+
+onWindowReady(window: Window): void
+
+Called when a window is ready.
+
+**System capability**: SystemCapability.WindowManager.WindowManager.Core
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| window | [Window](js-apis-window.md) | Yes| Current **Window** instance.|
+
+
+**Example**
+
+```ts
+export default class MyWindowExtensionAbility extends WindowExtensionAbility {
+
+ onWindowReady(window) {
+ window.loadContent('WindowExtAbility/pages/index1').then(() => {
+ window.getProperties().then((pro) => {
+ console.log("WindowExtension " + JSON.stringify(pro));
+ })
+ window.show();
+ })
+ }
+
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md
index 3dbdff01d34bed0a34df2b07a75c4d68d8d3e889..ca3269353344ca06935afaf6b390ae0c906f1a1a 100644
--- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md
+++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md
@@ -62,3 +62,17 @@ Enumerates ability continuation results.
| AGREE | 0 | Continuation agreed.|
| REJECT | 1 | Continuation denied.|
| MISMATCH | 2 | Mismatch.|
+
+## AbilityConstant.WindowMode
+
+Enumerates the window modes when an ability is started.
+
+**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+
+| Name | Value| Description |
+| --- | --- | --- |
+| WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. |
+| WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. |
+| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. |
+| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. |
+| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.|
diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md
index 2a7827180ffe1c0a0d5aa022957eb90a0d6cb3f9..e1bf96bae511de4e1fb83d92df6ee05bdddbf990 100644
--- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md
+++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md
@@ -7,7 +7,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying
> 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.
-# Modules to Import
+## Modules to Import
```js
import AbilityManager from '@ohos.application.abilityManager'
@@ -19,6 +19,8 @@ Enumerates the ability states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
+**System API**: This is a system API and cannot be called by third-party applications.
+
| Name| Value| Description|
| -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.|
diff --git a/en/application-dev/reference/apis/js-apis-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-application-applicationContext.md
index 7a76626655a193e7f146190df319fbbeafe8430d..88eccc98c39c5373930f35465ca48da1df19c40d 100644
--- a/en/application-dev/reference/apis/js-apis-application-applicationContext.md
+++ b/en/application-dev/reference/apis/js-apis-application-applicationContext.md
@@ -7,7 +7,7 @@ The **ApplicationContext** module provides application-level context. You can us
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
-## How to Use
+## Usage
Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance.
@@ -28,7 +28,7 @@ Registers a listener to monitor the ability lifecycle of the application.
| Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ |
-| [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | callback | Yes | Callback used to return the ID of the registered listener.|
+| callback | [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value**
@@ -98,7 +98,7 @@ Deregisters the listener that monitors the ability lifecycle of the application.
| Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- |
| callbackId | number | Yes | ID of the listener to deregister.|
-| AsyncCallback | callback | Yes | Callback used to return the result. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
@@ -123,7 +123,7 @@ Registers a listener for system environment changes. This API uses an asynchrono
| Name | Type | Mandatory| Description |
| ------------------------ | -------- | ---- | ------------------------------ |
-| [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | callback | Yes | Callback used to return the ID of the registered listener.|
+| callback | [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | Yes | Callback used to return the ID of the registered listener.|
**Return value**
@@ -175,7 +175,7 @@ Deregisters the listener for system environment changes. This API uses an asynch
| Name | Type | Mandatory| Description |
| ------------- | -------- | ---- | -------------------------- |
| callbackId | number | Yes | ID of the listener to deregister. |
-| AsyncCallback | callback | Yes | Callback used to return the result. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md
index f9e8ea3be2d7ccfff71426848d2dbc2f0e349201..eb85e5d52d50068b8147c1a4789389b2cf5506e1 100644
--- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md
@@ -1,45 +1,41 @@
# BundleInfo
-
-
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
-
-
-Provides the application bundle information.
+The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## BundleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
-| Name | Type | Readable| Writable| Description |
-| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------ |
-| name | string | Yes | No | Bundle name. |
-| type | string | Yes | No | Bundle type. |
-| appId | string | Yes | No | ID of the application to which the bundle belongs. |
-| uid | number | Yes | No | UID of the application to which the bundle belongs. |
-| installTime | number | Yes | No | Time when the HAP file was installed. |
-| updateTime | number | Yes | No | Time when the HAP file was updated. |
-| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. |
-| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information. |
-| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application. |
-| reqPermissionDetails | Array\<[ReqPermissionDetail](#ReqPermissionDetail)> | Yes | No | Detailed information of the permissions to request from the system.|
-| vendor | string | Yes | No | Vendor of the bundle. |
-| versionCode | number | Yes | No | Version number of the bundle. |
-| versionName | string | Yes | No | Version description of the bundle. |
-| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. |
-| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. |
-| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. |
-| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. |
-| entryModuleName | string | Yes | No | Name of the entry module. |
-| cpuAbi | string | Yes | No | cpuAbi information of the bundle. |
-| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. |
-| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. |
-| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. |
-| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. |
-| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information. |
+| Name | Type | Readable| Writable| Description |
+| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
+| name | string | Yes | No | Bundle name. |
+| type | string | Yes | No | Bundle type. |
+| appId | string | Yes | No | ID of the application to which the bundle belongs. |
+| uid | number | Yes | No | UID of the application to which the bundle belongs. |
+| installTime | number | Yes | No | Time when the HAP file was installed. |
+| updateTime | number | Yes | No | Time when the HAP file was updated. |
+| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. |
+| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.|
+| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
+| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
+| vendor | string | Yes | No | Vendor of the bundle. |
+| versionCode | number | Yes | No | Version number of the bundle. |
+| versionName | string | Yes | No | Version description of the bundle. |
+| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. |
+| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. |
+| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. |
+| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. |
+| entryModuleName | string | Yes | No | Name of the entry module. |
+| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. |
+| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. |
+| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. |
+| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. |
+| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. |
+| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.
The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.|
diff --git a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md
index 3c98a25b721a8f3cce41f927d7a35456761db366..9b11bb2f18da535af770b96cda13981cef95c62a 100644
--- a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md
@@ -6,9 +6,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.
-
-
-Provides the Extension ability information.
+The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## ExtensionAbilityInfo
@@ -28,5 +26,5 @@ Provides the Extension ability information.
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the Extension ability. |
| metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. |
| enabled | boolean | Yes | No | Whether the Extension ability is enabled. |
-| readPermission | string | Yes | No | Permission required for reading the Extension ability data. |
+| readPermission | string | Yes | No | Permission required for reading data from the Extension ability. |
| writePermission | string | Yes | No | Permission required for writing data to the Extension ability. |
diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md
index 2f6dbbef26e41ec1f78fe5768c2389d1a8ee0578..5a11609281eebb7464b1e627ec432b4ffad72700 100644
--- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md
@@ -6,16 +6,12 @@
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
-
-
-Provides the HAP module information.
+The **HapModuleInfo** module provides module information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## HapModuleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
-
-
| Name | Type | Readable| Writable| Description |
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- |
| name | string | Yes | No | Module name. |
@@ -36,4 +32,4 @@ Provides the HAP module information.
| mainElementName9+ | string | Yes | No | Information about the main ability. |
| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.|
| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. |
-| hashValue9+ | string | Yes | No | Hash value of the module. |
+| hashValue9+ | string | Yes | No | Hash value of the module.
The value is obtained by passing **GET_BUNDLE_WITH_HASH_VALUE**.|
diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md
index 3d532293b18ca1b262feabe80615dc1807ac30dc..72fcfaca8fb39e4345c2392e761b19b364922499 100644
--- a/en/application-dev/reference/apis/js-apis-bytrace.md
+++ b/en/application-dev/reference/apis/js-apis-bytrace.md
@@ -7,7 +7,7 @@
## Modules to Import
-```
+ ```js
import bytrace from '@ohos.bytrace';
```
@@ -35,7 +35,7 @@ Marks the start of a timeslice trace task.
**Example**
-```
+ ```js
bytrace.startTrace("myTestFunc", 1);
bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms.
```
@@ -62,7 +62,7 @@ Marks the end of a timeslice trace task.
**Example**
-```
+ ```js
bytrace.finishTrace("myTestFunc", 1);
```
@@ -105,7 +105,7 @@ Defines the variable that indicates the number of timeslice trace tasks.
**Example**
-```
+ ```js
let traceCount = 3;
bytrace.traceByValue("myTestCount", traceCount);
traceCount = 4;
diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md
new file mode 100644
index 0000000000000000000000000000000000000000..cfbfb83e3359a4b7d41cf6ab039d0c1f0552c9eb
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md
@@ -0,0 +1,22 @@
+# ContinuationExtraParams
+
+The **ContinuationExtraParams** module provides the extra parameters required by the device selection module in the continuation management entry.
+
+> **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.
+
+## ContinuationExtraParams
+
+Describes the extra parameters required by the device selection module in the continuation management entry.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| deviceType | Array\ | Yes| Yes| Device type.|
+| targetBundle | string | Yes| Yes| Target bundle name.|
+| description | string | Yes| Yes| Device filtering description.|
+| filter | any | Yes| Yes| Device filtering parameter.|
+| continuationMode | [ContinuationMode](js-apis-continuation-continuationManager.md#continuationmode) | Yes| Yes| Continuation mode.|
+| authInfo | { [key: string]: any } | Yes| Yes| Authentication information.|
diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md
new file mode 100644
index 0000000000000000000000000000000000000000..007d35d1408e2381aca841dd64cb9ce6a078b16a
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md
@@ -0,0 +1,496 @@
+# continuationManager
+
+The **continuationManager** module provides the continuation management entry. You can use the APIs of this module to connect to and cancel the continuation management service, subscribe to and unsubscribe from device connection events, start the device selection module, and update the device connection state.
+
+Currently, this module provides incomplete functions, and its APIs are mainly used to start the device selection module. **The continuation capability is not available for application development.**
+
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
+## Modules to Import
+
+```js
+import continuationManager from '@ohos.continuation.continuationManager'
+```
+
+## continuationManager.register
+
+register(callback: AsyncCallback\): void;
+
+Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | callback | AsyncCallback\ | Yes| Callback used to return the token generated after the continuation management service is connected.|
+
+**Example**
+
+ ```js
+ let token = -1;
+ continuationManager.register((err, data) => {
+ if (err.code != 0) {
+ console.error('register failed, cause: ' + JSON.stringify(err));
+ return;
+ }
+ console.info('register finished, ' + JSON.stringify(data));
+ token = data;
+ });
+ ```
+
+## continuationManager.register
+
+register(options: ContinuationExtraParams, callback: AsyncCallback\): void;
+
+Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.|
+ | callback | AsyncCallback\ | Yes| Callback used to return the token generated after the continuation management service is connected.|
+
+**Example**
+
+ ```js
+ let token = -1;
+ let continuationExtraParams = {
+ deviceType: ["00E"]
+ };
+ continuationManager.register(continuationExtraParams, (err, data) => {
+ if (err.code != 0) {
+ console.error('register failed, cause: ' + JSON.stringify(err));
+ return;
+ }
+ console.info('register finished, ' + JSON.stringify(data));
+ token = data;
+ });
+ ```
+
+## continuationManager.register
+
+register(options?: ContinuationExtraParams): Promise\;
+
+Registers the continuation management service and obtains a token. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.|
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | ------------------ |
+| Promise\ | Promise used to return the token generated after the continuation management service is connected.|
+
+**Example**
+
+ ```js
+ let token = -1;
+ let continuationExtraParams = {
+ deviceType: ["00E"]
+ };
+ continuationManager.register(continuationExtraParams)
+ .then((data) => {
+ console.info('register finished, ' + JSON.stringify(data));
+ token = data;
+ })
+ .catch((err) => {
+ console.error('register failed, cause: ' + JSON.stringify(err));
+ });
+ ```
+
+## continuationManager.on("deviceConnect")(deprecated)
+> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect) instead.
+
+on(type: "deviceConnect", callback: Callback\): void;
+
+Subscribes to device connection events. This API uses an asynchronous callback to return the result.
+
+## continuationManager.on("deviceDisconnect")(deprecated)
+> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect) instead.
+
+on(type: "deviceDisconnect", callback: Callback\): void;
+
+Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.
+
+## continuationManager.off("deviceConnect")(deprecated)
+> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect) instead.
+
+off(type: "deviceConnect", callback?: Callback\): void;
+
+Unsubscribes from device connection events. This API uses an asynchronous callback to return the result.
+
+## continuationManager.off("deviceDisconnect")(deprecated)
+> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect) instead.
+
+off(type: "deviceDisconnect", callback?: Callback\): void;
+
+Unsubscribes from device disconnection events. This API uses an asynchronous callback to return the result.
+
+## continuationManager.on("deviceConnect")9+
+
+on(type: "deviceConnect", token: number, callback: Callback\>): void;
+
+Subscribes to device connection events. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | callback | Callback\> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ continuationManager.on("deviceConnect", token, (data) => {
+ console.info('onDeviceConnect len: ' + data.length);
+ for (let i = 0; i < data.length; i++) {
+ console.info('onDeviceConnect deviceId: ' + JSON.stringify(data[i].id));
+ console.info('onDeviceConnect deviceType: ' + JSON.stringify(data[i].type));
+ console.info('onDeviceConnect deviceName: ' + JSON.stringify(data[i].name));
+ }
+ });
+ ```
+
+## continuationManager.on("deviceDisconnect")9+
+
+on(type: "deviceDisconnect", token: number, callback: Callback\>): void;
+
+Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | callback | Callback\> | Yes| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ continuationManager.on("deviceDisconnect", token, (data) => {
+ console.info('onDeviceDisconnect len: ' + data.length);
+ for (let i = 0; i < data.length; i++) {
+ console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data[i]));
+ }
+ console.info('onDeviceDisconnect finished.');
+ });
+ ```
+
+## continuationManager.off("deviceConnect")9+
+
+off(type: "deviceConnect", token: number): void;
+
+Unsubscribes from device connection events.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ continuationManager.off("deviceConnect", token);
+ ```
+
+## continuationManager.off("deviceDisconnect")9+
+
+off(type: "deviceDisconnect", token: number): void;
+
+Unsubscribes from device disconnection events.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ continuationManager.off("deviceDisconnect", token);
+ ```
+
+## continuationManager.startDeviceManager
+
+startDeviceManager(token: number, callback: AsyncCallback\): void;
+
+Starts the device selection module to show the list of available devices on the network. This API does not involve any filter parameters and uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | callback | AsyncCallback\ | Yes| Callback used to return the result.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ continuationManager.startDeviceManager(token, (err, data) => {
+ if (err.code != 0) {
+ console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
+ return;
+ }
+ console.info('startDeviceManager finished, ' + JSON.stringify(data));
+ });
+ ```
+
+## continuationManager.startDeviceManager
+
+startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void;
+
+Starts the device selection module to show the list of available devices on the network. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.|
+ | callback | AsyncCallback\ | Yes| Callback used to return the result.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ let continuationExtraParams = {
+ deviceType: ["00E"]
+ };
+ continuationManager.startDeviceManager(token, continuationExtraParams, (err, data) => {
+ if (err.code != 0) {
+ console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
+ return;
+ }
+ console.info('startDeviceManager finished, ' + JSON.stringify(data));
+ });
+ ```
+
+## continuationManager.startDeviceManager
+
+startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\;
+
+Starts the device selection module to show the list of available devices on the network. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.|
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | ------------------ |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ let continuationExtraParams = {
+ deviceType: ["00E"]
+ };
+ continuationManager.startDeviceManager(token, continuationExtraParams)
+ .then((data) => {
+ console.info('startDeviceManager finished, ' + JSON.stringify(data));
+ })
+ .catch((err) => {
+ console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
+ });
+ ```
+
+## continuationManager.updateConnectStatus
+
+updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\): void;
+
+Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | deviceId | string | Yes| Device ID.|
+ | status | [DeviceConnectState](#deviceconnectstate) | Yes| Device connection state.|
+ | callback | AsyncCallback\ | Yes| Callback used to return the result.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ let deviceId: string = "test deviceId";
+ continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED, (err, data) => {
+ if (err.code != 0) {
+ console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
+ return;
+ }
+ console.info('updateConnectStatus finished, ' + JSON.stringify(data));
+ });
+ ```
+
+## continuationManager.updateConnectStatus
+
+updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState): Promise\;
+
+Instructs the device selection module to update the device connection state. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | deviceId | string | Yes| Device ID.|
+ | status | [DeviceConnectState](#deviceconnectstate) | Yes| Device connection state.|
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | ------------------ |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ let deviceId: string = "test deviceId";
+ continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED)
+ .then((data) => {
+ console.info('updateConnectStatus finished, ' + JSON.stringify(data));
+ })
+ .catch((err) => {
+ console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
+ });
+ ```
+
+## continuationManager.unregister
+
+unregister(token: number, callback: AsyncCallback\): void;
+
+Deregisters the continuation management service. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+ | callback | AsyncCallback\ | Yes| Callback used to return the result.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ continuationManager.unregister(token, (err, data) => {
+ if (err.code != 0) {
+ console.error('unregister failed, cause: ' + JSON.stringify(err));
+ return;
+ }
+ console.info('unregister finished, ' + JSON.stringify(data));
+ });
+ ```
+
+## continuationManager.unregister
+
+unregister(token: number): Promise\;
+
+Deregisters the continuation management service. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | token | number | Yes| Token obtained after the registration of the continuation management service.|
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | ------------------ |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+ ```js
+ let token = 1;
+ continuationManager.unregister(token)
+ .then((data) => {
+ console.info('unregister finished, ' + JSON.stringify(data));
+ })
+ .catch((err) => {
+ console.error('unregister failed, cause: ' + JSON.stringify(err));
+ });
+ ```
+
+## DeviceConnectState
+
+Enumerates the device connection states.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Value| Description|
+ | -------- | -------- | -------- | -------- |
+ | IDLE | number | 0 | The device is in the initial state.|
+ | CONNECTING | number | 1 | The device is being connected.|
+ | CONNECTED | number | 2 | The device is connected.|
+ | DISCONNECTING | number | 3 | The device is being disconnected.|
+
+## ContinuationMode
+
+Enumerates the continuation modes provided by the device selection module.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+**Parameters**
+
+ | Name| Type| Value| Description|
+ | -------- | -------- | -------- | -------- |
+ | COLLABORATION_SINGLE | number | 0 | Single-choice mode.|
+ | COLLABORATION_MULTIPLE | number | 1 | Multi-choice mode.|
diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md
new file mode 100644
index 0000000000000000000000000000000000000000..bdebb727ff7b5c6b41868f37bf5ecdb0ea333d10
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md
@@ -0,0 +1,17 @@
+# ContinuationResult
+
+> **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.
+
+## ContinuationResult
+
+Describes the device information returned by the continuation management entry.
+
+**System capability**: SystemCapability.Ability.DistributedAbilityManager
+
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| id | string | Yes| Yes| Device ID.|
+| type | string | Yes| Yes| Device type.|
+| name | string | Yes| Yes| Device name.|
diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md
index 3fd4e4e52ca7a82b33dd6a13aa7f425ab2aea9be..43e096b951e7ea4d97ed9e0d40dc0481f34a0290 100644
--- a/en/application-dev/reference/apis/js-apis-convertxml.md
+++ b/en/application-dev/reference/apis/js-apis-convertxml.md
@@ -1,6 +1,9 @@
# XML-to-JavaScript Conversion
-> **NOTE**
+The **convertxml** module provides APIs for converting XML text into JavaScript objects.
+
+> **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.
@@ -47,10 +50,10 @@ let xml =
'';
let conv = new convertxml.ConvertXML();
let options = {trim : false, declarationKey:"_declaration",
- instructionKey : "_instruction", attributesKey : "_attributes",
- textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype",
- commentKey : "_comment", parentKey : "_parent", typeKey : "_type",
- nameKey : "_name", elementsKey : "_elements"}
+ instructionKey : "_instruction", attributesKey : "_attributes",
+ textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype",
+ commentKey : "_comment", parentKey : "_parent", typeKey : "_type",
+ nameKey : "_name", elementsKey : "_elements"}
let result = JSON.stringify(conv.convert(xml, options));
console.log(result)
```
diff --git a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md
index b0666612257857244fdffc8462cfd9719883412a..dc239c35cbe017f7c5edc0a9fd8ff1bd74b3c366 100644
--- a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md
+++ b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md
@@ -1,8 +1,8 @@
# Value Bucket
-The **ValueBucket** holds data in key-value (KV) pairs. You can use it to insert data into a database.
+The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database.
->**Note**
+>**NOTE**
>
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -20,7 +20,7 @@ Enumerates the value types allowed by the database.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
-| Name | Description |
+| Type | Description |
| ------- | -------------------- |
| number | The value is a number. |
| string | The value is a string.|
@@ -28,10 +28,10 @@ Enumerates the value types allowed by the database.
## ValuesBucket
-Holds a set of KV pairs.
+Defines the types of the key and value in a KV pair.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
-| Name | Type | Mandatory| Description |
-| ------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
-| [key: string] | [ValueType](#valuetype)\| Uint8Array \| null | Yes | KV pairs in a **ValuesBucket**. The key is of the string type. The value can be a number, string, Boolean value, Unit8Array, or **null**.|
+| Key Type | Value Type |
+| ------------- | --------------------------------------------- |
+| string | [ValueType](#valuetype)\| Uint8Array \| null |
diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md
index a1c0aba0f59aa5831cfa2e54cbad92302b8724c8..3860be1f4cd4fae2b432c7286ae5aca1c2b44868 100644
--- a/en/application-dev/reference/apis/js-apis-data-ability.md
+++ b/en/application-dev/reference/apis/js-apis-data-ability.md
@@ -789,7 +789,7 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
-| Name | Description |
+| Type | Description |
| ------- | -------------------- |
| number | The value is a number. |
| string | The value is a string. |
diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md
index 63371ed42b8eb940caa8072ffda6aa17d78658c5..560696c1ca48cb404aa0a29e95f8c3c1a1841198 100644
--- a/en/application-dev/reference/apis/js-apis-data-preferences.md
+++ b/en/application-dev/reference/apis/js-apis-data-preferences.md
@@ -681,7 +681,7 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
-| Name | Description |
+| Type | Description |
| -------------- | ------------------------------ |
| number | The value is a number. |
| string | The value is a string. |
diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md
index 65bec3ec53825f544a6bbda1618eda19d7abb708..38c07d6247487e037e9158a00e5c2f752621b44e 100644
--- a/en/application-dev/reference/apis/js-apis-data-rdb.md
+++ b/en/application-dev/reference/apis/js-apis-data-rdb.md
@@ -781,13 +781,6 @@ Sets the **RdbPredicates** to filter out duplicate records.
```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct("NAME")
-let promise = rdbStore.query(predicates, ["NAME"])
-promise.then((resultSet) => {
- console.log("ResultSet column names: " + resultSet.columnNames)
- console.log("ResultSet column count: " + resultSet.columnCount)
-}).catch((err) => {
- console.log("Query err.")
-})
```
@@ -1133,7 +1126,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) {
```
### update9+
-update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise<number>
+update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number>
Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
@@ -1215,7 +1208,7 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object.
**Return value**
| Type| Description|
| -------- | -------- |
-| Promise<number> | Promise used to return the number of rows updated.|
+| Promise<number> | Promise used to return the number of rows updated.|
**Example**
```js
@@ -1231,7 +1224,7 @@ promise.then((rows) => {
### delete9+
-delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback<number>):void
+delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void
Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
@@ -1275,7 +1268,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o
**Return value**
| Type| Description|
| -------- | -------- |
-| Promise<number> | Promise used to return the number of rows updated.|
+| Promise<number> | Promise used to return the number of rows updated.|
**Example**
```js
@@ -1354,7 +1347,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro
### query9+
-query(predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void
+query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void
Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
@@ -1363,6 +1356,7 @@ Queries data in the RDB store based on specified conditions. This API uses an as
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
+| table | string | Yes| Name of the target table.|
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.|
| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.|
| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
@@ -1384,7 +1378,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"],
### query9+
-query(predicates: DataSharePredicates, columns?: Array<string>):Promise<ResultSet>
+query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet>
Queries data in the RDB store based on specified conditions. This API uses a promise to return the result.
@@ -1393,6 +1387,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
+| table | string | Yes| Name of the target table.|
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.|
| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.|
@@ -1591,7 +1586,7 @@ rdbStore.commit()
### rollBack8+
-rollBack():void;
+rollBack():void
Rolls back the SQL statements that have been executed.
@@ -1997,7 +1992,7 @@ Defines the data types allowed.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-| Name| Description|
+| Type| Description|
| -------- | -------- |
| number | Number.|
| string | String.|
@@ -2006,14 +2001,13 @@ Defines the data types allowed.
## ValuesBucket
-Defines a bucket to store key-value pairs.
+Defines the types of the key and value in a KV pair.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| [key: string] | [ValueType](#valuetype)\| Uint8Array \| null | Yes| Defines a bucket to store key-value pairs.|
-
+| Key Type| Value Type|
+| -------- | -------- |
+| string | [ValueType](#valuetype)\| Uint8Array \| null |
## SyncMode8+
diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md
index 47a961f7cceb3c20de583387d9ed54d5494e5ac4..45465710a587c51fea60e7c59f2b804c80888043 100644
--- a/en/application-dev/reference/apis/js-apis-data-storage.md
+++ b/en/application-dev/reference/apis/js-apis-data-storage.md
@@ -793,7 +793,7 @@ Enumerates the value types.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
-| Name | Description |
+| Type | Description |
| ------- | -------------------- |
| number | The value is a number. |
| string | The value is a string. |
diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md
index dc674978d2c4b9491e860b13f1720787380cc53e..7d094be2e3b6a425e1c8b0eea194cb1085fd3505 100644
--- a/en/application-dev/reference/apis/js-apis-distributed-account.md
+++ b/en/application-dev/reference/apis/js-apis-distributed-account.md
@@ -94,7 +94,7 @@ Updates distributed account information. This API uses an asynchronous callback
**System capability**: SystemCapability.Account.OsAccount
-**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications)
+**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters
| Name| Type| Mandatory| Description|
@@ -119,7 +119,7 @@ Updates distributed account information. This API uses a promise to return the r
**System capability**: SystemCapability.Account.OsAccount
-**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications)
+**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters
| Name| Type| Mandatory| Description|
diff --git a/en/application-dev/reference/apis/js-apis-distributed-data .md b/en/application-dev/reference/apis/js-apis-distributed-data .md
new file mode 100644
index 0000000000000000000000000000000000000000..5682921badad9367817fd3e421b1afb823970425
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-distributed-data .md
@@ -0,0 +1,5671 @@
+# Distributed Data Management
+
+The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases.
+
+This module provides the following functions:
+
+- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores.
+- [KvStoreResultSet8+](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position.
+- [Query8+](#query8): provides methods to query data from the database through a **Query** instance by using predicates.
+- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance.
+- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device.
+- [DeviceKVStore8+ ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device.
+
+>**NOTE**
+>
+>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
+
+## Modules to Import
+
+```js
+import distributedData from '@ohos.data.distributedData';
+```
+
+
+## distributedData.createKVManager
+
+createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
+
+Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.|
+| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.|
+
+**Example**
+
+Stage model:
+```ts
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context,
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+FA model:
+```js
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context.getApplicationContext(),
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+## distributedData.createKVManager
+
+createKVManager(config: KVManagerConfig): Promise<KVManager>
+
+Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.|
+
+**Example**
+
+Stage model:
+```ts
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context,
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+FA model:
+```js
+import AbilityStage from '@ohos.application.Ability'
+let kvManager;
+export default class MyAbilityStage extends AbilityStage {
+ onCreate() {
+ console.log("MyAbilityStage onCreate")
+ let context = this.context
+ const kvManagerConfig = {
+ context: context.getApplicationContext(),
+ bundleName: 'com.example.datamanagertest',
+ userInfo: {
+ userId: '0',
+ userType: distributedData.UserType.SAME_USER_ID
+ }
+ }
+ distributedData.createKVManager(kvManagerConfig, function (err, manager) {
+ if (err) {
+ console.log("Failed to create KVManager: " + JSON.stringify(err));
+ return;
+ }
+ console.log("Created KVManager");
+ kvManager = manager;
+ });
+ }
+}
+```
+
+## KVManagerConfig
+
+Provides configuration of the **KVManager** object, including the bundle name and user information of the caller.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).|
+| userInfo | [UserInfo](#userinfo) | Yes | User information.|
+| bundleName | string | Yes | Bundle name.|
+
+## UserInfo
+
+Defines user information.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| userId | string | Yes | User ID.|
+| userType | [UserType](#usertype) | Yes | User type.|
+
+
+## UserType
+
+Enumerates the user types.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name| Value| Description|
+| ----- | ------ | ------ |
+| SAME_USER_ID | 0 | User who logs in to different devices using the same account.|
+
+
+## KVManager
+
+Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use [createKVManager](#distributeddatacreatekvmanager) to create a **KVManager** object.
+
+### getKVStore
+
+getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
+
+Creates and obtains a KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| ----- | ------ | ------ | ------ |
+| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| options | [Options](#options) | Yes | Configuration of the KV store.|
+| callback | AsyncCallback<T> , <T extends [KVStore](#kvstore)>| Yes | Callback invoked to return the KV store created.|
+
+**Example**
+
+```js
+let kvStore;
+let kvManager;
+try {
+ const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ securityLevel : distributedData.SecurityLevel.S2,
+ };
+ kvManager.getKVStore('storeId', options, function (err, store) {
+ if (err) {
+ console.log("getKVStore err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("getKVStore success");
+ kvStore = store;
+ });
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### getKVStore
+
+getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T>
+
+Creates and obtains a KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ------- | ---------------------- | ---- | -------------------- |
+| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| options | [Options](#options) | Yes | Configuration of the KV store.|
+
+
+**Return value**
+
+| Type | Description |
+| -------------------------------------- | ------------------------ |
+| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.|
+
+**Example**
+
+```js
+let kvStore;
+let kvManager;
+try {
+ const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ securityLevel : distributedData.SecurityLevel.S2,
+ };
+ kvManager.getKVStore('storeId', options).then((store) => {
+ console.log("getKVStore success");
+ kvStore = store;
+ }).catch((err) => {
+ console.log("getKVStore err: " + JSON.stringify(err));
+ });
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### closeKVStore8+ ###
+
+closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void
+
+Closes a KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+
+| Name | Type | Mandatory| Description |
+| ------- | ----------------- | ---- | --------------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| kvStore | [KVStore](#kvstore) | Yes | KV store to close. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+let kvManager;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+ }
+ try {
+ kvManager.getKVStore('storeId', options, async function (err, store) {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) {
+ console.log('closeKVStore success');
+ });
+ });
+} catch (e) {
+ console.log('closeKVStore e ' + e);
+}
+```
+
+
+### closeKVStore8+ ###
+
+closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void>
+
+Closes a KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| kvStore | [KVStore](#kvstore) | Yes | KV store to close. |
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| Promise\ | Promise that returns no value.|
+
+**Example**
+
+```js
+let kvManager;
+let kvStore;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+}
+ try {
+ kvManager.getKVStore('storeId', options).then(async (store) => {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => {
+ console.log('closeKVStore success');
+ }).catch((err) => {
+ console.log('closeKVStore err ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('CloseKVStore getKVStore err ' + JSON.stringify(err));
+ });
+ } catch (e) {
+ console.log('closeKVStore e ' + e);
+}
+```
+
+
+### deleteKVStore8+ ###
+
+deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void
+
+Deletes a KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+let kvManager;
+let kvStore;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+}
+try {
+ kvManager.getKVStore('store', options, async function (err, store) {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.deleteKVStore('appId', 'storeId', function (err, data) {
+ console.log('deleteKVStore success');
+ });
+ });
+} catch (e) {
+ console.log('DeleteKVStore e ' + e);
+}
+```
+
+### deleteKVStore8+ ###
+
+deleteKVStore(appId: string, storeId: string): Promise<void>
+
+Deletes a KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
+
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| Promise<void> | Promise that returns no value.|
+
+**Example**
+
+```js
+let kvManager;
+let kvStore;
+const options = {
+ createIfMissing : true,
+ encrypt : false,
+ backup : false,
+ autoSync : true,
+ kvStoreType : distributedData.KVStoreType.SINGLE_VERSION,
+ schema : '',
+ securityLevel : distributedData.SecurityLevel.S2,
+}
+try {
+ kvManager.getKVStore('storeId', options).then(async (store) => {
+ console.log('getKVStore success');
+ kvStore = store;
+ kvManager.deleteKVStore('appId', 'storeId').then(() => {
+ console.log('deleteKVStore success');
+ }).catch((err) => {
+ console.log('deleteKVStore err ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('getKVStore err ' + JSON.stringify(err));
+ });
+} catch (e) {
+ console.log('deleteKVStore e ' + e);
+}
+```
+
+
+### getAllKVStoreId8+ ###
+
+getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void
+
+Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+| callback | AsyncCallback<string[]> | Yes |Callback used to return the KV store IDs obtained. |
+
+**Example**
+
+```js
+let kvManager;
+try {
+ kvManager.getAllKVStoreId('appId', function (err, data) {
+ console.log('GetAllKVStoreId success');
+ console.log('GetAllKVStoreId size = ' + data.length);
+ });
+} catch (e) {
+ console.log('GetAllKVStoreId e ' + e);
+}
+```
+
+
+### getAllKVStoreId8+ ###
+
+getAllKVStoreId(appId: string): Promise<string[]>
+
+Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| appId | string | Yes | Bundle name of the app that invokes the KV store. |
+
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| Promise<string[]>| Promise used to return the KV store IDs obtained.|
+
+**Example**
+
+```js
+let kvManager;
+try {
+ console.log('GetAllKVStoreId');
+ kvManager.getAllKVStoreId('appId').then((data) => {
+ console.log('getAllKVStoreId success');
+ console.log('size = ' + data.length);
+ }).catch((err) => {
+ console.log('getAllKVStoreId err ' + JSON.stringify(err));
+ });
+} catch(e) {
+ console.log('getAllKVStoreId e ' + e);
+}
+```
+
+
+### on('distributedDataServiceDie')8+ ###
+
+on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void
+
+Subscribes to service status changes.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates service status changes.|
+| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.|
+
+**Example**
+
+```js
+let kvManager;
+try {
+
+ console.log('KVManagerOn');
+ const deathCallback = function () {
+ console.log('death callback call');
+ }
+ kvManager.on('distributedDataServiceDie', deathCallback);
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### off('distributedDataServiceDie')8+ ###
+
+off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void
+
+Unsubscribes from the service status changes.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates service status changes.|
+| deathCallback | Callback<void> | No | Callback used to return service status changes.|
+
+
+**Example**
+
+```js
+let kvManager;
+try {
+ console.log('KVManagerOff');
+ const deathCallback = function () {
+ console.log('death callback call');
+ }
+ kvManager.off('distributedDataServiceDie', deathCallback);
+} catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+
+```
+
+## Options
+
+Provides KV store configuration.
+
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC |
+| kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
+| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
+| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
+
+
+## KVStoreType
+
+Enumerates the KV store types.
+
+
+| Name | Value| Description |
+| --- | ---- | ----------------------- |
+| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
+| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
+| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
+
+
+## SecurityLevel
+
+Enumerates the KV store security levels.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value| Description |
+| --- | ---- | ----------------------- |
+| NO_LEVEL | 0 | No security level is set for the KV store. |
+| S0 | 1 | The KV store security level is public.|
+| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.|
+| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.|
+| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.|
+| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.|
+
+
+## Constants
+
+Defines the KV store constants.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value| Description |
+| --- | ---- | ----------------------- |
+| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. |
+| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the KV store, in bytes. |
+| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes.|
+| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. |
+| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.|
+| MAX_BATCH_SIZE | 128 | Maximum number of batch operations.|
+
+## Schema8+ ##
+
+Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+| Name | Type| Description |
+| --- | ---- | ----------------------- |
+| root8+ | [FieldNode](#fieldnode8) | JSON root object.|
+| indexes8+ | Array\ | String array in JSON format. |
+| mode8+ | number | Schema mode. |
+| skip8+ | number | Size of a skip of the schema. |
+
+### constructor8+ ###
+
+constructor()
+
+A constructor used to create a **Schema** instance.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+## FieldNode8+ ##
+
+Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+| Name | Type| Description |
+| --- | ---- | ----------------------- |
+| nullable8+ | boolean | Whether the database field can be null. |
+| default8+ | string | Default value of a **FieldNode**.|
+| type8+ | number | Value of the data type corresponding to the specified node.|
+
+### constructor8+ ###
+
+constructor(name: string)
+
+A constructor used to create a **FieldNode** instance with a string field.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name| Type| Mandatory| Description |
+| ------ | -------- | ---- | --------------- |
+| name | string | Yes | Value of **FieldNode**.|
+
+### appendChild8+ ###
+
+appendChild(child: FieldNode): boolean
+
+Appends a child node to this **FieldNode**.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| child | [FieldNode](#fieldnode8) | Yes | Child node to append. |
+
+**Return value**
+
+| Type | Description |
+| ------------- | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise.|
+
+**Example**
+
+```js
+import ddm from '@ohos.data.distributedData';
+try {
+ let node = new ddm.FieldNode("root");
+ let child1 = new ddm.FieldNode("child1");
+ let child2 = new ddm.FieldNode("child2");
+ let child3 = new ddm.FieldNode("child3");
+ node.appendChild(child1);
+ node.appendChild(child2);
+ node.appendChild(child3);
+ console.log("appendNode " + JSON.stringify(node));
+ child1 = null;
+ child2 = null;
+ child3 = null;
+ node = null;
+} catch (e) {
+ console.log("AppendChild " + e);
+}
+```
+
+
+## KvStoreResultSet8+ ##
+
+Provides methods to obtain the KV store result sets, and query and move the data read position.
+
+Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object.
+
+
+### getCount8+ ###
+
+getCount(): number
+
+Obtains the total number of rows in the result set.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| number |Total number of rows obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const count = resultSet.getCount();
+ console.log("getCount succeed:" + count);
+} catch (e) {
+ console.log("getCount failed: " + e);
+}
+```
+
+### getPosition8+ ###
+
+getPosition(): number
+
+Obtains the current data read position (position from which data is read) in the result set.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| number |Current data read position obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeeded.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const position = resultSet.getPosition();
+ console.log("getPosition succeed:" + position);
+} catch (e) {
+ console.log("getPosition failed: " + e);
+}
+```
+
+
+### moveToFirst8+ ###
+
+moveToFirst(): boolean
+
+Moves the data read position to the first row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved1 = resultSet.moveToFirst();
+ console.log("moveToFirst succeed: " + moved1);
+} catch (e) {
+ console.log("moveToFirst failed " + e);
+}
+```
+
+
+### moveToLast8+ ###
+
+moveToLast(): boolean
+
+Moves the data read position to the last row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved2 = resultSet.moveToLast();
+ console.log("moveToLast succeed:" + moved2);
+} catch (e) {
+ console.log("moveToLast failed: " + e);
+}
+```
+
+
+### moveToNext8+ ###
+
+moveToNext(): boolean
+
+Moves the data read position to the next row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved3 = resultSet.moveToNext();
+ console.log("moveToNext succeed: " + moved3);
+} catch (e) {
+ console.log("moveToNext failed: " + e);
+}
+```
+
+
+### moveToPrevious8+ ###
+
+moveToPrevious(): boolean
+
+Moves the data read position to the previous row. If the result set is empty, **false** will be returned.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved4 = resultSet.moveToPrevious();
+ console.log("moveToPrevious succeed:" + moved4);
+} catch (e) {
+ console.log("moveToPrevious failed: " + e);
+}
+```
+
+
+### move8+ ###
+
+move(offset: number): boolean
+
+Moves the data read position with the specified offset from the current position.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward. |
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved5 = resultSet.move();
+ console.log("move succeed:" + moved5);
+} catch (e) {
+ console.log("move failed: " + e);
+}
+```
+
+
+### moveToPosition8+ ###
+
+moveToPosition(position: number): boolean
+
+Moves the data read position from 0 to an absolute position.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| position | number | Yes |Absolute position to move to. |
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the operation is successful; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const moved6 = resultSet.moveToPosition();
+ console.log("moveToPosition succeed: " + moved6);
+} catch (e) {
+ console.log("moveToPosition failed: " + e);
+}
+```
+
+
+### isFirst8+ ###
+
+isFirst(): boolean
+
+Checks whether the data read position is the first row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the first row is being read; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const isfirst = resultSet.isFirst();
+ console.log("Check isFirst succeed:" + isfirst);
+} catch (e) {
+ console.log("Check isFirst failed: " + e);
+}
+```
+
+
+### isLast8+ ###
+
+isLast(): boolean
+
+Checks whether the data read position is the last row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the last row is being read; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const islast = resultSet.isLast();
+ console.log("Check isLast succeed: " + islast);
+} catch (e) {
+ console.log("Check isLast failed: " + e);
+}
+```
+
+### isBeforeFirst8+ ###
+
+isBeforeFirst(): boolean
+
+Checks whether the data read position is before the first row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the data read position is before the first row; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const isbeforefirst = resultSet.isBeforeFirst();
+ console.log("Check isBeforeFirst succeed: " + isbeforefirst);
+} catch (e) {
+ console.log("Check isBeforeFirst failed: " + e);
+}
+```
+
+
+### isAfterLast8+ ###
+
+isAfterLast(): boolean
+
+Checks whether the data read position is after the last row.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------- |
+| boolean |Returns **true** if the data read position is after the last row; returns **false** otherwise. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const isafterlast = resultSet.isAfterLast();
+ console.log("Check isAfterLast succeed:" + isafterlast);
+} catch (e) {
+ console.log("Check isAfterLast failed: " + e);
+}
+```
+
+
+### getEntry8+ ###
+
+getEntry(): Entry
+
+Obtains the KV pair from the current position.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Entry](#entry) |KV pair obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + err);
+ });
+ const entry = resultSet.getEntry();
+ console.log("getEntry succeed:" + JSON.stringify(entry));
+} catch (e) {
+ console.log("getEntry failed: " + e);
+}
+```
+
+
+## Query8+ ##
+
+Provides methods to create a **Query** object, which defines different data query criteria.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+### constructor8+ ###
+
+constructor()
+
+A constructor used to create a **Schema** instance.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+
+### reset8+ ###
+
+reset(): Query
+
+Resets the **Query** object.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object reset.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.equalTo("key", "value");
+ console.log("query is " + query.getSqlLike());
+ query.reset();
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("simply calls should be ok :" + e);
+}
+```
+
+
+### equalTo8+ ###
+
+equalTo(field: string, value: number|string|boolean): Query
+
+Creates a **Query** object to match the specified field whose value is equal to the given value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.equalTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### notEqualTo8+ ###
+
+notEqualTo(field: string, value: number|string|boolean): Query
+
+Creates a **Query** object to match the specified field whose value is not equal to the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### greaterThan8+ ###
+
+greaterThan(field: string, value: number|string|boolean): Query
+
+Creates a **Query** object to match the specified field whose value is greater than the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.greaterThan("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### lessThan8+ ###
+
+lessThan(field: string, value: number|string): Query
+
+Creates a **Query** object to match the specified field whose value is less than the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.lessThan("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### greaterThanOrEqualTo8+ ###
+
+greaterThanOrEqualTo(field: string, value: number|string): Query
+
+Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.greaterThanOrEqualTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### lessThanOrEqualTo8+ ###
+
+lessThanOrEqualTo(field: string, value: number|string): Query
+
+Creates a **Query** object to match the specified field whose value is less than or equal to the specified value.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | number\|string\|boolean | Yes | Value specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.lessThanOrEqualTo("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### isNull8+ ###
+
+isNull(field: string): Query
+
+Creates a **Query** object to match the specified field whose value is **null**.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.isNull("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### inNumber8+ ###
+
+inNumber(field: string, valueList: number[]): Query
+
+Creates a **Query** object to match the specified field whose value is within the specified list of numbers.
+
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | number[] | Yes | List of numbers.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.inNumber("field", [0, 1]);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### inString8+ ###
+
+inString(field: string, valueList: string[]): Query
+
+Creates a **Query** object to match the specified field whose value is within the specified list of strings.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | string[] | Yes | List of strings.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.inString("field", ['test1', 'test2']);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### notInNumber8+ ###
+
+notInNumber(field: string, valueList: number[]): Query
+
+Creates a **Query** object to match the specified field whose value is not within the specified list of numbers.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | number[] | Yes | List of numbers.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notInNumber("field", [0, 1]);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### notInString8+ ###
+
+notInString(field: string, valueList: string[]): Query
+
+Creates a **Query** object to match the specified field whose value is not within the specified list of strings.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| valueList | string[] | Yes | List of strings.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notInString("field", ['test1', 'test2']);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### like8+ ###
+
+like(field: string, value: string): Query
+
+Creates a **Query** object to match the specified field whose value is similar to the specified string.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | string | Yes | String specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.like("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### unlike8+ ###
+
+unlike(field: string, value: string): Query
+
+Creates a **Query** object to match the specified field whose value is not similar to the specified string.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+| value | string | Yes | String specified.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.unlike("field", "value");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### and8+ ###
+
+and(): Query
+
+Creates a **Query** object with the AND condition.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object Created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value1");
+ query.and();
+ query.notEqualTo("field", "value2");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### or8+ ###
+
+or(): Query
+
+Creates a **Query** object with the OR condition.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object Created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value1");
+ query.or();
+ query.notEqualTo("field", "value2");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### orderByAsc8+ ###
+
+orderByAsc(field: string): Query
+
+Creates a **Query** object to sort the query results in ascending order.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ query.orderByAsc("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### orderByDesc8+ ###
+
+orderByDesc(field: string): Query
+
+Creates a **Query** object to sort the query results in descending order.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ query.orderByDesc("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### limit8+ ###
+
+limit(total: number, offset: number): Query
+
+Creates a **Query** object to specify the number of results and where to start.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| total | number | Yes |Number of results to query. |
+| offset | number | Yes |Start position for query. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+let total = 10;
+let offset = 1;
+try {
+ let query = new distributedData.Query();
+ query.notEqualTo("field", "value");
+ query.limit(total, offset);
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### isNotNull8+ ###
+
+isNotNull(field: string): Query
+
+Creates a **Query** object to match the specified field whose value is not **null**.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| fieId | string | Yes |Field to match. It cannot contain '^'. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.isNotNull("field");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### beginGroup8+ ###
+
+beginGroup(): Query
+
+Creates a **Query** object for a query condition group with a left parenthesis.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.beginGroup();
+ query.isNotNull("field");
+ query.endGroup();
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### endGroup8+ ###
+
+endGroup(): Query
+
+Creates a **Query** object for a query condition group with a right parenthesis.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.beginGroup();
+ query.isNotNull("field");
+ query.endGroup();
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### prefixKey8+ ###
+
+prefixKey(prefix: string): Query
+
+Creates a **Query** object with a specified key prefix.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| prefix | string | Yes |Key prefix. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.prefixKey("$.name");
+ query.prefixKey("0");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### setSuggestIndex8+ ###
+
+setSuggestIndex(index: string): Query
+
+Creates a **Query** object with an index preferentially used for query.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| index | string | Yes |Index preferentially used for query. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.setSuggestIndex("$.name");
+ query.setSuggestIndex("0");
+ console.log("query is " + query.getSqlLike());
+ query = null;
+} catch (e) {
+ console.log("duplicated calls should be ok :" + e);
+}
+```
+
+
+### deviceId8+ ###
+
+deviceId(deviceId:string):Query
+
+Creates a **Query** object with the device ID as the key prefix.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId | string | Yes |Device ID. |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| [Query](#query8) |**Query** object created.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ query.deviceId("deviceId");
+ console.log("query is " + query.getSqlLike());
+} catch (e) {
+ console.log("should be ok on Method Chaining : " + e);
+}
+```
+
+
+### getSqlLike8+ ###
+
+getSqlLike():string
+
+Obtains the query statement of the **Query** object.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| string |Returns the query statement obtained.|
+
+**Example**
+
+```js
+try {
+ let query = new distributedData.Query();
+ let sql1 = query.getSqlLike();
+ console.log("GetSqlLike sql=" + sql1);
+} catch (e) {
+ console.log("duplicated calls should be ok : " + e);
+}
+```
+
+
+## KVStore
+
+Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization.
+
+Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object.
+
+### put
+
+put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void
+
+Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). |
+| callback | AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("put err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("put success");
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### put
+
+put(key: string, value: Uint8Array | string | number | boolean): Promise<void>
+
+Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
+ console.log("put success: " + JSON.stringify(data));
+ }).catch((err) => {
+ console.log("put err: " + JSON.stringify(err));
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### delete
+
+delete(key: string, callback: AsyncCallback<void>): void
+
+Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| callback | AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("put err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("put success");
+ kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("delete err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("delete success");
+ });
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### delete
+
+delete(key: string): Promise<void>
+
+Deletes a KV pair from this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
+ console.log("put success: " + JSON.stringify(data));
+ kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log("delete success");
+ }).catch((err) => {
+ console.log("delete err: " + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log("put err: " + JSON.stringify(err));
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### delete9+
+
+delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>)
+
+Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.|
+| callback | AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ kvStore.delete(predicates, function (err, data) {
+ if (err == undefined) {
+ console.log('delete success');
+ } else {
+ console.log('delete fail' + err);
+ }
+ });
+} catch (e) {
+ console.log('An unexpected error occurred. Error:' + e);
+}
+```
+
+### delete9+
+
+delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void>
+
+Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.|
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise used to return the result.|
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let arr = ["name"];
+ predicates.inKeys(arr);
+ kvStore.put("name", "bob").then((data) => {
+ console.log('put success' + JSON.stringify(data));
+ kvStore.delete(predicates).then((data) => {
+ console.log('delete success');
+ }).catch((err) => {
+ console.log('delete fail' + JSON.stringify(err));
+ });
+ }) .catch((err) => {
+ console.log(' put fail' + err);
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+
+```
+
+### on('dataChange')
+
+on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void
+
+Subscribes to data change notifications of the specified type.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. |
+| type |[SubscribeType](#subscribetype) | Yes |Type of data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
+ console.log("dataChange callback call data: " + JSON.stringify(data));
+});
+```
+
+
+### on('syncComplete')
+
+on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void
+
+Subscribes to data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('syncComplete', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+
+### off('dataChange')8+
+
+off(event:'dataChange', listener?: Callback<ChangeNotification>): void
+
+Unsubscribes from data change notifications.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+kvStore.off('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+
+### off('syncComplete')9+
+
+off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void
+
+Unsubscribes from data change events. This API uses a synchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const func = function (data) {
+ console.log('syncComplete ' + data)
+ };
+ kvStore.on('syncComplete', func);
+ kvStore.off('syncComplete', func);
+}catch(e) {
+ console.log('syncComplete e ' + e);
+}
+```
+
+
+### putBatch8+
+
+putBatch(entries: Entry[], callback: AsyncCallback<void>): void
+
+Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
+| callback |Asyncallback<void> |Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_string_key', function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+}catch(e) {
+ console.log('PutBatch e ' + JSON.stringify(e));
+}
+```
+
+
+### putBatch8+
+
+putBatch(entries: Entry[]): Promise<void>
+
+Inserts KV pairs in batches to this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_string_key').then((entries) => {
+ console.log('getEntries success');
+ console.log('PutBatch ' + JSON.stringify(entries));
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + JSON.stringify(e));
+}
+```
+
+### putBatch9+
+
+putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void
+
+Writes data to this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. |
+| callback |Asyncallback<void> |Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let v8Arr = [];
+ let arr = new Uint8Array([4,5,6,7]);
+ let vb1 = {key : "name_1", value : 32}
+ let vb2 = {key : "name_2", value : arr};
+ let vb3 = {key : "name_3", value : "lisi"};
+
+ v8Arr.push(vb1);
+ v8Arr.push(vb2);
+ v8Arr.push(vb3);
+ kvStore.putBatch(v8Arr, async function (err,data) {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('putBatch e ' + JSON.stringify(e));
+}
+```
+
+### putBatch9+
+
+putBatch(value: Array<ValuesBucket>): Promise<void>
+
+Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let v8Arr = [];
+ let arr = new Uint8Array([4,5,6,7]);
+ let vb1 = {key : "name_1", value : 32}
+ let vb2 = {key : "name_2", value : arr};
+ let vb3 = {key : "name_3", value : "lisi"};
+
+ v8Arr.push(vb1);
+ v8Arr.push(vb2);
+ v8Arr.push(vb3);
+ kvStore.putBatch(v8Arr).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + JSON.stringify(e));
+}
+
+```
+
+### deleteBatch8+
+
+deleteBatch(keys: string[], callback: AsyncCallback<void>): void
+
+Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keys |string[] | Yes |KV pairs to delete in batches. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ let keys = [];
+ for (var i = 0; i < 5; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ keys.push(key + i);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.deleteBatch(keys, async function (err,data) {
+ console.log('deleteBatch success');
+ });
+ });
+}catch(e) {
+ console.log('DeleteBatch e ' + e);
+}
+```
+
+
+### deleteBatch8+ ###
+
+deleteBatch(keys: string[]): Promise<void>
+
+Deletes KV pairs in batches from this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keys |string[] | Yes |KV pairs to delete in batches. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ let keys = [];
+ for (var i = 0; i < 5; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ keys.push(key + i);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.deleteBatch(keys).then((err) => {
+ console.log('deleteBatch success');
+ }).catch((err) => {
+ console.log('deleteBatch fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('DeleteBatch e ' + e);
+}
+```
+
+
+### startTransaction8+ ###
+
+startTransaction(callback: AsyncCallback<void>): void
+
+Starts the transaction in this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+function putBatchString(len, prefix) {
+ let entries = [];
+ for (var i = 0; i < len; i++) {
+ var entry = {
+ key : prefix + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ return entries;
+}
+try {
+ var count = 0;
+ kvStore.on('dataChange', 0, function (data) {
+ console.log('startTransaction 0' + data)
+ count++;
+ });
+ kvStore.startTransaction(async function (err,data) {
+ console.log('startTransaction success');
+ let entries = putBatchString(10, 'batch_test_string_key');
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ });
+ });
+}catch(e) {
+ console.log('startTransaction e ' + e);
+}
+```
+
+
+### startTransaction8+ ###
+
+startTransaction(): Promise<void>
+
+Starts the transaction in this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var count = 0;
+ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
+ console.log('startTransaction ' + JSON.stringify(data));
+ count++;
+ });
+ kvStore.startTransaction().then(async (err) => {
+ console.log('startTransaction success');
+ }).catch((err) => {
+ console.log('startTransaction fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('startTransaction e ' + e);
+}
+```
+
+
+### commit8+ ###
+
+commit(callback: AsyncCallback<void>): void
+
+Commits the transaction in this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.commit(function (err,data) {
+ if (err == undefined) {
+ console.log('commit success');
+ } else {
+ console.log('commit fail');
+ }
+ });
+}catch(e) {
+ console.log('Commit e ' + e);
+}
+```
+
+
+### commit8+ ###
+
+commit(): Promise<void>
+
+Commits the transaction in this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.commit().then(async (err) => {
+ console.log('commit success');
+ }).catch((err) => {
+ console.log('commit fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('Commit e ' + e);
+}
+```
+
+
+### rollback8+ ###
+
+rollback(callback: AsyncCallback<void>): void
+
+Rolls back the transaction in this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.rollback(function (err,data) {
+ if (err == undefined) {
+ console.log('commit success');
+ } else {
+ console.log('commit fail');
+ }
+ });
+}catch(e) {
+ console.log('Rollback e ' + e);
+}
+```
+
+
+### rollback8+ ###
+
+rollback(): Promise<void>
+
+Rolls back the transaction in this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.rollback().then(async (err) => {
+ console.log('rollback success');
+ }).catch((err) => {
+ console.log('rollback fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('Rollback e ' + e);
+}
+```
+
+
+### enableSync8+ ###
+
+enableSync(enabled: boolean, callback: AsyncCallback<void>): void
+
+Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.enableSync(true, function (err,data) {
+ if (err == undefined) {
+ console.log('enableSync success');
+ } else {
+ console.log('enableSync fail');
+ }
+ });
+}catch(e) {
+ console.log('EnableSync e ' + e);
+}
+```
+
+
+### enableSync8+ ###
+
+enableSync(enabled: boolean): Promise<void>
+
+Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.enableSync(true).then((err) => {
+ console.log('enableSync success');
+ }).catch((err) => {
+ console.log('enableSync fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('EnableSync e ' + e);
+}
+```
+
+
+### setSyncRange8+ ###
+
+setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void
+
+Sets the data synchronization range. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| localLabels |string[] | Yes |Synchronization labels set for the local device. |
+| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const localLabels = ['A', 'B'];
+ const remoteSupportLabels = ['C', 'D'];
+ kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) {
+ console.log('SetSyncRange put success');
+ });
+}catch(e) {
+ console.log('SetSyncRange e ' + e);
+}
+```
+
+
+### setSyncRange8+ ###
+
+setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void>
+
+Sets the data synchronization range. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| localLabels |string[] | Yes |Synchronization labels set for the local device. |
+| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+| Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const localLabels = ['A', 'B'];
+ const remoteSupportLabels = ['C', 'D'];
+ kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => {
+ console.log('setSyncRange success');
+ }).catch((err) => {
+ console.log('delete fail ' + err);
+ });
+}catch(e) {
+ console.log('SetSyncRange e ' + e);
+}
+```
+
+
+## SubscribeType
+
+Enumerates the subscription types.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value | Description |
+| ----- | ------ | ----------------------- |
+| SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. |
+| SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. |
+| SUBSCRIBE_TYPE_ALL |2 |Local and remote data changes. |
+
+## ChangeNotification
+
+Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Type |Readable |Writable | Description |
+| ----- | ------- | -----| ------|------------------------ |
+| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. |
+| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. |
+| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. |
+| deviceId | string | Yes | Yes|UUID of the device. |
+
+## Entry
+
+Defines the KV pairs stored in the KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Type |Readable |Writable | Description |
+| ----- | ------- | -----| ------|------------------------ |
+| key | string | Yes | Yes|Key of the KV pair stored in the KV store. |
+| value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. |
+
+
+## Value
+
+Defines the **value** object in a KV store.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Type |Readable |Writable | Description |
+| ----- | ------- | -----| ------|------------------------ |
+| type | [ValueType](#value) | Yes | Yes|Type of the value. |
+| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. |
+
+## ValueType
+
+Enumerates the data types.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value | Description |
+| ----- | ------ | ----------------------- |
+| STRING |0 |String. |
+| INTEGER |1 |Integer. |
+| FLOAT |2 |Float (single-precision floating point). |
+| BYTE_ARRAY |3 |Byte array. |
+| BOOLEAN |4 |Boolean. |
+| DOUBLE |5 |Double (double-precision floating point). |
+
+## SingleKVStore
+
+Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore).
+
+Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices.
+
+Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance.
+
+### get
+
+get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void
+
+Obtains the value of the specified key. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
+ if (err != undefined) {
+ console.log("put err: " + JSON.stringify(err));
+ return;
+ }
+ console.log("put success");
+ kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
+ console.log("get success data: " + data);
+ });
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+
+### get
+
+get(key: string): Promise<Uint8Array | string | boolean | number>
+
+Obtains the value of the specified key. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => {
+ console.log("put success: " + JSON.stringify(data));
+ kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log("get success data: " + data);
+ }).catch((err) => {
+ console.log("get err: " + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log("put err: " + JSON.stringify(err));
+ });
+}catch (e) {
+ console.log("An unexpected error occurred. Error:" + e);
+}
+```
+
+### getEntries8+ ###
+
+getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void
+
+Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_number_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.INTEGER,
+ value : 222
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_number_key', function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(keyPrefix: string): Promise<Entry[]>
+
+Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + entries);
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.getEntries('batch_test_string_key').then((entries) => {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
+ console.log('entries[0].value.value: ' + entries[0].value.value);
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query, callback: AsyncCallback<Entry[]>): void
+
+Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |Key prefix to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getEntries(query, function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query): Promise<Entry[]>
+
+Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getEntries(query).then((entries) => {
+ console.log('getEntries success');
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('GetEntries putBatch fail ' + JSON.stringify(err))
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains the result set with the specified prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match.|
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('GetResultSet putBatch success');
+ kvStore.getResultSet('batch_test_string_key', async function (err, result) {
+ console.log('GetResultSet getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('GetResultSet closeResultSet success');
+ })
+ });
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(keyPrefix: string): Promise<KvStoreResultSet>
+
+Obtains the result set with the specified prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| keyPrefix |string | Yes |Key prefix to match.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the result set obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('PutBatch putBatch fail ' + JSON.stringify(err));
+ });
+ kvStore.getResultSet('batch_test_string_key').then((result) => {
+ console.log('GetResult getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('GetResult closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResult e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |Query | Yes |**Query** object to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet(query, async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ });
+ });
+} catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet(query).then((result) => {
+ console.log(' getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+### getResultSet9+ ###
+
+getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let resultSet;
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.prefixKey("batch_test_string_key");
+ kvStore.getResultSet(predicates, async function (err, result) {
+ console.log(' GetResultSet success');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log(' closeResultSet success');
+ })
+ });
+}catch(e) {
+ console.log('An unexpected error occurred. Error:' + e);
+}
+```
+### getResultSet9+ ###
+
+getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+let kvStore;
+try {
+ let resultSet;
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ predicates.prefixKey("batch_test_string_key");
+ kvStore.getResultSet(predicates) .then((result) => {
+ console.log(' GetResultSet success');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log(' closeResultSet success');
+ })
+ });
+}catch(e) {
+ console.log('An unexpected error occurred. Error:' + e);
+}
+```
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void
+
+Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ if (err == undefined) {
+ console.log('closeResultSet success');
+ } else {
+ console.log('closeResultSet fail');
+ }
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet): Promise<void>
+
+Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet).then(() => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query, callback: AsyncCallback<number>): void
+
+Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize(query, async function (err, resultSize) {
+ console.log('getResultSet succeed.');
+ });
+ });
+} catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query): Promise<number>
+
+Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<number> |Promise used to return the number of results obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize(query).then((resultSize) => {
+ console.log('getResultSet succeed.');
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void
+
+Deletes data of a device. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('put success');
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid, async function (err,data) {
+ if (err == undefined) {
+ console.log('removeDeviceData success');
+ } else {
+ console.log('removeDeviceData fail');
+ kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('RemoveDeviceData get success');
+ });
+ }
+ });
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string): Promise<void>
+
+Deletes data of a device. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => {
+ console.log('removeDeviceData put success');
+ }).catch((err) => {
+ console.log('put fail ' + JSON.stringify(err));
+ });
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid).then((err) => {
+ console.log('removeDeviceData success');
+ }).catch((err) => {
+ console.log('removeDeviceData fail ' + JSON.stringify(err));
+ });
+ kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log('get success data:' + data);
+ }).catch((err) => {
+ console.log('RemoveDeviceData get fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### on('syncComplete')8+ ###
+
+on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void
+
+Subscribes to the data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
+const VALUE_TEST_FLOAT_ELEMENT = 321.12;
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('syncComplete ' + data)
+ });
+ kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
+ console.log('syncComplete put success');
+ }).catch((error) => {
+ console.log('syncComplete put fail ' + error);
+ });
+}catch(e) {
+ console.log('syncComplete put e ' + e);
+}
+```
+
+
+### off('syncComplete')8+ ###
+
+off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void
+
+Unsubscribes from the data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. |
+| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const func = function (data) {
+ console.log('syncComplete ' + data)
+ };
+ kvStore.on('syncComplete', func);
+ kvStore.off('syncComplete', func);
+}catch(e) {
+ console.log('syncComplete e ' + e);
+}
+```
+
+### on('dataChange')9+ ###
+
+on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void
+
+Subscribes to data changes of the specified type. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. |
+| type |[SubscribeType](#subscribetype) | Yes |Subscription type. |
+| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
+ console.log("dataChange callback call data: " + JSON.stringify(data));
+});
+
+```
+
+### off('dataChange')9+ ###
+
+off(event:'dataChange', listener?: Callback<ChangeNotification>): void
+
+Unsubscribes from the data change events. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+kvStore.off('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+### sync7+
+
+
+sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. |
+| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000);
+```
+
+### sync9+
+sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. |
+| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
+const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) {
+ console.log('Sync put success');
+ const devices = ['deviceList'];
+ const mode = distributedData.SyncMode.PULL_ONLY;
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.sync(devices, query, mode , 1000);
+ });
+}catch(e) {
+ console.log('Sync e' + e);
+}
+```
+
+### setSyncParam8+ ###
+
+setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void
+
+Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const defaultAllowedDelayMs = 500;
+ kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) {
+ console.log('SetSyncParam put success');
+ });
+}catch(e) {
+ console.log('testSingleKvStoreSetSyncParam e ' + e);
+}
+```
+
+
+### setSyncParam8+ ###
+
+setSyncParam(defaultAllowedDelayMs: number): Promise<void>
+
+Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. |
+
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ const defaultAllowedDelayMs = 500;
+ kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => {
+ console.log('SetSyncParam put success');
+ }).catch((err) => {
+ console.log('SetSyncParam put fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('SetSyncParam e ' + e);
+}
+```
+
+
+### getSecurityLevel8+ ###
+
+getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void
+
+Obtains the security level of this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback invoked to return the security level obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.getSecurityLevel(function (err,data) {
+ console.log('getSecurityLevel success');
+ });
+}catch(e) {
+ console.log('GetSecurityLevel e ' + e);
+}
+```
+
+
+### getSecurityLevel8+ ###
+
+getSecurityLevel(): Promise<SecurityLevel>
+
+Obtains the security level of this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ kvStore.getSecurityLevel().then((data) => {
+ console.log(' getSecurityLevel success');
+ }).catch((err) => {
+ console.log('getSecurityLevel fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetSecurityLevel e ' + e);
+}
+```
+
+
+## DeviceKVStore8+ ##
+
+Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore).
+
+Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified.
+
+For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted.
+
+Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object.
+
+### get8+ ###
+
+get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void
+
+Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| key |string | Yes |Key to match. |
+| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
+try{
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('put success');
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) {
+ console.log('get success');
+ });
+ })
+}catch(e) {
+ console.log('get e' + e);
+}
+```
+
+
+### get8+ ###
+
+get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array>
+
+Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| key |string | Yes |Key to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => {
+ console.log(' put success');
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log('get success');
+ }).catch((err) => {
+ console.log('get fail ' + JSON.stringify(err));
+ });
+ }).catch((error) => {
+ console.log('put error' + error);
+ });
+} catch (e) {
+ console.log('Get e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void
+
+Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + entries);
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]>
+
+Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + entries);
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ console.log('entries[0].value: ' + JSON.stringify(entries[0].value));
+ console.log('entries[0].value.value: ' + entries[0].value.value);
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('PutBatch e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query, callback: AsyncCallback<Entry[]>): void
+
+Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getEntries(query, function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ });
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(query: Query): Promise<Entry[]>
+
+Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getEntries(query).then((entries) => {
+ console.log('getEntries success');
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('GetEntries putBatch fail ' + JSON.stringify(err))
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void
+
+Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries, async function (err,data) {
+ console.log('putBatch success');
+ var query = new distributedData.Query();
+ query.deviceId('localDeviceId');
+ query.prefixKey("batch_test");
+ kvStore.getEntries('localDeviceId', query, function (err,entries) {
+ console.log('getEntries success');
+ console.log('entries.length: ' + entries.length);
+ console.log('entries[0]: ' + JSON.stringify(entries[0]));
+ })
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getEntries8+ ###
+
+getEntries(deviceId: string, query: Query): Promise<Entry[]>
+
+Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ var arr = new Uint8Array([21,31]);
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_bool_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.BYTE_ARRAY,
+ value : arr
+ }
+ }
+ entries.push(entry);
+ }
+ console.log('entries: ' + JSON.stringify(entries));
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ var query = new distributedData.Query();
+ query.deviceId('localDeviceId');
+ query.prefixKey("batch_test");
+ kvStore.getEntries('localDeviceId', query).then((entries) => {
+ console.log('getEntries success');
+ }).catch((err) => {
+ console.log('getEntries fail ' + JSON.stringify(err));
+ });
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ console.log('GetEntries success');
+}catch(e) {
+ console.log('GetEntries e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('closeResultSet success');
+ })
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| keyPrefix |string | Yes |Key prefix to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getResultSet(query, async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('closeResultSet success');
+ })
+ });
+ });
+} catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(query: Query): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + err);
+ });
+ const query = new distributedData.Query();
+ query.deviceId('localDeviceId');
+ query.prefixKey("batch_test");
+ console.log("GetResultSet " + query.getSqlLike());
+ kvStore.getResultSet(query).then((result) => {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet('localDeviceId', query, async function (err, result) {
+ console.log('getResultSet succeed.');
+ resultSet = result;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ console.log('closeResultSet success');
+ })
+ });
+ });
+} catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### getResultSet8+ ###
+
+getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet>
+
+Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let resultSet;
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('GetResultSet putBatch success');
+ }).catch((err) => {
+ console.log('PutBatch putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSet('localDeviceId', query).then((result) => {
+ console.log('GetResultSet getResultSet succeed.');
+ resultSet = result;
+ }).catch((err) => {
+ console.log('GetResultSet getResultSet failed: ' + JSON.stringify(err));
+ });
+ query.deviceId('localDeviceId');
+ console.log("GetResultSet " + query.getSqlLike());
+ kvStore.closeResultSet(resultSet).then((err) => {
+ console.log('GetResultSet closeResultSet success');
+ }).catch((err) => {
+ console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err));
+ });
+
+}catch(e) {
+ console.log('GetResultSet e ' + e);
+}
+```
+
+
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void
+
+Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ console.log('CloseResultSet success');
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet, function (err, data) {
+ if (err == undefined) {
+ console.log('closeResultSet success');
+ } else {
+ console.log('closeResultSet fail');
+ }
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### closeResultSet8+ ###
+
+closeResultSet(resultSet: KvStoreResultSet): Promise<void>
+
+Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ console.log('CloseResultSet success');
+ let resultSet = null;
+ kvStore.closeResultSet(resultSet).then(() => {
+ console.log('closeResultSet success');
+ }).catch((err) => {
+ console.log('closeResultSet fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('CloseResultSet e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query, callback: AsyncCallback<number>): void
+
+Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getResultSize(query, async function (err, resultSize) {
+ console.log('getResultSet succeed.');
+ });
+ });
+} catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(query: Query): Promise<number>
+
+Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<number> |Promise used to return the number of results obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.getResultSize(query).then((resultSize) => {
+ console.log('getResultSet succeed.');
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void;
+
+Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. |
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries, async function (err, data) {
+ console.log('putBatch success');
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) {
+ console.log('getResultSet succeed.');
+ });
+ });
+} catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### getResultSize8+ ###
+
+getResultSize(deviceId: string, query: Query): Promise<number>
+
+Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| query |[Query](#query8) | Yes |**Query** object to match. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<number> |Promise used to return the number of results obtained.|
+
+**Example**
+
+```js
+let kvStore;
+try {
+ let entries = [];
+ for (var i = 0; i < 10; i++) {
+ var key = 'batch_test_string_key';
+ var entry = {
+ key : key + i,
+ value : {
+ type : distributedData.ValueType.STRING,
+ value : 'batch_test_string_value'
+ }
+ }
+ entries.push(entry);
+ }
+ kvStore.putBatch(entries).then(async (err) => {
+ console.log('putBatch success');
+ }).catch((err) => {
+ console.log('putBatch fail ' + JSON.stringify(err));
+ });
+ var query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ kvStore.getResultSize('localDeviceId', query).then((resultSize) => {
+ console.log('getResultSet succeed.');
+ }).catch((err) => {
+ console.log('getResultSet failed: ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('GetResultSize e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void
+
+Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+| callback |AsyncCallback<void> | Yes |Callback used to return the result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('RemoveDeviceData put success');
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid, async function (err,data) {
+ if (err == undefined) {
+ console.log('removeDeviceData success');
+ } else {
+ console.log('removeDeviceData fail');
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) {
+ console.log('RemoveDeviceData get success');
+ });
+ }
+ });
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### removeDeviceData8+ ###
+
+removeDeviceData(deviceId: string): Promise<void>
+
+Deletes data of the specified device from this KV store. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceId |string | Yes |ID of the target device. |
+
+**Return value**
+
+| Type | Description |
+| ------ | ------- |
+|Promise<void> |Promise that returns no value.|
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_STRING_ELEMENT = 'key_test_string';
+const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
+try {
+ kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => {
+ console.log('RemoveDeviceData put success');
+ }).catch((err) => {
+ console.log('RemoveDeviceData put fail ' + JSON.stringify(err));
+ });
+ const deviceid = 'no_exist_device_id';
+ kvStore.removeDeviceData(deviceid).then((err) => {
+ console.log('removeDeviceData success');
+ }).catch((err) => {
+ console.log('removeDeviceData fail ' + JSON.stringify(err));
+ });
+ kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => {
+ console.log('RemoveDeviceData get success data:' + data);
+ }).catch((err) => {
+ console.log('RemoveDeviceData get fail ' + JSON.stringify(err));
+ });
+}catch(e) {
+ console.log('RemoveDeviceData e ' + e);
+}
+```
+
+
+### sync8+ ###
+
+sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |IDs of the devices to be synchronized.|
+| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. |
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
+const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) {
+ console.log('Sync put success');
+ const devices = ['deviceList'];
+ const mode = distributedData.SyncMode.PULL_ONLY;
+ kvStore.sync(devices, mode);
+ });
+}catch(e) {
+ console.log('Sync e' + e);
+}
+```
+
+### sync9+ ###
+
+sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
+
+Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md).
+
+**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| deviceIds |string[] | Yes |IDs of the devices to be synchronized.|
+| query |[Query](#query8) | Yes | **Query** object to match.|
+| delayMs |number | No |Allowed synchronization delay time, in ms. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
+const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('Sync dataChange');
+ });
+ kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) {
+ console.log('Sync put success');
+ const devices = ['deviceList'];
+ const mode = distributedData.SyncMode.PULL_ONLY;
+ const query = new distributedData.Query();
+ query.prefixKey("batch_test");
+ query.deviceId('localDeviceId');
+ kvStore.sync(devices, query, 1000);
+ });
+}catch(e) {
+ console.log('Sync e' + e);
+}
+```
+
+### on('syncComplete')8+ ###
+
+on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void
+
+Subscribes to the data synchronization complete events.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates the data synchronization complete event.|
+| syncCallback |Callback | Yes |Callback used to return the synchronization result. |
+
+**Example**
+
+```js
+let kvStore;
+const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
+const VALUE_TEST_FLOAT_ELEMENT = 321.12;
+try {
+ kvStore.on('syncComplete', function (data) {
+ console.log('syncComplete ' + data)
+ });
+ kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
+ console.log('syncComplete put success');
+ }).catch((error) => {
+ console.log('syncComplete put fail ' + error);
+ });
+}catch(e) {
+ console.log('syncComplete put e ' + e);
+}
+```
+
+
+### off('syncComplete')8+ ###
+
+off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void
+
+Unsubscribes from the synchronization complete events. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.|
+| syncCallback |Callback9+ ###
+
+on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void
+
+Subscribes to data changes of the specified type. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. |
+| type |[SubscribeType](#subscribetype) | Yes |Subscription type. |
+| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
+ console.log("dataChange callback call data: " + JSON.stringify(data));
+});
+```
+
+
+### off('dataChange')9+ ###
+
+off(event:'dataChange', listener?: Callback<ChangeNotification>): void
+
+Unsubscribes from the data change events. This API returns the result synchronously.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+**Parameters**
+
+| Name | Type| Mandatory | Description |
+| ----- | ------ | ---- | ----------------------- |
+| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. |
+| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.|
+
+**Example**
+
+```js
+let kvStore;
+kvStore.on('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+kvStore.off('dataChange', function (data) {
+ console.log("callback call data: " + data);
+});
+```
+
+## SyncMode
+
+Enumerates the synchronization modes.
+
+**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
+
+| Name | Value | Description |
+| ----- | ------ | ----------------------- |
+| PULL_ONLY |0 |Pull data from the peer end to the local end only.|
+| PUSH_ONLY |1 |Push data from the local end to the peer end only.|
+| PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.|
+
diff --git a/en/application-dev/reference/apis/js-apis-environment.md b/en/application-dev/reference/apis/js-apis-environment.md
index 942e514367c923db4d7aa270218e39ae82f65aa0..d023cdc8403d028ff250d3ea7afa82858d6ad5b8 100644
--- a/en/application-dev/reference/apis/js-apis-environment.md
+++ b/en/application-dev/reference/apis/js-apis-environment.md
@@ -1,12 +1,12 @@
# Environment
+This module provides JS APIs for obtaining the root directories of the storage and public 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.
-This module provides JS APIs for obtaining the root directories of the storage and public files.
-
## Modules to Import
```js
diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md
index 6e970785345a27be2c2c4d1051f87c13c4d8533f..4d3791fd26788b92c136c32df7f298787f887f3d 100644
--- a/en/application-dev/reference/apis/js-apis-fileio.md
+++ b/en/application-dev/reference/apis/js-apis-fileio.md
@@ -17,15 +17,31 @@ import fileio from '@ohos.fileio';
Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows:
+Stage Model
+
+ ```js
+import Ability from '@ohos.application.Ability';
+class MainAbility extends Ability {
+ onWindowStageCreate(windowStage) {
+ let context = this.context;
+ let path = context.filesDir;
+ }
+}
+ ```
+
+ For details about how to obtain the stage model context, see [Stage Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-ability-context.md#abilitycontext).
+
+FA Model
+
```js
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
- let path = '';
context.getFilesDir().then((data) => {
- path = data;
+ let path = data;
})
```
-
+
+ For details about how to obtain the context of the FA model, see [FA Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-Context.md#context).
## fileio.stat
@@ -654,7 +670,7 @@ Reads data from a file. This API uses a promise to return the result.
let fd = fileio.openSync(path, 0o2);
let buf = new ArrayBuffer(4096);
fileio.read(fd, buf).then(function(readOut){
- console.info("Read file data");
+ console.info("Read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}).catch(function(err){
console.info("Failed to read file data. Error:"+ err);
@@ -690,7 +706,7 @@ Reads data from a file. This API uses an asynchronous callback to return the res
let buf = new ArrayBuffer(4096);
fileio.read(fd, buf, function (err, readOut) {
if (readOut) {
- console.info("Read file data");
+ console.info("Read file data successfully");
console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer)));
}
});
@@ -1263,7 +1279,7 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal
| -------- | ------------------------- | ---- | ---------------- |
| fd | number | Yes | File descriptor of the file to truncate. |
| len | number | Yes | File length, in bytes, after truncation.|
- | callback | AsyncCallback<void> | Yes | Callback that returns no value. |
+ | callback | AsyncCallback<void> | Yes | Callback that returns no value.|
**Example**
@@ -1347,7 +1363,7 @@ Truncates a file based on the file path. This API uses an asynchronous callback
| -------- | ------------------------- | ---- | -------------------------------- |
| path | string | Yes | Application sandbox path of the file to truncate.|
| len | number | Yes | File length, in bytes, after truncation.|
-| callback | AsyncCallback<void> | Yes | Callback that returns no value. |
+| callback | AsyncCallback<void> | Yes | Callback that returns no value.|
**Example**
@@ -1411,7 +1427,7 @@ Reads the text content of a file. This API uses a promise to return the result.
```js
fileio.readText(path).then(function(str) {
- console.info("Read text:"+ str);
+ console.info("Read text successfully:"+ str);
}).catch(function(err){
console.info("Failed to read the text. Error:"+ err);
});
@@ -2159,7 +2175,7 @@ Opens a file stream based on the file path. This API uses a promise to return th
| Type | Description |
| --------------------------------- | --------- |
- | Promise<[Stream](#stream7)> | Promise used to return the result.|
+ | Promise<[Stream](#stream)> | Promise used to return the result.|
**Example**
@@ -2186,7 +2202,7 @@ Opens a file stream based on the file path. This API uses an asynchronous callba
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Application sandbox path 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](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. |
+| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. |
**Example**
@@ -2216,7 +2232,7 @@ Synchronously opens a stream based on the file path.
| Type | Description |
| ------------------ | --------- |
- | [Stream](#stream7) | Stream opened.|
+ | [Stream](#stream) | Stream opened.|
**Example**
@@ -2244,7 +2260,7 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret
| Type | Description |
| --------------------------------- | --------- |
- | Promise<[Stream](#stream7)> | Promise used to return the result.|
+ | Promise<[Stream](#stream)> | Promise used to return the result.|
**Example**
@@ -2272,7 +2288,7 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| fd | number | Yes | File descriptor of the target 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](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. |
+ | callback | AsyncCallback <[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. |
**Example**
@@ -2303,7 +2319,7 @@ Synchronously opens a stream based on the file descriptor.
| Type | Description |
| ------------------ | --------- |
- | [Stream](#stream7) | Stream opened.|
+ | [Stream](#stream) | Stream opened.|
**Example**
@@ -2720,7 +2736,7 @@ Stops the **watcher** instance. This API uses a promise to return the result.
```js
let filename = path +"/test.txt";
- let watcher = await fileio.createWatcher(filename, 1, function(number){
+ let watcher = fileio.createWatcher(filename, 1, function(number){
console.info("Monitoring times: "+number);
});
watcher.stop().then(function(){
@@ -2747,7 +2763,7 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return
```js
let filename = path +"/test.txt";
- let watcher = await fileio.createWatcher(filename, 1, function(number){
+ let watcher = fileio.createWatcher(filename, 1, function(number){
console.info("Monitoring times: "+number);
});
watcher.stop(function(){
@@ -3124,7 +3140,6 @@ Reads the next directory entry. This API uses a promise to return the result.
**Example**
```js
- let dir = fileio.opendirSync(path);
dir.read().then(function (dirent){
console.log("Read the next directory entry:"+JSON.stringify(dirent));
}).catch(function(err){
@@ -3150,7 +3165,6 @@ Reads the next directory entry. This API uses an asynchronous callback to return
**Example**
```js
- let dir = fileio.opendirSync(path);
dir.read(function (err, dirent) {
if (dirent) {
// Do something
@@ -3177,7 +3191,6 @@ Synchronously reads the next directory entry.
**Example**
```js
- let dir = fileio.opendirSync(path);
let dirent = dir.readSync();
```
@@ -3193,7 +3206,6 @@ Closes a directory. This API uses a promise to return the result. After a direct
**Example**
```js
- let dir = fileio.opendirSync(path);
dir.close().then(function(err){
console.info("close dir successfully");
});
@@ -3211,7 +3223,6 @@ Closes a directory. This API uses an asynchronous callback to return the result.
**Example**
```js
- let dir = fileio.opendirSync(path);
dir.close(function(err){
console.info("close dir successfully");
});
@@ -3229,7 +3240,6 @@ Closes a directory. After a directory is closed, the file descriptor in Dir will
**Example**
```js
- let dir = fileio.opendirSync(path);
dir.closeSync();
```
diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md
index 24339fc434b3afe97cf0f5ebbbfd1862f86c6e6e..0abc724302fcf89b86421b90c0bb507f1894b312 100644
--- a/en/application-dev/reference/apis/js-apis-i18n.md
+++ b/en/application-dev/reference/apis/js-apis-i18n.md
@@ -673,6 +673,32 @@ Formats a phone number.
phonenumberfmt.format("15812312312");
```
+### getLocationName8+
+
+static getLocationName(number: string, locale: string): string
+
+Obtains the home location of a phone number.
+
+**System capability**: SystemCapability.Global.I18n
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ------ | ------ | ---- | ---------- |
+| number | string | Yes | Phone number.|
+| locale | string | Yes | Locale ID.|
+
+**Return value**
+| Type | Description |
+| ------ | ---------- |
+| string | Home location of the phone number.|
+
+**Example**
+ ```
+ var location = i18n.PhoneNumberFormat.getLocationName('15812312345', 'zh-CN');
+ ```
+
+
+
## PhoneNumberFormatOptions8+
diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md
index 85ff0550112bbfc81e22925c3a69ca7ac813cfab..13701cecf67e947c876789d0f1f4acde7f62a601 100644
--- a/en/application-dev/reference/apis/js-apis-image.md
+++ b/en/application-dev/reference/apis/js-apis-image.md
@@ -1,5 +1,7 @@
# Image Processing
+The **Image** module provides APIs for image processing. You can use the APIs to create a **PixelMap** object with specified properties or read image pixel data (even in an area).
+
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -11,11 +13,12 @@ import image from '@ohos.multimedia.image';
```
## image.createPixelMap8+
+
createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\
Creates a **PixelMap** object. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -34,7 +37,7 @@ Creates a **PixelMap** object. This API uses a promise to return the result.
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts)
.then((pixelmap) => {
@@ -47,7 +50,7 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: As
Creates a **PixelMap** object. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -61,10 +64,15 @@ Creates a **PixelMap** object. This API uses an asynchronous callback to return
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
-image.createPixelMap(color, opts, (pixelmap) => {
- })
+image.createPixelMap(color, opts, (error, pixelmap) => {
+ if(error) {
+ console.log('Failed to create pixelmap.');
+ } else {
+ console.log('Succeeded in creating pixelmap.');
+ }
+})
```
## PixelMap7+
@@ -73,11 +81,11 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i
### Attributes
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Type | Readable| Writable| Description |
-| ----------------------- | ------- | ---- | ---- | -------------------------- |
-| isEditable7+ | boolean | Yes | No | Whether the image pixel map is editable.|
+| Name | Type | Readable| Writable| Description |
+| ---------- | ------- | ---- | ---- | -------------------------- |
+| isEditable | boolean | Yes | No | Whether the image pixel map is editable.|
### readPixelsToBuffer7+
@@ -85,24 +93,24 @@ readPixelsToBuffer(dst: ArrayBuffer): Promise\
Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ----------- | ---- | ------------------------------------------------------------ |
-| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written.|
+| Name| Type | Mandatory| Description |
+| ------ | ----------- | ---- | ----------------------------------------------------------------------------------------------------- |
+| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written. The buffer size is obtained by calling **getPixelBytesNumber**.|
**Return value**
| Type | Description |
-| :------------- | :---------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| -------------- | ----------------------------------------------- |
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
-const readBuffer = new ArrayBuffer(400);
+const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then(() => {
console.log('Succeeded in reading image pixel data.'); // Called if the condition is met.
}).catch(error => {
@@ -116,19 +124,19 @@ readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\): void
Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | -------------------- | ---- | ------------------------------------------------------------ |
-| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written.|
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned. |
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------------------------------------------------------------------------------- |
+| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written. The buffer size is obtained by calling **getPixelBytesNumber**.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned. |
**Example**
```js
-const readBuffer = new ArrayBuffer(400);
+const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer, (err, res) => {
if(err) {
console.log('Failed to read image pixel data.'); // Called if no condition is met.
@@ -144,7 +152,7 @@ readPixels(area: PositionArea): Promise\
Reads image pixel map data in an area. This API uses a promise to return the data read.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -156,7 +164,7 @@ Reads image pixel map data in an area. This API uses a promise to return the dat
| Type | Description |
| :------------- | :-------------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
@@ -175,20 +183,20 @@ readPixels(area: PositionArea, callback: AsyncCallback\): void
Reads image pixel map data in an area. This API uses an asynchronous callback to return the data read.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------ | ---- | ------------------------------ |
| area | [PositionArea](#positionarea7) | Yes | Area from which the image pixel map data will be read. |
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err, pixelmap) => {
if(pixelmap == undefined){
@@ -211,7 +219,7 @@ writePixels(area: PositionArea): Promise\
Writes image pixel map data to an area. This API uses a promise to return the operation result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -223,13 +231,13 @@ Writes image pixel map data to an area. This API uses a promise to return the op
| Type | Description |
| :------------- | :-------------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts)
.then( pixelmap => {
@@ -265,21 +273,21 @@ writePixels(area: PositionArea, callback: AsyncCallback\): void
Writes image pixel map data to an area. This API uses an asynchronous callback to return the operation result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------------ | ---- | ------------------------------ |
| area | [PositionArea](#positionarea7) | Yes | Area to which the image pixel map data will be written. |
-| callback: | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const area = new ArrayBuffer(400);
pixelmap.writePixels(area, (error) => {
- if (error!=undefined) {
+ if (error != undefined) {
console.info('Failed to write pixelmap into the specified area.');
} else {
const readArea = {
@@ -298,7 +306,7 @@ writeBufferToPixels(src: ArrayBuffer): Promise\
Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** object. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -310,14 +318,14 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj
| Type | Description |
| -------------- | ----------------------------------------------- |
-| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.|
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color).then(() => {
console.log("Succeeded in writing data from a buffer to a PixelMap.");
}).catch((err) => {
@@ -331,21 +339,21 @@ writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\): void
Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** object. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------ |
| src | ArrayBuffer | Yes | Buffer from which the image data will be read. |
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
**Example**
```js
-const color = new ArrayBuffer(96);\
+const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color, function(err) {
if (err) {
console.error("Failed to write data from a buffer to a PixelMap.");
@@ -362,7 +370,7 @@ getImageInfo(): Promise\
Obtains pixel map information of this image. This API uses a promise to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
@@ -387,7 +395,7 @@ getImageInfo(callback: AsyncCallback\): void
Obtains pixel map information of this image. This API uses an asynchronous callback to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
@@ -399,7 +407,7 @@ Obtains pixel map information of this image. This API uses an asynchronous callb
```js
pixelmap.getImageInfo((imageInfo) => {
- console.log("Succeeded in obtaining the image pixel map information..");
+ console.log("Succeeded in obtaining the image pixel map information.");
})
```
@@ -407,21 +415,21 @@ pixelmap.getImageInfo((imageInfo) => {
getBytesNumberPerRow(): number
-Obtains the number of bytes per line of the image pixel map.
+Obtains the number of bytes per row of this image pixel map.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
| Type | Description |
| ------ | -------------------- |
-| number | Number of bytes per line.|
+| number | Number of bytes per row.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err,pixelmap) => {
let rowCount = pixelmap.getBytesNumberPerRow();
@@ -432,9 +440,9 @@ image.createPixelMap(color, opts, (err,pixelmap) => {
getPixelBytesNumber(): number
-Obtains the total number of bytes of the image pixel map.
+Obtains the total number of bytes of this image pixel map.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
@@ -448,25 +456,410 @@ Obtains the total number of bytes of the image pixel map.
let pixelBytesNumber = pixelmap.getPixelBytesNumber();
```
+### getDensity9+
+
+getDensity():number
+
+Obtains the density of this image pixel map.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | --------------- |
+| number | Density of the image pixel map.|
+
+**Example**
+
+```js
+let getDensity = pixelmap.getDensity();
+```
+
+### opacity9+
+
+opacity(rate: number, callback: AsyncCallback\): void
+
+Sets an opacity rate for this image pixel map. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ------------------------------ |
+| rate | number | Yes | Opacity rate to set. The value ranges from 0 to 1. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.opacity(0.5);
+}
+```
+
+### opacity9+
+
+opacity(rate: number): Promise\
+
+Sets an opacity rate for this image pixel map. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | --------------------------- |
+| rate | number | Yes | Opacity rate to set. The value ranges from 0 to 1.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | ----------------------------------------------- |
+| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.opacity(0.5);
+}
+```
+
+### createAlphaPixelmap9+
+
+createAlphaPixelmap(): Promise\
+
+Creates a **PixelMap** object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Return value**
+
+| Type | Description |
+| -------------------------------- | --------------------------- |
+| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.|
+
+**Example**
+
+```js
+pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => {
+ if (alphaPixelMap == undefined) {
+ console.info('Failed to obtain new pixel map.');
+ } else {
+ console.info('Succeed in obtaining new pixel map.');
+ }
+})
+```
+
+### createAlphaPixelmap9+
+
+createAlphaPixelmap(callback: AsyncCallback\): void
+
+Creates a **PixelMap** object that contains only the alpha channel information. This object can be used for the shadow effect. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------ | ---- | ------------------------ |
+| callback | AsyncCallback\ | Yes | Callback used to return the **PixelMap** object.|
+
+**Example**
+
+```js
+let pixelMap = await imageSource.createPixelMap();
+if (pixelMap != undefined) {
+ pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => {
+ console.info('Failed to obtain new pixel map.');
+ })
+} else {
+ console.info('Succeed in obtaining new pixel map.');
+}
+```
+
+### scale9+
+
+scale(x: number, y: number, callback: AsyncCallback\): void
+
+Scales this image based on the input width and height. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ------------------------------- |
+| x | number | Yes | Scaling ratio of the width.|
+| y | number | Yes | Scaling ratio of the height.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned. |
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.scale(2.0, 1.0);
+}
+```
+
+### scale9+
+
+scale(x: number, y: number): Promise\
+
+Scales this image based on the input width and height. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------------------------- |
+| x | number | Yes | Scaling ratio of the width.|
+| y | number | Yes | Scaling ratio of the height.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.scale(2.0, 1.0);
+}
+```
+
+### translate9+
+
+translate(x: number, y: number, callback: AsyncCallback\): void
+
+Translates this image based on the input coordinates. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------- |
+| x | number | Yes | X coordinate to translate. |
+| y | number | Yes | Y coordinate to translate. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.translate(3.0, 1.0);
+}
+```
+
+### translate9+
+
+translate(x: number, y: number): Promise\
+
+Translates this image based on the input coordinates. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ----------- |
+| x | number | Yes | X coordinate to translate.|
+| y | number | Yes | Y coordinate to translate.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.translate(3.0, 1.0);
+}
+```
+
+### rotate9+
+
+rotate(angle: number, callback: AsyncCallback\): void
+
+Rotates this image based on the input angle. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------- |
+| angle | number | Yes | Angle to rotate. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.rotate(90.0);
+}
+```
+
+### rotate9+
+
+rotate(angle: number): Promise\
+
+Rotates this image based on the input angle. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ----------------------------- |
+| angle | number | Yes | Angle to rotate. |
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.rotate(90.0);
+}
+```
+
+### flip9+
+
+flip(horizontal: boolean, vertical: boolean, callback: AsyncCallback\): void
+
+Flips this image horizontally or vertically, or both. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | -------------------- | ---- | ----------------------------- |
+| horizontal | boolean | Yes | Whether to flip the image horizontally. |
+| vertical | boolean | Yes | Whether to flip the image vertically. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.flip(false, true);
+}
+```
+
+### flip9+
+
+flip(horizontal: boolean, vertical: boolean): Promise\
+
+Flips this image horizontally or vertically, or both. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------- | ---- | --------- |
+| horizontal | boolean | Yes | Whether to flip the image horizontally.|
+| vertical | boolean | Yes | Whether to flip the image vertically.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.flip(false, true);
+}
+```
+
+### crop9+
+
+crop(region: Region, callback: AsyncCallback\): void
+
+Crops this image based on the input size. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ----------------------------- |
+| region | [Region](#region7) | Yes | Size of the image after cropping. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.crop(3x3);
+}
+```
+
+### crop9+
+
+crop(region: Region): Promise\
+
+Crops this image based on the input size. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------------------ | ---- | ----------- |
+| region | [Region](#region7) | Yes | Size of the image after cropping.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+async function () {
+ await pixelMap.crop(3x3);
+}
+```
+
### release7+
release():Promise\
Releases this **PixelMap** object. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
-| Type | Description |
-| -------------- | ------------------ |
-| Promise\ | Promise used to return the operation result.|
+| Type | Description |
+| -------------- | ------------------------------- |
+| Promise\ | Promise used to return the result.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (pixelmap) => {
pixelmap.release().then(() => {
@@ -483,25 +876,23 @@ release(callback: AsyncCallback\): void
Releases this **PixelMap** object. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------ |
-| callback | AsyncCallback\ | Yes | Callback used to return the operation result.|
+| callback | AsyncCallback\ | Yes | Callback used to return the result.|
**Example**
```js
const color = new ArrayBuffer(96);
-let bufferArr = new Unit8Array(color);
+let bufferArr = new Uint8Array(color);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (pixelmap) => {
pixelmap.release().then(() => {
console.log('Succeeded in releasing pixelmap object.');
- }).catch(error => {
- console.log('Failed to release pixelmap object.');
})
})
```
@@ -512,7 +903,7 @@ createImageSource(uri: string): ImageSource
Creates an **ImageSource** instance based on the URI.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -533,18 +924,45 @@ let path = this.context.getApplicationContext().fileDirs + "test.jpg";
const imageSourceApi = image.createImageSource(path);
```
+## image.createImageSource9+
+
+createImageSource(uri: string, options: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance based on the URI.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------------------------- | ---- | ----------------------------------- |
+| uri | string | Yes | Image path. Currently, only the application sandbox path is supported. |
+| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | -------------------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.|
+
+**Example**
+
+```js
+const imageSourceApi = image.createImageSource('/sdcard/test.jpg');
+```
+
## image.createImageSource7+
createImageSource(fd: number): ImageSource
Creates an **ImageSource** instance based on the file descriptor.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | -------------- |
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------- |
| fd | number | Yes | File descriptor.|
**Return value**
@@ -559,13 +977,144 @@ Creates an **ImageSource** instance based on the file descriptor.
const imageSourceApi = image.createImageSource(0);
```
+## image.createImageSource9+
+
+createImageSource(fd: number, options: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance based on the file descriptor.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------------------------- | ---- | ----------------------------------- |
+| fd | number | Yes | File descriptor. |
+| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | -------------------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.|
+
+**Example**
+
+```js
+const imageSourceApi = image.createImageSource(fd);
+```
+
+## image.createImageSource9+
+
+createImageSource(buf: ArrayBuffer): ImageSource
+
+Creates an **ImageSource** instance based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ----------- | ---- | ---------------- |
+| buf | ArrayBuffer | Yes | Array of image buffers.|
+
+**Example**
+
+```js
+const buf = new ArrayBuffer(96);
+const imageSourceApi = image.createImageSource(buf);
+```
+
+## image.createImageSource9+
+
+createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | -------------------------------- | ---- | ------------------------------------ |
+| buf | ArrayBuffer | Yes | Array of image buffers. |
+| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | -------------------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.|
+
+**Example**
+
+```js
+const data = new ArrayBuffer(112);
+const imageSourceApi = image.createImageSource(data);
+```
+
+## image.CreateIncrementalSource9+
+
+CreateIncrementalSource(buf: ArrayBuffer): ImageSource
+
+Creates an **ImageSource** instance in incremental mode based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------| ---- | ----------|
+| buf | ArrayBuffer | Yes | Incremental data.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | --------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns undefined otherwise.|
+
+**Example**
+
+```js
+const buf = new ArrayBuffer(96);
+const imageSourceApi = image.CreateIncrementalSource(buf);
+```
+
+## image.CreateIncrementalSource9+
+
+CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
+
+Creates an **ImageSource** instance in incremental mode based on the buffer.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------------------------------- | ---- | ------------------------------------ |
+| buf | ArrayBuffer | Yes | Incremental data. |
+| options | [SourceOptions](#sourceoptions9) | No | Image properties, including the image index and default property value.|
+
+**Return value**
+
+| Type | Description |
+| --------------------------- | --------------------------------- |
+| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns undefined otherwise.|
+
+**Example**
+
+```js
+const buf = new ArrayBuffer(96);
+const imageSourceApi = image.CreateIncrementalSource(buf);
+```
+
## ImageSource
Provides APIs to obtain image information. Before calling any API in **ImageSource**, you must use **createImageSource** to create an **ImageSource** instance.
### Attributes
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Readable| Writable| Description |
| ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
@@ -577,7 +1126,7 @@ getImageInfo(index: number, callback: AsyncCallback\): void
Obtains information about an image with the specified index. This API uses an asynchronous callback to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -604,7 +1153,7 @@ getImageInfo(callback: AsyncCallback\): void
Obtains information about this image. This API uses an asynchronous callback to return the information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -626,7 +1175,7 @@ getImageInfo(index?: number): Promise\
Obtains information about an image with the specified index. This API uses a promise to return the image information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -657,7 +1206,7 @@ getImageProperty(key:string, options?: GetImagePropertyOptions): Promise\ | Promise used to return the property value. If the operation fails, the default value is returned.|
**Example**
@@ -687,7 +1236,7 @@ getImageProperty(key:string, callback: AsyncCallback\): void
Obtains the value of a property with the specified index in this image. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -714,14 +1263,14 @@ getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCa
Obtains the value of a property in this image. This API uses an asynchronous callback to return the property value in a string.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
-| key | string | Yes | Name of the property. |
-| options | [GetImagePropertyOptions](#getimagepropertyoptions7) | Yes | Image properties, including the image index and default property value. |
+| Name | Type | Mandatory| Description |
+| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------- |
+| key | string | Yes | Name of the property. |
+| options | [GetImagePropertyOptions](#getimagepropertyoptions7) | Yes | Image properties, including the image index and default property value. |
| callback | AsyncCallback\ | Yes | Callback used to return the property value. If the operation fails, the default value is returned.|
**Example**
@@ -737,13 +1286,128 @@ imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {
})
```
+### modifyImageProperty9+
+
+modifyImageProperty(key: string, value: string): Promise\
+
+Modifies the value of a property in this image. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ------ | ---- | ------------ |
+| key | string | Yes | Name of the property.|
+| value | string | Yes | New value of the property. |
+
+**Return value**
+
+| Type | Description |
+| -------------- | --------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+imageSourceApi.modifyImageProperty("ImageWidth", "120")
+ .then(() => {
+ const w = imageSourceApi.getImageProperty("ImageWidth")
+ console.info('w', w);
+ })
+```
+
+### modifyImageProperty9+
+
+modifyImageProperty(key: string, value: string, callback: AsyncCallback\): void
+
+Modifies the value of a property in this image. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------- | ---- | ------------------------------ |
+| key | string | Yes | Name of the property. |
+| value | string | Yes | New value of the property. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+imageSourceApi.modifyImageProperty("ImageWidth", "120",() => {})
+```
+
+### updateData9+
+
+updateData(buf: ArrayBuffer, isFinished: boolean, value: number, length: number): Promise\
+
+Updates incremental data. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ----------- | ---- | ------------ |
+| buf | ArrayBuffer | Yes | Incremental data. |
+| isFinished | boolean | Yes | Whether the update is complete.|
+| value | number | No | Offset for data reading. |
+| length | number | No | Array length. |
+
+**Return value**
+
+| Type | Description |
+| -------------- | -------------------------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+const array = new ArrayBuffer(100);
+imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => {
+ console.info('Succeeded in updating data.');
+ })
+```
+
+
+### updateData9+
+
+updateData(buf: ArrayBuffer, isFinished: boolean, value: number, length: number, callback: AsyncCallback\): void
+
+Updates incremental data. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------- | ---- | -------------------- |
+| buf | ArrayBuffer | Yes | Incremental data. |
+| isFinished | boolean | Yes | Whether the update is complete. |
+| value | number | No | Offset for data reading. |
+| length | number | No | Array length. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+const array = new ArrayBuffer(100);
+imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {
+ if(data !== undefined){
+ console.info('Succeeded in updating data.');
+ }
+ })
+```
+
### createPixelMap7+
createPixelMap(options?: DecodingOptions): Promise\
Creates a **PixelMap** object based on image decoding parameters. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -773,7 +1437,7 @@ createPixelMap(callback: AsyncCallback\): void
Creates a **PixelMap** object based on the default parameters. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -784,11 +1448,9 @@ Creates a **PixelMap** object based on the default parameters. This API uses an
**Example**
```js
-imageSourceApi.createPixelMap(pixelmap => {
- console.log('Succeeded in creating pixelmap object.');
-}).catch(error => {
- console.log('Failed to create pixelmap object.');
-})
+imageSourceApi.createPixelMap((err, pixelmap) => {
+ console.info('Succeeded in creating pixelmap object.');
+ })
```
### createPixelMap7+
@@ -797,7 +1459,7 @@ createPixelMap(options: DecodingOptions, callback: AsyncCallback\): vo
Creates a **PixelMap** object based on image decoding parameters. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -821,7 +1483,7 @@ release(callback: AsyncCallback\): void
Releases this **ImageSource** instance. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Parameters**
@@ -843,13 +1505,13 @@ release(): Promise\
Releases this **ImageSource** instance. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
**Return value**
| Type | Description |
| -------------- | --------------------------- |
-| Promise\ | Promise used to return the operation result.|
+| Promise\ | Promise used to return the result.|
**Example**
@@ -867,7 +1529,7 @@ createImagePacker(): ImagePacker
Creates an **ImagePacker** instance.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Return value**
@@ -887,7 +1549,7 @@ Provide APIs to pack images. Before calling any API in **ImagePacker**, you must
### Attributes
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
| Name | Type | Readable| Writable| Description |
| ---------------- | -------------- | ---- | ---- | -------------------------- |
@@ -899,7 +1561,7 @@ packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\
Packs an image. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Parameters**
@@ -935,8 +1597,8 @@ Packs an image. This API uses a promise to return the result.
**Return value**
| Type | Description |
-| :--------------------------- | :-------------------------------------------- |
-| Promise\ | Promise used to return the packed data.|
+| ---------------------------- | --------------------------------------------- |
+| Promise\ | Promise used to return the packed data.|
**Example**
@@ -957,7 +1619,7 @@ packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\ {
console.log('Succeeded in packing the image.');
-}).catch(error => {
- console.log('Failed to pack the image.');
})
```
@@ -985,7 +1645,7 @@ packing(source: PixelMap, option: PackingOption): Promise\
Packs an image. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Parameters**
@@ -996,8 +1656,8 @@ Packs an image. This API uses a promise to return the result.
**Return value**
-| Type | Description |
-| :--------------------------- | :-------------------------------------------- |
+| Type | Description |
+| --------------------- | -------------------------------------------- |
| Promise\ | Promise used to return the packed data.|
**Example**
@@ -1019,7 +1679,7 @@ release(callback: AsyncCallback\): void
Releases this **ImagePacker** instance. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Parameters**
@@ -1041,12 +1701,12 @@ release(): Promise\
Releases this **ImagePacker** instance. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
**Return value**
-| Type | Description |
-| :------------- | :------------------------------------------------------ |
+| Type | Description |
+| -------------- | ------------------------------------------------------ |
| Promise\ | Promise used to return the instance release result. If the operation fails, an error message is returned.|
**Example**
@@ -1098,11 +1758,11 @@ Before calling any APIs in **ImageReceiver**, you must create an **ImageReceiver
**System capability**: SystemCapability.Multimedia.Image.ImageReceiver
-| Name | Type | Readable| Writable| Description |
-| --------------------- | ---------------------------- | ---- | ---- | ------------------ |
-| size9+ | [Size](#size) | Yes | No | Image size. |
-| capacity9+ | number | Yes | No | Maximum number of images that can be accessed at the same time.|
-| format9+ | [ImageFormat](#imageformat9) | Yes | No | Image format. |
+| Name | Type | Readable| Writable| Description |
+| -------- | ---------------------------- | ---- | ---- | ------------------ |
+| size | [Size](#size) | Yes | No | Image size. |
+| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.|
+| format | [ImageFormat](#imageformat9) | Yes | No | Image format. |
### getReceivingSurfaceId9+
@@ -1192,7 +1852,7 @@ Reads the latest image from the **ImageReceiver** instance. This API uses a prom
| Type | Description |
| ------------------------- | ------------------ |
-| Promise<[Image](#image8)> | Promise used to return the latest image.|
+| Promise<[Image](#image9)> | Promise used to return the latest image.|
**Example**
@@ -1327,11 +1987,11 @@ Provides APIs for basic image operations, including obtaining image information
**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Type | Readable| Writable| Description |
-| --------------------- | ------------------ | ---- | ---- | -------------------------------------------------- |
-| clipRect9+ | [Region](#region7) | Yes | Yes | Image area to be cropped. |
-| size9+ | [Size](#size) | Yes | No | Image size. |
-| format9+ | number | Yes | No | Image format. For details, see [PixelMapFormat](#pixelmapformat7).|
+| Name | Type | Readable| Writable| Description |
+| -------- | ------------------ | ---- | ---- | -------------------------------------------------- |
+| clipRect | [Region](#region7) | Yes | Yes | Image area to be cropped. |
+| size | [Size](#size) | Yes | No | Image size. |
+| format | number | Yes | No | Image format. For details, see [PixelMapFormat](#pixelmapformat7).|
### getComponent9+
@@ -1407,8 +2067,6 @@ The corresponding resources must be released before another image arrives.
```js
img.release(() =>{
console.log('release succeeded.');
-}).catch(error => {
- console.log('release failed.');
})
```
@@ -1442,7 +2100,7 @@ img.release().then(() =>{
Describes area information in an image.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Type | Readable| Writable| Description |
| ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ |
@@ -1455,7 +2113,7 @@ Describes area information in an image.
Describes image information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name| Type | Readable| Writable| Description |
| ---- | ------------- | ---- | ---- | ---------- |
@@ -1465,7 +2123,7 @@ Describes image information.
Describes the size of an image.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Type | Readable| Writable| Description |
| ------ | ------ | ---- | ---- | -------------- |
@@ -1476,19 +2134,20 @@ Describes the size of an image.
Enumerates the pixel formats of images.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Default Value| Description |
-| --------- | ------ | ----------------- |
-| UNKNOWN | 0 | Unknown format. |
-| RGBA_8888 | 3 | RGBA_8888.|
-| RGB_565 | 2 | RGB_565. |
+| Name | Default Value| Description |
+| ---------------------- | ------ | ----------------- |
+| UNKNOWN | 0 | Unknown format. |
+| RGB_565 | 2 | RGB_565. |
+| RGBA_8888 | 3 | RGBA_8888.|
+| BGRA_88889+ | 4 | BGRA_8888.|
## AlphaType9+
Enumerates the alpha types of images.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Default Value| Description |
| -------- | ------ | ----------------------- |
@@ -1501,32 +2160,45 @@ Enumerates the alpha types of images.
Enumerates the scale modes of images.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name | Default Value| Description |
| --------------- | ------ | -------------------------------------------------- |
| CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.|
| FIT_TARGET_SIZE | 2 | Reduces the image size to the dimensions of the target. |
+## SourceOptions9+
+
+Defines image source initialization options.
+
+**System capability**: SystemCapability.Multimedia.Image.Core
+
+| Name | Type | Readable| Writable| Description |
+| ----------------- | ---------------------------------- | ---- | ---- | ------------------ |
+| sourceDensity | number | Yes | Yes | Density of the image source.|
+| sourcePixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel format of the image source. |
+| sourceSize | [Size](#size) | Yes | Yes | Pixel size of the image source. |
+
+
## InitializationOptions8+
Defines pixel map initialization options.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Type | Readable| Writable| Description |
-| ---------------------- | ---------------------------------- | ---- | ---- | -------------- |
-| alphaType9+ | [AlphaType](#alphatype9) | Yes | Yes | Alpha type. |
-| editable | boolean | Yes | Yes | Whether the image is editable. |
-| pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. |
-| scaleMode9+ | [ScaleMode](#scalemode9) | Yes | Yes | Scale mode. |
-| size | [Size](#size) | Yes | Yes | Image size.|
+| Name | Type | Readable| Writable| Description |
+| ------------------------ | ---------------------------------- | ---- | ---- | -------------- |
+| alphaType9+ | [AlphaType](#alphatype9) | Yes | Yes | Alpha type. |
+| editable | boolean | Yes | Yes | Whether the image is editable. |
+| pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. |
+| scaleMode9+ | [ScaleMode](#scalemode9) | Yes | Yes | Scale mode. |
+| size | [Size](#size) | Yes | Yes | Image size.|
## DecodingOptions7+
Defines image decoding options.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Readable| Writable| Description |
| ------------------ | ---------------------------------- | ---- | ---- | ---------------- |
@@ -1542,7 +2214,7 @@ Defines image decoding options.
Describes region information.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
| Name| Type | Readable| Writable| Description |
| ---- | ------------- | ---- | ---- | ------------ |
@@ -1554,18 +2226,18 @@ Describes region information.
Defines the option for image packing.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImagePacker
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | -------------- |
-| format | string | Yes | Yes | Format of the packed image. |
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | --------------------------------------------------- |
+| format | string | Yes | Yes | Format of the packed image. |
| quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.|
## GetImagePropertyOptions7+
Describes image properties.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.ImageSource
| Name | Type | Readable| Writable| Description |
| ------------ | ------ | ---- | ---- | ------------ |
@@ -1576,18 +2248,18 @@ Describes image properties.
Describes the exchangeable image file format (Exif) information of an image.
-**System capability**: SystemCapability.Multimedia.Image
+**System capability**: SystemCapability.Multimedia.Image.Core
-| Name | Default Value | Description |
-| ----------------- | ----------------- | -------------------- |
-| BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. |
-| ORIENTATION | "Orientation" | Image orientation. |
-| IMAGE_LENGTH | "ImageLength" | Image length. |
-| IMAGE_WIDTH | "ImageWidth" | Image width. |
-| GPS_LATITUDE | "GPSLatitude" | Image latitude. |
-| GPS_LONGITUDE | "GPSLongitude" | Image longitude. |
-| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S.|
-| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E.|
+| Name | Default Value | Description |
+| ----------------- | ----------------------- | ------------------------ |
+| BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. |
+| ORIENTATION | "Orientation" | Image orientation. |
+| IMAGE_LENGTH | "ImageLength" | Image length. |
+| IMAGE_WIDTH | "ImageWidth" | Image width. |
+| GPS_LATITUDE | "GPSLatitude" | Image latitude. |
+| GPS_LONGITUDE | "GPSLongitude" | Image longitude. |
+| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. |
+| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. |
## ImageFormat9+
@@ -1625,3 +2297,45 @@ Describes the color components of an image.
| rowStride | number | Yes | No | Row stride. |
| pixelStride | number | Yes | No | Pixel stride. |
| byteBuffer | ArrayBuffer | Yes | No | Component buffer.|
+
+## ResponseCode
+
+Enumerates the response codes returned upon build errors.
+
+| Name | Value | Description |
+| ----------------------------------- | -------- | --------------------------------------------------- |
+| ERR_MEDIA_INVALID_VALUE | -1 | Invalid value. |
+| SUCCESS | 0 | Operation successful. |
+| ERROR | 62980096 | Operation failed. |
+| ERR_IPC | 62980097 | IPC error. |
+| ERR_SHAMEM_NOT_EXIST | 62980098 | The shared memory does not exist. |
+| ERR_SHAMEM_DATA_ABNORMAL | 62980099 | The shared memory is abnormal. |
+| ERR_IMAGE_DECODE_ABNORMAL | 62980100 | An error occurs during image decoding. |
+| ERR_IMAGE_DATA_ABNORMAL | 62980101 | The input image data is incorrect. |
+| ERR_IMAGE_MALLOC_ABNORMAL | 62980102 | An error occurs during image memory allocation. |
+| ERR_IMAGE_DATA_UNSUPPORT | 62980103 | Unsupported image type. |
+| ERR_IMAGE_INIT_ABNORMAL | 62980104 | An error occurs during image initialization. |
+| ERR_IMAGE_GET_DATA_ABNORMAL | 62980105 | An error occurs during image data retrieval. |
+| ERR_IMAGE_TOO_LARGE | 62980106 | The image data is too large. |
+| ERR_IMAGE_TRANSFORM | 62980107 | An error occurs during image transformation. |
+| ERR_IMAGE_COLOR_CONVERT | 62980108 | An error occurs during image color conversion. |
+| ERR_IMAGE_CROP | 62980109 | An error occurs during image cropping. |
+| ERR_IMAGE_SOURCE_DATA | 62980110 | The image source data is incorrect. |
+| ERR_IMAGE_SOURCE_DATA_INCOMPLETE | 62980111 | The image source data is incomplete. |
+| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image format does not match. |
+| ERR_IMAGE_UNKNOWN_FORMAT | 62980113 | Unknown image format. |
+| ERR_IMAGE_SOURCE_UNRESOLVED | 62980114 | The image source is not parsed. |
+| ERR_IMAGE_INVALID_PARAMETER | 62980115 | Invalid image parameter. |
+| ERR_IMAGE_DECODE_FAILED | 62980116 | Decoding failed. |
+| ERR_IMAGE_PLUGIN_REGISTER_FAILED | 62980117 | Failed to register the plug-in. |
+| ERR_IMAGE_PLUGIN_CREATE_FAILED | 62980118 | Failed to create the plug-in. |
+| ERR_IMAGE_ENCODE_FAILED | 62980119 | Failed to encode the image. |
+| ERR_IMAGE_ADD_PIXEL_MAP_FAILED | 62980120 | Failed to add the image pixel map. |
+| ERR_IMAGE_HW_DECODE_UNSUPPORT | 62980121 | Unsupported image hardware decoding. |
+| ERR_IMAGE_DECODE_HEAD_ABNORMAL | 62980122 | The image decoding header is incorrect. |
+| ERR_IMAGE_DECODE_EXIF_UNSUPPORT | 62980123 | EXIF decoding is not supported. |
+| ERR_IMAGE_PROPERTY_NOT_EXIST | 62980124 | The image property does not exist. The error codes for the image start from 150.|
+| ERR_IMAGE_READ_PIXELMAP_FAILED | 62980246 | Failed to read the pixel map. |
+| ERR_IMAGE_WRITE_PIXELMAP_FAILED | 62980247 | Failed to write the pixel map. |
+| ERR_IMAGE_PIXELMAP_NOT_ALLOW_MODIFY | 62980248 | Modification to the pixel map is not allowed. |
+| ERR_IMAGE_CONFIG_FAILED | 62980259 | The software parameter setting is incorrect. |
diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md
index b863c6189f1c4d89bf5b7ccb7fd3dc887992ec03..3abc771bff725718ccd5df3eb0334331701faea4 100644
--- a/en/application-dev/reference/apis/js-apis-resource-manager.md
+++ b/en/application-dev/reference/apis/js-apis-resource-manager.md
@@ -2,7 +2,8 @@
The resource management module provides APIs to obtain information about the current device configuration (including the language, region, screen direction, and MCC/MNC) and device capability (including the device type and resolution).
-> **NOTE**
+> **NOTE**
+>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -12,9 +13,9 @@ The resource management module provides APIs to obtain information about the cur
import resourceManager from '@ohos.resourceManager';
```
-## Usage
+## How to Use
-Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its APIs without first importing the required bundle. This method, however, is not applicable to the FA model.
+Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This method, however, is not applicable to the FA model.
```
this.context.resourceManager;
@@ -26,14 +27,14 @@ getResourceManager(callback: AsyncCallback<ResourceManager>): void
Obtains the **ResourceManager** object of this application. This API uses an asynchronous callback to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------- |
-| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the result.|
**Example**
```
@@ -59,7 +60,7 @@ getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManage
Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses an asynchronous callback to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
@@ -67,7 +68,7 @@ This API is used only in the FA model.
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ----------------------------- |
| bundleName | string | Yes | Bundle name of the target application. |
-| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the result.|
**Example**
```
@@ -82,7 +83,7 @@ getResourceManager(): Promise<ResourceManager>
Obtains the **ResourceManager** object of this application. This API uses a promise to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
@@ -113,7 +114,7 @@ getResourceManager(bundleName: string): Promise<ResourceManager>
Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses a promise to return the result.
-This API is used only in the FA model.
+This API can be used only in the FA model.
**System capability**: SystemCapability.Global.ResourceManager
@@ -229,21 +230,34 @@ resourceManager.getResourceManager((error, mgr) => {
## RawFileDescriptor8+
-Defines the descriptor information of the raw file.
+Defines the descriptor of the raw file.
**System capability**: SystemCapability.Global.ResourceManager
| Name | Type | Description |
| ------ | ------ | ------------------ |
-| fd | number | Descriptor of a raw file.|
-| offset | number | Offset to the start position of the raw file. |
+| fd | number | Descriptor of the raw file.|
+| offset | number | Start offset of the raw file. |
| length | number | Length of the raw file. |
+## Resource9+
+
+Defines the resource information of an application.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+| Name | Type | Description |
+| ------ | ------ | ------------------ |
+| bundleName | string | Bundle name of the application.|
+| moduleName | string | Module name of the application. |
+| id | number | Resource ID. |
+
## ResourceManager
Defines the capability of accessing application resources.
-> **NOTE**
+> **NOTE**
+>
> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm.
>
> - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**.
@@ -261,7 +275,7 @@ Obtains the string corresponding to the specified resource ID. This API uses an
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
@@ -307,6 +321,68 @@ Obtains the string corresponding to the specified resource ID. This API uses a p
```
+### getString9+
+
+getString(resource: Resource, callback: AsyncCallback<string>): void
+
+Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
+ this.context.resourceManager.getString(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
+ });
+ ```
+
+### getString9+
+
+getString(resource: Resource): Promise<string>
+
+Obtains the string corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| Promise<string> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
+ this.context.resourceManager.getString(resource).then(value => {
+ let str = value;
+ }).catch(error => {
+ console.log("getstring promise error is " + error);
+ });
+ ```
+
### getStringArray
getStringArray(resId: number, callback: AsyncCallback<Array<string>>): void
@@ -319,7 +395,7 @@ Obtains the string array corresponding to the specified resource ID. This API us
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
**Example**
```
@@ -364,6 +440,67 @@ Obtains the string array corresponding to the specified resource ID. This API us
});
```
+### getStringArray9+
+
+getStringArray(resource: Resource, callback: AsyncCallback<Array<string>>): void
+
+Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.strarray.test').id
+ };
+ this.context.resourceManager.getStringArray(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let strArray = value;
+ }
+ });
+ ```
+
+### getStringArray9+
+
+getStringArray(resource: Resource): Promise<Array<string>>
+
+Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| Promise<Array<string>> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.strarray.test').id
+ };
+ this.context.resourceManager.getStringArray(resource).then(value => {
+ let strArray = value;
+ }).catch(error => {
+ console.log("getStringArray promise error is " + error);
+ });
+ ```
### getMedia
@@ -377,7 +514,7 @@ Obtains the content of the media file corresponding to the specified resource ID
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Example**
```
@@ -422,6 +559,67 @@ Obtains the content of the media file corresponding to the specified resource ID
});
```
+### getMedia9+
+
+getMedia(resource: Resource, callback: AsyncCallback<Uint8Array>): void
+
+Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMedia(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
+ });
+ ```
+
+### getMedia9+
+
+getMedia(resource: Resource): Promise<Uint8Array>
+
+Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| Promise<Uint8Array> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMedia(resource).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.log("getMedia promise error is " + error);
+ });
+ ```
### getMediaBase64
@@ -435,7 +633,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID.
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
@@ -480,6 +678,68 @@ Obtains the Base64 code of the image corresponding to the specified resource ID.
});
```
+### getMediaBase649+
+
+getMediaBase64(resource: Resource, callback: AsyncCallback<string>): void
+
+Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------ |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMediaBase64(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
+ });
+ ```
+
+### getMediaBase649+
+
+getMediaBase64(resource: Resource): Promise<string>
+
+Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | -------------------- |
+| Promise<string> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ this.context.resourceManager.getMediaBase64(resource).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.log("getMediaBase64 promise error is " + error);
+ });
+ ```
+
### getConfiguration
@@ -492,7 +752,7 @@ Obtains the device configuration. This API uses an asynchronous callback to retu
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------- |
-| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the result.|
**Example**
```
@@ -546,7 +806,7 @@ Obtains the device capability. This API uses an asynchronous callback to return
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------- |
-| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the result.|
**Example**
```
@@ -593,7 +853,7 @@ Obtains the device capability. This API uses a promise to return the result.
getPluralString(resId: number, num: number, callback: AsyncCallback<string>): void
-Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -601,8 +861,8 @@ Obtains the specified number of singular-plural strings corresponding to the spe
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------------- |
| resId | number | Yes | Resource ID. |
-| num | number | Yes | Number that determines the plural or singular form. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
@@ -622,7 +882,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe
getPluralString(resId: number, num: number): Promise<string>
-Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -630,7 +890,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
-| num | number | Yes | Number that determines the plural or singular form. |
+| num | number | Yes | Number. |
**Return value**
| Type | Description |
@@ -648,6 +908,70 @@ Obtains the specified number of singular-plural strings corresponding to the spe
});
```
+### getPluralString9+
+
+getPluralString(resource: Resource, num: number, callback: AsyncCallback<string>): void
+
+Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.plural.test').id
+ };
+ this.context.resourceManager.getPluralString(resource, 1, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
+ });
+ ```
+
+### getPluralString9+
+
+getPluralString(resource: Resource, num: number): Promise<string>
+
+Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+| num | number | Yes | Number. |
+
+**Return value**
+| Type | Description |
+| --------------------- | ------------------------- |
+| Promise<string> | Promise used to return the result.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.plural.test').id
+ };
+ this.context.resourceManager.getPluralString(resource, 1).then(value => {
+ let str = value;
+ }).catch(error => {
+ console.log("getPluralString promise error is " + error);
+ });
+ ```
+
### getRawFile8+
getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void
@@ -660,7 +984,7 @@ Obtains the content of the raw file in the **resources/rawfile** directory. This
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ----------------------- |
| path | string | Yes | Path of the raw file. |
-| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Example**
```
@@ -716,7 +1040,7 @@ Obtains the descriptor of the raw file in the **resources/rawfile** directory. T
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------------------- |
| path | string | Yes | Path of the raw file. |
-| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.|
**Example**
```
@@ -776,7 +1100,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ----------- |
| path | string | Yes | Path of the raw file.|
-| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```
@@ -805,7 +1129,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th
**Return value**
| Type | Description |
| ------------------- | ---- |
-| Promise<void> | No value is returned.|
+| Promise<void> | Promise that returns no value.|
**Example**
```
@@ -822,7 +1146,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th
release()
-Releases the created **resourceManager**.
+Releases a created **resourceManager** object.
**System capability**: SystemCapability.Global.ResourceManager
@@ -845,11 +1169,11 @@ Obtains the string corresponding to the specified resource name. This API uses a
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------- |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getStringByName("test", (error, value) => {
+ this.context.resourceManager.getStringByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -874,11 +1198,11 @@ Obtains the string corresponding to the specified resource name. This API uses a
**Return value**
| Type | Description |
| --------------------- | ----------- |
-| Promise<string> | String corresponding to the resource name.|
+| Promise<string> | Promise used to return the result.|
**Example**
```
- resourceManager.getStringByName("test").then(value => {
+ this.context.resourceManager.getStringByName("test").then(value => {
let string = value;
}).catch(error => {
console.log("getStringByName promise error is " + error);
@@ -897,11 +1221,11 @@ Obtains the string array corresponding to the specified resource name. This API
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getStringArrayByName("test", (error, value) => {
+ this.context.resourceManager.getStringArrayByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -930,7 +1254,7 @@ Obtains the string array corresponding to the specified resource name. This API
**Example**
```
- resourceManager.getStringArrayByName("test").then(value => {
+ this.context.resourceManager.getStringArrayByName("test").then(value => {
let strArray = value;
}).catch(error => {
console.log("getStringArrayByName promise error is " + error);
@@ -949,11 +1273,11 @@ Obtains the content of the media file corresponding to the specified resource na
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ------------------ |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getMediaByName("test", (error, value) => {
+ this.context.resourceManager.getMediaByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -982,7 +1306,7 @@ Obtains the content of the media file corresponding to the specified resource na
**Example**
```
- resourceManager.getMediaByName("test").then(value => {
+ this.context.resourceManager.getMediaByName("test").then(value => {
let media = value;
}).catch(error => {
console.log("getMediaByName promise error is " + error);
@@ -1001,11 +1325,11 @@ Obtains the Base64 code of the image corresponding to the specified resource nam
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getMediaBase64ByName("test", (error, value) => {
+ this.context.resourceManager.getMediaBase64ByName("test", (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -1034,7 +1358,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam
**Example**
```
- resourceManager.getMediaByName("test").then(value => {
+ this.context.resourceManager.getMediaBase64ByName("test").then(value => {
let media = value;
}).catch(error => {
console.log("getMediaBase64ByName promise error is " + error);
@@ -1045,7 +1369,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam
getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void
-Obtains the plural string corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
+Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -1053,12 +1377,12 @@ Obtains the plural string corresponding to the specified resource name. This API
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------------- |
| resName | string | Yes | Resource name. |
-| num | number | Yes | Number that determines the plural or singular form. |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.|
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Example**
```
- resourceManager.getPluralStringByName("test", 1, (error, value) => {
+ this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
@@ -1071,7 +1395,7 @@ Obtains the plural string corresponding to the specified resource name. This API
getPluralStringByName(resName: string, num: number): Promise<string>
-Obtains the plural string corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -1079,7 +1403,7 @@ Obtains the plural string corresponding to the specified resource name. This API
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----- |
| resName | string | Yes | Resource name.|
-| num | number | Yes | Number that determines the plural or singular form. |
+| num | number | Yes | Number. |
**Return value**
| Type | Description |
@@ -1088,7 +1412,7 @@ Obtains the plural string corresponding to the specified resource name. This API
**Example**
```
- resourceManager.getPluralStringByName("test", 1).then(value => {
+ this.context.resourceManager.getPluralStringByName("test", 1).then(value => {
let str = value;
}).catch(error => {
console.log("getPluralStringByName promise error is " + error);
@@ -1115,7 +1439,35 @@ Obtains the string corresponding to the specified resource ID. This API returns
**Example**
```
- resourceManager.getStringSync($r('app.string.test').id);
+ this.context.resourceManager.getStringSync($r('app.string.test').id);
+ ```
+
+### getStringSync9+
+
+getStringSync(resource: Resource): string
+
+Obtains the string corresponding to the specified resource object. This API returns the result synchronously.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| string | String corresponding to the resource object.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
+ this.context.resourceManager.getStringSync(resource);
```
### getStringByNameSync9+
@@ -1138,7 +1490,7 @@ Obtains the string corresponding to the specified resource name. This API return
**Example**
```
- resourceManager.getStringByNameSync("test");
+ this.context.resourceManager.getStringByNameSync("test");
```
### getBoolean9+
@@ -1161,7 +1513,34 @@ Obtains the Boolean result corresponding to the specified resource ID. This API
**Example**
```
- resourceManager.getBoolean($r('app.boolean.boolean_test').id);
+ this.context.resourceManager.getBoolean($r('app.boolean.boolean_test').id);
+ ```
+### getBoolean9+
+
+getBoolean(resource: Resource): boolean
+
+Obtains the Boolean result corresponding to the specified resource object. This API returns the result synchronously.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| boolean | Boolean result corresponding to the specified resource object.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.boolean.boolean_test').id
+ };
+ this.context.resourceManager.getBoolean(resource);
```
### getBooleanByName9+
@@ -1184,7 +1563,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP
**Example**
```
- resourceManager.getBooleanByName("boolean_test");
+ this.context.resourceManager.getBooleanByName("boolean_test");
```
### getNumber9+
@@ -1207,8 +1586,36 @@ Obtains the integer or float value corresponding to the specified resource ID. T
**Example**
```
- resourceManager.getNumber($r('app.integer.integer_test').id);
- resourceManager.getNumber($r('app.float.float_test').id);
+ this.context.resourceManager.getNumber($r('app.integer.integer_test').id);
+ this.context.resourceManager.getNumber($r('app.float.float_test').id);
+ ```
+
+### getNumber9+
+
+getNumber(resource: Resource): number
+
+Obtains the integer or float value corresponding to the specified resource object. This API returns the result synchronously.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ----------- |
+| number | Integer or float value corresponding to the specified resource object.|
+
+**Example**
+ ```
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.integer.integer_test').id
+ };
+ this.context.resourceManager.getNumber(resource);
```
### getNumberByName9+
@@ -1231,6 +1638,6 @@ Obtains the integer or float value corresponding to the specified resource name.
**Example**
```
- resourceManager.getNumberByName("integer_test");
- resourceManager.getNumberByName("float_test");
+ this.context.resourceManager.getNumberByName("integer_test");
+ this.context.resourceManager.getNumberByName("float_test");
```
diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md
index fe414f5d9f4b180cc36d1dbb3c36889924d3840c..ae0847a588b0d66d4e75f19353f2ca98d89cb3c8 100644
--- a/en/application-dev/reference/apis/js-apis-rpc.md
+++ b/en/application-dev/reference/apis/js-apis-rpc.md
@@ -873,7 +873,7 @@ Writes a String value to this **MessageParcel** object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | val | string | Yes| String value to write.|
+ | val | string | Yes| String value to write. The length of the value must be less than 40960 bytes.|
**Return value**
| Type| Description|
@@ -1322,7 +1322,7 @@ Writes a FloatArray to this **MessageParcel** object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | floatArray | number[] | Yes| FloatArray to write.|
+ | floatArray | number[] | Yes| FloatArray to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.|
**Return value**
| Type| Description|
@@ -1349,7 +1349,7 @@ Reads a FloatArray from this **MessageParcel** object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | dataIn | number[] | Yes| FloatArray to read.|
+ | dataIn | number[] | Yes| FloatArray to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.|
**Example**
@@ -1622,7 +1622,7 @@ Writes a StringArray to this **MessageParcel** object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | stringArray | string[] | Yes| StringArray to write.|
+ | stringArray | string[] | Yes| StringArray to write. The length of a single element in the array must be less than 40960 bytes.|
**Return value**
| Type| Description|
@@ -1764,20 +1764,20 @@ Reads the exception information from this **MessageParcel** object.
let reply = rpc.MessageParcel.create();
data.writeInt(1);
data.writeString("hello");
- proxy.sendRequest(1, data, reply, option)
+ proxy.sendRequestAsync(1, data, reply, option)
.then(function(errCode) {
if (errCode === 0) {
- console.log("sendRequest got result");
+ console.log("sendRequestAsync got result");
reply.readException();
let msg = reply.readString();
console.log("RPCTest: reply msg: " + msg);
} else {
- console.log("RPCTest: sendRequest failed, errCode: " + errCode);
+ console.log("RPCTest: sendRequestAsync failed, errCode: " + errCode);
}
}).catch(function(e) {
- console.log("RPCTest: sendRequest got exception: " + e.message);
+ console.log("RPCTest: sendRequestAsync got exception: " + e.message);
}).finally (() => {
- console.log("RPCTest: sendRequest ends, reclaim parcel");
+ console.log("RPCTest: sendRequestAsync ends, reclaim parcel");
data.reclaim();
reply.reclaim();
});
@@ -2504,7 +2504,7 @@ Obtains the interface.
### sendRequest(deprecated)
> **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8).
+> This API is deprecated since API Version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9).
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
@@ -2526,7 +2526,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
-### sendRequest8+
+### sendRequest8+(deprecated)
+
+> **NOTE**
+> This API is deprecated since API Version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9).
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>
@@ -2534,6 +2537,27 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**System capability**: SystemCapability.Communication.IPC.Core
+**Parameters**
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
+ | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.|
+ | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.|
+ | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.|
+
+**Return value**
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.|
+
+### sendRequestAsync9+
+
+sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>
+
+Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information.
+
+**System capability**: SystemCapability.Communication.IPC.Core
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
@@ -2653,7 +2677,7 @@ Provides methods to implement **IRemoteObject**.
### sendRequest(deprecated)
> **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8-2).
+> This API is deprecated since API Version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9-1).
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
@@ -2715,7 +2739,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
reply.reclaim();
```
-### sendRequest8+
+### sendRequest8+(deprecated)
+
+> **NOTE**
+> This API is deprecated since API Version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9-1).
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>
@@ -2782,6 +2809,72 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
});
```
+### sendRequestAsync9+
+
+sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>
+
+Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information.
+
+**System capability**: SystemCapability.Communication.IPC.Core
+
+**Parameters**
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
+ | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.|
+ | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.|
+ | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.|
+
+**Return value**
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.|
+
+**Example**
+
+ ```
+ import FA from "@ohos.ability.featureAbility";
+ let proxy;
+ let connect = {
+ onConnect: function(elementName, remoteProxy) {
+ console.log("RpcClient: js onConnect called.");
+ proxy = remoteProxy;
+ },
+ onDisconnect: function(elementName) {
+ console.log("RpcClient: onDisconnect");
+ },
+ onFailed: function() {
+ console.log("RpcClient: onFailed");
+ }
+ };
+ let want = {
+ "bundleName": "com.ohos.server",
+ "abilityName": "com.ohos.server.MainAbility",
+ };
+ FA.connectAbility(want, connect);
+ let option = new rpc.MessageOption();
+ let data = rpc.MessageParcel.create();
+ let reply = rpc.MessageParcel.create();
+ data.writeInt(1);
+ data.writeString("hello");
+ proxy.sendRequestAsync(1, data, reply, option)
+ .then(function(result) {
+ if (result.errCode === 0) {
+ console.log("sendRequestAsync got result");
+ result.reply.readException();
+ let msg = result.reply.readString();
+ console.log("RPCTest: reply msg: " + msg);
+ } else {
+ console.log("RPCTest: sendRequestAsync failed, errCode: " + result.errCode);
+ }
+ }).catch(function(e) {
+ console.log("RPCTest: sendRequestAsync got exception: " + e.message);
+ }).finally (() => {
+ console.log("RPCTest: sendRequestAsync ends, reclaim parcel");
+ data.reclaim();
+ reply.reclaim();
+ });
+ ```
### sendRequest8+
@@ -3082,7 +3175,7 @@ Provides common message options (flag and wait time). The flag is used to constr
| -------- | -------- | -------- |
| TF_SYNC | 0 | Synchronous call.|
| TF_ASYNC | 1 | Asynchronous call.|
-| TF_ACCEPT_FDS | 0x10 | Indication to the [sendRequest](#sendrequest8) API for returning the file descriptor.|
+| TF_ACCEPT_FDS | 0x10 | Indication to [sendRequestAsync](#sendrequestasync9) for returning the file descriptor.|
| TF_WAIT_TIME | 8 | Time to wait, in seconds.|
@@ -3471,7 +3564,7 @@ A constructor used to create a **RemoteObject** object.
### sendRequest(deprecated)
> **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8-4).
+> This API is deprecated since API Version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9-2).
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
@@ -3535,7 +3628,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
```
-### sendRequest8+
+### sendRequest8+(deprecated)
+
+> **NOTE**
+> This API is deprecated since API Version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9-2).
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>
@@ -3604,6 +3700,73 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
});
```
+### sendRequestAsync9+
+
+sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult>
+
+Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information.
+
+**System capability**: SystemCapability.Communication.IPC.Core
+
+**Parameters**
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
+ | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.|
+ | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.|
+ | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.|
+
+**Return value**
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.|
+
+**Example**
+
+ ```
+ class MyDeathRecipient {
+ onRemoteDied() {
+ console.log("server died");
+ }
+ }
+ class TestRemoteObject extends rpc.RemoteObject {
+ constructor(descriptor) {
+ super(descriptor);
+ }
+ addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean {
+ return true;
+ }
+ removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean {
+ return true;
+ }
+ isObjectDead(): boolean {
+ return false;
+ }
+ }
+ let testRemoteObject = new TestRemoteObject("testObject");
+ let option = new rpc.MessageOption();
+ let data = rpc.MessageParcel.create();
+ let reply = rpc.MessageParcel.create();
+ data.writeInt(1);
+ data.writeString("hello");
+ testRemoteObject.sendRequestAsync(1, data, reply, option)
+ .then(function(result) {
+ if (result.errCode === 0) {
+ console.log("sendRequestAsync got result");
+ result.reply.readException();
+ let msg = result.reply.readString();
+ console.log("RPCTest: reply msg: " + msg);
+ } else {
+ console.log("RPCTest: sendRequestAsync failed, errCode: " + result.errCode);
+ }
+ }).catch(function(e) {
+ console.log("RPCTest: sendRequestAsync got exception: " + e.message);
+ }).finally (() => {
+ console.log("RPCTest: sendRequestAsync ends, reclaim parcel");
+ data.reclaim();
+ reply.reclaim();
+ });
+ ```
### sendRequest8+
@@ -3672,7 +3835,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean
-Provides a response to **sendRequest()**. The server processes the request and returns a response in this function.
+Provides a response to **sendRequestAsync()**. The server processes the request and returns a response in this function.
**System capability**: SystemCapability.Communication.IPC.Core
diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md
index d75b957512e60e55aacfac1fdce2fdf063eb9c56..832d9754db5e41a11d38b020e77673ee5fe4d346 100644
--- a/en/application-dev/reference/apis/js-apis-screen-lock.md
+++ b/en/application-dev/reference/apis/js-apis-screen-lock.md
@@ -1,8 +1,10 @@
# Screen Lock Management
+The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set.
+
> **NOTE**
>
-> The initial APIs of this module are supported since API version … Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
@@ -73,6 +75,7 @@ Checks whether a device is in secure mode. This API uses an asynchronous callbac
**System capability**: SystemCapability.MiscServices.ScreenLock
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
@@ -125,6 +128,7 @@ Unlocks the screen. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
@@ -174,10 +178,12 @@ Subscribes to screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'beginWakeUp'**: Wakeup starts.
- **'endWakeUp'**: Wakeup ends.
- **'beginScreenOn'**: Screen turn-on starts.
- **'endScreenOn'**: Screen turn-on ends.
- **'beginScreenOff'**: Screen turn-off starts.
- **'endScreenOff'**: Screen turn-off ends.
- **'unlockScreen'**: The screen is unlocked.
- **'beginExitAnimation'**: Animation starts to exit. |
+| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.|
| callback | Callback\ | Yes| Callback used to return the result.|
**Example**
@@ -196,10 +202,12 @@ Subscribes to screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'beginSleep'**: The screen enters sleep mode.
- **'endSleep'**: The screen exits sleep mode.
- **'changeUser'**: The user is switched.|
+| type | string | Yes| Event type.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.|
| callback | Callback\ | Yes| Callback used to return the result. |
**Example**
@@ -217,11 +225,13 @@ Subscribes to screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'screenlockEnabled'**: Screen lock is enabled.|
-| callback | Callback\ | Yes| Callback used to return the result. |
+| type | string | Yes| Event type.
- **"screenlockEnabled"**: Screen lock is enabled.|
+| callback | Callback\ | Yes| Callback used to return the result.|
**Example**
@@ -240,10 +250,12 @@ Unsubscribes from screen lock status changes.
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type.
- **'beginWakeUp'**: Wakeup starts.
- **'endWakeUp'**: Wakeup ends.
- **'beginScreenOn'**: Screen turn-on starts.
- **'endScreenOn'**: Screen turn-on ends.
- **'beginScreenOff'**: Screen turn-off starts.
- **'endScreenOff'**: Screen turn-off ends.
- **'unlockScreen'**: The screen is unlocked.
- **'beginExitAnimation'**: Animation starts to exit.
- **'screenlockEnabled'**: Screen lock is enabled.
- **'beginSleep'**: The screen enters sleep mode.
- **'endSleep'**: The screen exits sleep mode.
- **'changeUser'**: The user is switched.|
+| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.
- **"screenlockEnabled"**: Screen lock is enabled.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.|
| callback | Callback\ | Yes| Callback used to return the result.|
**Example**
@@ -262,11 +274,13 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac
**System capability**: SystemCapability.MiscServices.ScreenLock
+**System API**: This is a system API and cannot be called by third-party applications.
+
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| event | String | Yes| Event type.
- **'unlockScreenResult'**: Screen unlock result.
- **'screenDrawDone'**: Screen drawing is complete.|
-| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **0**: The unlock failed.
- **2**: The unlock was canceled.|
+| event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.|
+| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.|
| callback | AsyncCallback\ | Yes| Callback used to return the result.|
**Example**
@@ -279,18 +293,19 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac
## screenlock.sendScreenLockEvent9+
-sendScreenLockEvent(event: String, parameter: number): Promise
+sendScreenLockEvent(event: String, parameter: number): Promise\
Sends an event to the screen lock service. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
-**Parameters**
+**System API**: This is a system API and cannot be called by third-party applications.
+**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| event | String | Yes| Event type.
- **'unlockScreenResult'**: Screen unlock result.
- **'screenDrawDone'**: Screen drawing is complete.|
-| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **0**: The unlock failed.
- **2**: The unlock was canceled.|
+| event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.|
+| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.|
**Return value**
| Type| Description|
@@ -300,7 +315,7 @@ Sends an event to the screen lock service. This API uses a promise to return the
**Example**
```js
- screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((err, result) => {
+ screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => {
console.log('sending result:' + result);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md
index d2c9431ec4c0a4c8c4228b74e3bf85a30c697c0f..94f5f3cb5e532f3e28f221addb164358589b1754 100644
--- a/en/application-dev/reference/apis/js-apis-screen.md
+++ b/en/application-dev/reference/apis/js-apis-screen.md
@@ -223,6 +223,8 @@ Creates a virtual screen. This API uses an asynchronous callback to return the r
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid; available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -256,6 +258,8 @@ Creates a virtual screen. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------- | ---- | ------------------------ |
@@ -343,6 +347,8 @@ Sets the surface for a virtual screen. This API uses an asynchronous callback to
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -372,6 +378,8 @@ Sets the surface for a virtual screen. This API uses a promise to return the res
**System capability**: SystemCapability.WindowManager.WindowManager.Core
+**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications)
+
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------- |
@@ -696,9 +704,6 @@ Enumerates the screen orientations.
| HORIZONTAL | 2 | Horizontal. |
| REVERSE_VERTICAL | 3 | Reverse vertical. |
| REVERSE_HORIZONTAL | 4 | Reverse horizontal. |
-| SENSOR | 5 | The screen orientation follows the sensor direction. |
-| SENSOR_VERTICAL | 6 | The screen orientation follows the sensor direction vertically.|
-| SENSOR_HORIZONTAL | 7 | The screen orientation follows the sensor direction horizontally.|
## ScreenModeInfo
Defines the screen mode information.
diff --git a/en/application-dev/reference/apis/js-apis-securityLabel.md b/en/application-dev/reference/apis/js-apis-securityLabel.md
index 86ae51122132f39ce30fe8df4bebc626c8e07d3f..d61e7c1b5a08c7dcdb841742a8359bac5e12ad69 100644
--- a/en/application-dev/reference/apis/js-apis-securityLabel.md
+++ b/en/application-dev/reference/apis/js-apis-securityLabel.md
@@ -1,10 +1,10 @@
# Security Label
+The **secuityLabel** module provides APIs to manage file data security levels, including obtaining and setting file data security levels.
+
> **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 **secuityLabel** module provides APIs to manage file data security levels, including obtaining and setting file data security levels.
-
## Modules to Import
```js
@@ -48,8 +48,7 @@ Sets the security label for a file in asynchronous mode. This API uses a promise
**Example**
```js
- let type = "s4";
- securityLabel.setSecurityLabel(path, type).then(function(){
+ securityLabel.setSecurityLabel(path, "s0").then(function(){
console.info("setSecurityLabel successfully");
}).catch(function(error){
console.info("setSecurityLabel failed with error:" + error);
@@ -75,8 +74,7 @@ Sets the security label for a file in asynchronous mode. This API uses a callbac
**Example**
```js
- let type = "s4";
- securityLabel.setSecurityLabel(path, type, function(error){
+ securityLabel.setSecurityLabel(path, "s0", function(error){
console.info("setSecurityLabel:" + JSON.stringify(error));
});
```
@@ -98,8 +96,7 @@ Sets the security label for a file in synchronous mode.
**Example**
```js
-let type = "s4";
-securityLabel.setSecurityLabelSync(path, type);
+securityLabel.setSecurityLabelSync(path, "s0");
```
## securityLabel.getSecurityLabel
@@ -125,11 +122,10 @@ Obtains the security label of a file in asynchronous mode. This API uses a promi
**Example**
```js
- let type = "s4";
securityLabel.getSecurityLabel(path).then(function(type){
console.log("getSecurityLabel successfully:" + type);
- }).catch(function(error){
- console.log("getSecurityLabel failed with error:" + error);
+ }).catch(function(err){
+ console.log("getSecurityLabel failed with error:" + err);
});
```
@@ -151,8 +147,7 @@ Obtains the security label of a file in asynchronous mode. This API uses a callb
**Example**
```js
- let type = "s4";
- securityLabel.getSecurityLabel(path,function(error, type){
+ securityLabel.getSecurityLabel(path, function(err, type){
console.log("getSecurityLabel successfully:" + type);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md
index 5606a2e64372c3e002815d535f59851718e535e9..658082d2690c0ab00d76959a1a7ce1c97574ce5d 100644
--- a/en/application-dev/reference/apis/js-apis-storage-statistics.md
+++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md
@@ -1,12 +1,12 @@
# App Storage Statistics
+The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data.
+
> **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.
> - API version 9 is a canary version for trial use. The APIs of this version may be unstable.
-The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data.
-
## Modules to Import
```js
@@ -264,14 +264,13 @@ Asynchronously obtains space information of the current third-party application.
## BundleStats9+
+### Attributes
+
**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics
This is a system API and cannot be called by third-party applications.
-
-### Attributes
-
| Name | Type | Description |
| --------- | ------ | -------------- |
| appSize | number | Size of the application. |
@@ -523,14 +522,13 @@ This is a system API and cannot be called by third-party applications.
## StorageStats9+
+### Attributes
+
**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics
This is a system API and cannot be called by third-party applications.
-
-### Attributes
-
| Name | Type | Description |
| --------- | ------ | -------------- |
| total | number | Total space of the built-in memory card. |
diff --git a/en/application-dev/reference/apis/js-apis-uiappearance.md b/en/application-dev/reference/apis/js-apis-uiappearance.md
index 981e16381df774aa0bfdc7d869f3c7081887883b..3bac964627675b3475e273551d06b146636b410d 100644
--- a/en/application-dev/reference/apis/js-apis-uiappearance.md
+++ b/en/application-dev/reference/apis/js-apis-uiappearance.md
@@ -5,6 +5,7 @@ The **uiAppearance** module provides basic capabilities for managing the system
> **NOTE**
>
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
+>
> The APIs provided by this module are system APIs.
@@ -20,6 +21,8 @@ import uiAppearance from '@ohos.uiAppearance'
Enumerates the color modes.
+**System capability**: SystemCapability.ArkUI.UiAppearance
+
| Name| Value| Description|
| -- | -- | -- |
| ALWAYS_DARK | 0 | The system is always in dark mode. |
@@ -32,12 +35,11 @@ setDarkMode(mode: DarkMode, callback: AsyncCallback\): void
Sets the system color mode. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.UPDATE_CONFIGRATION
+**Permission required**: ohos.permission.UPDATE_CONFIGURATION
-**System capability**: SystemCapability.ArkUI.ArkUI.Full
+**System capability**: SystemCapability.ArkUI.UiAppearance
**Parameters**
-
| Name| Type| Mandatory| Description|
| -- | -- | -- | -- |
| mode | [DarkMode](#darkmode) | Yes| Color mode to set.|
@@ -57,15 +59,21 @@ setDarkMode(mode: DarkMode): Promise\;
Sets the system color mode. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.UPDATE_CONFIGRATION
+**Permission required**: ohos.permission.UPDATE_CONFIGURATION
-**System capability**: SystemCapability.ArkUI.ArkUI.Full
+**System capability**: SystemCapability.ArkUI.UiAppearance
**Parameters**
| Name| Type| Mandatory| Description|
| -- | -- | -- | -- |
| mode | [DarkMode](#darkmode) | Yes| Color mode to set.|
+**Return value**
+
+| Type | Description |
+| ------ | ------------------------------ |
+| Promise\ | Promise that returns no value.|
+
**Example**
```ts
uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK).then(() => {
@@ -82,12 +90,11 @@ getDarkMode(): DarkMode;
Obtains the system color mode.
-**Required permissions**: ohos.permission.UPDATE_CONFIGRATION
+**Permission required**: ohos.permission.UPDATE_CONFIGURATION
-**System capability**: SystemCapability.ArkUI.ArkUI.Full
+**System capability**: SystemCapability.ArkUI.UiAppearance
**Return value**
-
| Type| Description|
| -- | -- |
|[DarkMode](#darkmode) | Color mode obtained.|
diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
index 56ac3823f29e6cee7efa13094d4becf5528fa854..d98f43faaf7bc2a575cfa80907a776d9436bfbff 100644
--- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md
+++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
@@ -1,5 +1,7 @@
# User Authentication
+The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login.
+
> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -10,26 +12,7 @@
import userIAM_userAuth from '@ohos.userIAM.userAuth';
```
-## Example
-
-```js
-// API version 6
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-export default {
- startAuth() {
- console.info("start auth");
- let auth = userIAM_userAuth.getAuthenticator();
- auth.execute("FACE_ONLY", "S2").then((code)=>{
- console.info("auth success");
- // Add the logic to be executed when the authentication is successful.
- }).catch((code)=>{
- console.error("auth fail, code = " + code);
- // Add the logic to be executed when the authentication fails.
- });
- }
-}
-```
+## Sample Code
```js
// API version 8
@@ -106,133 +89,25 @@ export default {
}
```
-## userIAM_userAuth.getAuthenticator(deprecated)
-
-getAuthenticator(): Authenticator
-
-> **NOTE**
-> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8).
-
-Obtains an **Authenticator** object for user authentication.
-
-**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-**Return value**
-| Type | Description |
-| ----------------------------------------- | ------------ |
-| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.|
-
-**Example**
- ```js
- let authenticator = userIAM_userAuth.getAuthenticator();
- ```
-
-## Authenticator(deprecated)
-
-> **NOTE**
-> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8).
-
-Provides methods to manage an **Authenticator** object.
-
-
-### execute(deprecated)
-
-execute(type: string, level: string, callback: AsyncCallback<number>): void
-
-> **NOTE**
-> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
-
-Performs user authentication. This API uses asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
-| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
-| callback | AsyncCallback<number> | No | Callback used to return the result. |
-
- Parameters returned in callback
-
-| Type | Description |
-| ------ | ------------------------------------------------------------ |
-| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
-
-**Example**
- ```js
- authenticator.execute("FACE_ONLY", "S2", (code)=>{
- if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) {
- console.info("auth success");
- return;
- }
- console.error("auth fail, code = " + code);
- })
- ```
-
-
-### execute(deprecated)
-
-execute(type:string, level:string): Promise<number>
-
-> **NOTE**
-> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
-
-Performs user authentication. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
-| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
-
-**Return value**
-| Type | Description |
-| --------------------- | ------------------------------------------------------------ |
-| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
-
-**Example**
-
```js
-let authenticator = userIAM_userAuth.getAuthenticator();
-authenticator.execute("FACE_ONLY", "S2").then((code)=>{
- console.info("auth success");
-}).catch((code)=>{
- console.error("auth fail, code = " + code);
-});
-```
-
-## AuthenticationResult(deprecated)
-
-> **NOTE**
-> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8).
-
-Enumerates the authentication results.
+// API version 6
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
+export default {
+ startAuth() {
+ console.info("start auth");
+ let auth = userIAM_userAuth.getAuthenticator();
+ auth.execute("FACE_ONLY", "S2").then((code)=>{
+ console.info("auth success");
+ // Add the logic to be executed when the authentication is successful.
+ }).catch((code)=>{
+ console.error("auth fail, code = " + code);
+ // Add the logic to be executed when the authentication fails.
+ });
+ }
+}
+```
-| Name | Default Value| Description |
-| ------------------ | ------ | -------------------------- |
-| NO_SUPPORT | -1 | The device does not support the current authentication mode.|
-| SUCCESS | 0 | The authentication is successful. |
-| COMPARE_FAILURE | 1 | The feature comparison failed. |
-| CANCELED | 2 | The authentication was canceled by the user. |
-| TIMEOUT | 3 | The authentication has timed out. |
-| CAMERA_FAIL | 4 | The camera failed to start. |
-| BUSY | 5 | The authentication service is not available. Try again later. |
-| INVALID_PARAMETERS | 6 | The authentication parameters are invalid. |
-| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.|
-| NOT_ENROLLED | 8 | No authentication credential is registered. |
-| GENERAL_ERROR | 100 | Other errors. |
## UserAuth8+
@@ -607,3 +482,131 @@ Enumerates the trust levels of the authentication result.
| ATL2 | 20000 | Trust level 2.|
| ATL3 | 30000 | Trust level 3.|
| ATL4 | 40000 | Trust level 4.|
+
+## userIAM_userAuth.getAuthenticator(deprecated)
+
+getAuthenticator(): Authenticator
+
+> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8).
+
+Obtains an **Authenticator** object for user authentication.
+
+**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+**Return value**
+| Type | Description |
+| ----------------------------------------- | ------------ |
+| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.|
+
+**Example**
+ ```js
+ let authenticator = userIAM_userAuth.getAuthenticator();
+ ```
+
+## Authenticator(deprecated)
+
+> **NOTE**
+> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8).
+
+Provides methods to manage an **Authenticator** object.
+
+
+### execute(deprecated)
+
+execute(type: string, level: string, callback: AsyncCallback<number>): void
+
+> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
+
+Performs user authentication. This API uses asynchronous callback to return the result.
+
+**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
+| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
+| callback | AsyncCallback<number> | No | Callback used to return the result. |
+
+ Parameters returned in callback
+
+| Type | Description |
+| ------ | ------------------------------------------------------------ |
+| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
+
+**Example**
+ ```js
+ authenticator.execute("FACE_ONLY", "S2", (code)=>{
+ if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) {
+ console.info("auth success");
+ return;
+ }
+ console.error("auth fail, code = " + code);
+ })
+ ```
+
+
+### execute(deprecated)
+
+execute(type:string, level:string): Promise<number>
+
+> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8).
+
+Performs user authentication. This API uses a promise to return the result.
+
+**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+**Parameters**
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
+| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
+
+**Return value**
+| Type | Description |
+| --------------------- | ------------------------------------------------------------ |
+| Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
+
+**Example**
+
+```js
+let authenticator = userIAM_userAuth.getAuthenticator();
+authenticator.execute("FACE_ONLY", "S2").then((code)=>{
+ console.info("auth success");
+}).catch((code)=>{
+ console.error("auth fail, code = " + code);
+});
+```
+
+## AuthenticationResult(deprecated)
+
+> **NOTE**
+> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8).
+
+Enumerates the authentication results.
+
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
+
+| Name | Default Value| Description |
+| ------------------ | ------ | -------------------------- |
+| NO_SUPPORT | -1 | The device does not support the current authentication mode.|
+| SUCCESS | 0 | The authentication is successful. |
+| COMPARE_FAILURE | 1 | The feature comparison failed. |
+| CANCELED | 2 | The authentication was canceled by the user. |
+| TIMEOUT | 3 | The authentication has timed out. |
+| CAMERA_FAIL | 4 | The camera failed to start. |
+| BUSY | 5 | The authentication service is not available. Try again later. |
+| INVALID_PARAMETERS | 6 | The authentication parameters are invalid. |
+| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.|
+| NOT_ENROLLED | 8 | No authentication credential is registered. |
+| GENERAL_ERROR | 100 | Other errors. |
diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md
index a91577d272d67835ba1d7194200be508ed44a6ea..87cfad2f83ba3c25d4ab90a874777d86bb2cd473 100644
--- a/en/application-dev/reference/apis/js-apis-volumemanager.md
+++ b/en/application-dev/reference/apis/js-apis-volumemanager.md
@@ -191,20 +191,24 @@ Asynchronously obtains volume information based on the universally unique identi
**Parameters**
| 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.|
**Example**
```js
let uuid = "";
- let volume = await volumemanager.getVolumeByUuid(uuid);
+ volumemanager.getVolumeByUuid(uuid).then(function(volume) {
+ console.info("getVolumeByUuid successfully:" + JSON.stringify(volume));
+ }).catch(function(error){
+ console.info("getVolumeByUuid failed with error:"+ error);
+ });
```
## volumemanager.getVolumeByUuid
@@ -235,7 +239,7 @@ Asynchronously obtains volume information based on the UUID. This API uses a cal
## volumemanager.getVolumeById
-getVolumeById(id: string): Promise<Volume>
+getVolumeById(volumeId: string): Promise<Volume>
Asynchronously obtains volume information based on the volume ID. This API uses a promise to return the result.
@@ -247,7 +251,7 @@ Asynchronously obtains volume information based on the volume ID. This API uses
| Name | Type | Mandatory | Description|
| -------- | ------ | ---- | ---- |
- | id | string | Yes | Volume ID.|
+ | volumeId | string | Yes | Volume ID.|
**Return value**
@@ -258,13 +262,17 @@ Asynchronously obtains volume information based on the volume ID. This API uses
**Example**
```js
- let id = "";
- let volume = await volumemanager.getVolumeById(id);
+ let volumeId = "";
+ volumemanager.getVolumeById(volumeId).then(function(volume) {
+ console.info("getVolumeById successfully:" + JSON.stringify(volume));
+ }).catch(function(error){
+ console.info("getVolumeById failed with error:"+ error);
+ });
```
## volumemanager.getVolumeById
-getVolumeById(id: string, callback: AsyncCallback<Volume>): void
+getVolumeById(volumeId: string, callback: AsyncCallback<Volume>): void
Asynchronously obtains volume information based on the volume ID. This API uses a callback to return the result.
@@ -274,16 +282,16 @@ Asynchronously obtains volume information based on the volume ID. This API uses
**Parameters**
- | Name | Type | Mandatory| Description |
- | -------- | ------------------------------------------------ | ---- | -------------------- |
- | id | string | Yes | Volume ID. |
- | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.|
+ | Name | Type | Mandatory| Description |
+ | -------- | ------------------------- | ---- | ----------------------------- |
+ | volumeId | string | Yes | Volume ID. |
+ | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained. |
**Example**
```js
- let id = "";
- volumemanager.getVolumeById(id, (error, volume) => {
+ let volumeId = "";
+ volumemanager.getVolumeById(volumeId, (error, volume) => {
// Do something.
});
```
@@ -316,7 +324,11 @@ Asynchronously sets the volume description based on the UUID. This API uses a pr
```js
let uuid = "";
let description = "";
- let bool = await volumemanager.setVolumeDescription(uuid, description);
+ volumemanager.setVolumeDescription(uuid, description).then(function() {
+ console.info("setVolumeDescription successfully");
+ }).catch(function(error){
+ console.info("setVolumeDescription failed with error:"+ error);
+ });
```
## volumemanager.setVolumeDescription
@@ -349,7 +361,7 @@ Asynchronously sets the volume description based on the UUID. This API uses a ca
## volumemanager.format
-format(volId: string): Promise<void>
+format(volumeId: string, fsType: string): Promise<void>
Asynchronously formats a volume. This API uses a promise to return the result.
@@ -361,24 +373,30 @@ Asynchronously formats a volume. This API uses a promise to return the result.
| Name | Type | Mandatory| Description|
| ----------- | ------ | ---- | ---- |
- | volId | string | Yes | Volume ID.|
+ | volumeId | string | Yes | Volume ID.|
+ | fsType | string | Yes | File system type.|
**Return value**
- | Type | Description |
- | --------------------- | ----------------------- |
- | Promise<void> | Promise used to return the result. |
+ | Type | Description |
+ | ---------------------- | ---------- |
+ | Promise<void> | Promise used to return the result.|
**Example**
```js
- let volId = "";
- let bool = await volumemanager.format(volId);
+ let volumeId = "";
+ let fsType = "";
+ volumemanager.format(volumeId, fsType).then(function() {
+ console.info("format successfully");
+ }).catch(function(error){
+ console.info("format failed with error:"+ error);
+ });
```
## volumemanager.format
-format(volId: string, callback: AsyncCallback<void>): void
+format(volumeId: string, fsType: string, callback: AsyncCallback<void>): void
Asynchronously formats a volume. This API uses a callback to return the result.
@@ -388,23 +406,25 @@ Asynchronously formats a volume. This API uses a callback to return the result.
**Parameters**
- | Name | Type | Mandatory| Description |
- | -------- | --------------------------------------- | ---- | ---------------- |
- | volId | string | Yes | Volume ID. |
- | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result. |
+ | Name | Type | Mandatory| Description |
+ | -------- | ------------------------- | ---- | ----------------------------- |
+ | volumeId | string | Yes | Volume ID. |
+ | fsType | string | Yes | File system type.|
+ | callback | callback:AsyncCallback<void> | Yes | Called after the volume is formatted. |
**Example**
```js
- let volId = "";
- volumemanager.format(volId, (error, bool) => {
+ let volumeId = "";
+ let fsType = "";
+ volumemanager.format(volumeId, fsType, (error, bool) => {
// Do something.
});
```
## volumemanager.partition
-partition(volId: string, fstype: string): Promise<void>
+partition(diskId: string, type: number): Promise<void>
Asynchronously partitions a disk. This API uses a promise to return the result.
@@ -415,9 +435,9 @@ Asynchronously partitions a disk. This API uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory| Description|
- | ----------- | ------ | ---- | ---- |
- | volId | string | Yes | ID of the disk to which the volume belongs.|
- | fstype | string | Yes | Partition type. |
+ | ----------- | ------ | ---- | ---- |
+ | diskId | string | Yes | ID of the disk to which the volume belongs.|
+ | type | number | Yes | Partition type. |
**Return value**
@@ -428,14 +448,18 @@ Asynchronously partitions a disk. This API uses a promise to return the result.
**Example**
```js
- let volId = "";
- let fstype = "";
- let bool = await volumemanager.partition(volId, fstype);
+ let diskId = "";
+ let type = 0;
+ volumemanager.partition(diskId, type).then(function() {
+ console.info("partition successfully");
+ }).catch(function(error){
+ console.info("partition failed with error:"+ error);
+ });
```
## volumemanager.partition
-partition(volId: string, fstype : string, callback: AsyncCallback<void>): void
+partition(diskId: string, type: number, callback: AsyncCallback<void>): void
Asynchronously partitions a disk. This API uses a callback to return the result.
@@ -447,16 +471,16 @@ Asynchronously partitions a disk. This API uses a callback to return the result.
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------------- |
- | volId | string | Yes | ID of the disk to which the volume belongs. |
- | fstype | string | Yes | Partition type. |
+ | diskId | string | Yes | ID of the disk to which the volume belongs. |
+ | type | number | Yes | Partition type. |
| callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result. |
**Example**
```js
- let volId = "";
- let fstype = "";
- volumemanager.format(volId, fstype, (error, bool) => {
+ let diskId = "";
+ let type = 0;
+ volumemanager.partition(diskId, type, (error, bool) => {
// Do something.
});
```
@@ -471,6 +495,7 @@ Asynchronously partitions a disk. This API uses a callback to return the result.
| ----------- | ------- | -------------------- |
| id | string | Volume ID. |
| uuid | string | UUID of the volume. |
+| diskId | string | ID of the disk to which the volume belongs. |
| description | string | Description of the volume. |
| removable | boolean | Whether the volume is a removable storage device.|
| state | number | Volume state. |
diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md
index 75dda908af3e32140bf7c94b92ff73117be0ad7e..15fd2c4fcdeb681b4ace2dc49d521f54e08014f5 100644
--- a/en/application-dev/reference/apis/js-apis-wallpaper.md
+++ b/en/application-dev/reference/apis/js-apis-wallpaper.md
@@ -1,7 +1,9 @@
# Wallpaper
-> **NOTE**
The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
@@ -465,7 +467,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a
}).catch((error) => {
console.error(`failed to createPixelMap because: ` + JSON.stringify(error));
});
- ```
+```
## wallpaper.setWallpaper
@@ -520,7 +522,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr
}).catch((error) => {
console.error(`failed to createPixelMap because: ` + JSON.stringify(error));
});
- ```
+```
## wallpaper.getFile8+
@@ -528,7 +530,7 @@ getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): vo
Obtains the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.SET_WALLPAPER and ohos.permission.READ_USER_STORAGE
+**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE
**System capability**: SystemCapability.MiscServices.Wallpaper
@@ -557,7 +559,7 @@ getFile(wallpaperType: WallpaperType): Promise<number>
Obtains the wallpaper of the specified type. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.SET_WALLPAPER and ohos.permission.READ_USER_STORAGE
+**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE
**System capability**: SystemCapability.MiscServices.Wallpaper
@@ -636,7 +638,7 @@ Obtains the pixel image for the wallpaper of the specified type. This API uses a
**Example**
```js
- wallpaper.getPixelMap(WALLPAPER_SYSTEM).then((data) => {
+ wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data);
console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data));
}).catch((err) => {
@@ -695,9 +697,9 @@ Unsubscribes from the wallpaper color change event.
wallpaper.on('colorChange', listener);
// Unsubscribe from the listener.
wallpaper.off('colorChange', listener);
-//Unsubscribe from all subscriptions of the colorChange type.
+// Unsubscribe from all subscriptions of the colorChange type.
wallpaper.off('colorChange');
-```
+ ```
## RgbaColor
diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md
index a487890669ef23b80304bf82afff664a2008da05..ee169162cdeeeeb0be3c4c717d74d6bb231b74ff 100644
--- a/en/application-dev/reference/arkui-ts/Readme-EN.md
+++ b/en/application-dev/reference/arkui-ts/Readme-EN.md
@@ -127,7 +127,7 @@
- Canvas Components
- [Canvas](ts-components-canvas-canvas.md)
- [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md)
- - [OffscreenCanvasRenderingConxt2D](ts-offscreencanvasrenderingcontext2d.md)
+ - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md)
- [Lottie](ts-components-canvas-lottie.md)
- [Path2D](ts-components-canvas-path2d.md)
- [CanvasGradient](ts-components-canvas-canvasgradient.md)
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md
index 2758e99f0cdba7ed1a7722cd10a4ed6c68438466..a98e84fffd5816a22445daa66833cb47d0dbae88 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md
@@ -1,15 +1,15 @@
# Text
-> **NOTE**
-> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
-
-
The **\** component is used to display a piece of textual information.
+> **NOTE**
+>
+> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
+
## Required Permissions
-N/A
+None
## Child Components
@@ -32,8 +32,8 @@ Text(content?: string)
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| textAlign | TextAlign | TextAlign.Start | Text alignment mode of multiple lines of text.|
-| textOverflow | {overflow: TextOverflow} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.
**NOTE**
Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters. |
-| maxLines | number | Infinity | Maximum number of lines in the text.|
+| textOverflow | {overflow: TextOverflow} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.
**NOTE**
Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect.|
+| maxLines | number | Infinity | Maximum number of lines in the text.
**NOTE**
By default, text is automatically folded. If this parameter is specified, the text does not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode.|
| lineHeight | Length | - | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.|
| decoration | {
type: TextDecorationType,
color?: Color
} | {
type: TextDecorationType.None,
color: Color.Black
} | Style and color of the text decorative line.|
| baselineOffset | Length | - | Offset of the text baseline.|
@@ -78,7 +78,7 @@ Text(content?: string)
| LocalDevice | Intra-device copy and paste is allowed.|
| CrossDevice | Cross-device copy and paste is allowed.|
-> **NOTE**
+> **NOTE**
> If the **\** component contains both the text and the **\** child component, only the content in **\** is displayed.
diff --git a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md
index 082bfb57ec7ecd2d964c3e9cab1a75715d02c58a..d625528c2c4f1cd857ae04585201d5507bb70ff8 100644
--- a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md
+++ b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md
@@ -20,14 +20,14 @@ CanvasRenderingContext2D(setting: RenderingContextSetting)
### RenderingContextSettings
-RenderingContextSettings(antialias?: bool)
+RenderingContextSettings(antialias?: boolean)
Configures the settings of a **CanvasRenderingContext2D** object, including whether to enable antialiasing.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---- | --------- | ------------- | -------------------------------- |
- | antialias | bool | No | false | Whether antialiasing is enabled. |
+ | antialias | boolean | No | false | Whether antialiasing is enabled. |
## Attributes
diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md
index cc6e43dbc45b9c35dcda68aee838d64de2c60802..c520530cb00102c4d30eaf36d1f25b27c5bb968b 100644
--- a/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md
+++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md
@@ -1,17 +1,17 @@
# ImageBitmap
-> **NOTE**
+> **NOTE**
+>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
-**CanvasImageData** stores pixel data rendered on a canvas.
+An **ImageBitmap** object stores pixel data rendered on a canvas.
## Attributes
-| Name | Type | Description |
+| Name | Type | Description |
| -------- | -------- | -------- |
| width | number | Actual width of the rectangle on the canvas, in pixels. |
| height | number | Actual height of the rectangle on the canvas, in pixels. |
-| data | <Uint8ClampedArray> | A one-dimensional array of color values. The values range from 0 to 255. |
diff --git a/en/application-dev/reference/arkui-ts/ts-container-refresh.md b/en/application-dev/reference/arkui-ts/ts-container-refresh.md
index 2392680bc520832629d8763fb9eee5e28b946bf7..92aa736e68b028b7c188e12005badf7e967ab8ba 100644
--- a/en/application-dev/reference/arkui-ts/ts-container-refresh.md
+++ b/en/application-dev/reference/arkui-ts/ts-container-refresh.md
@@ -1,9 +1,10 @@
# Refresh
-> **NOTE**
-> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
+ The **\** component is a container that provides the pull-to-refresh feature.
-The **** component is used to refresh a page through a pull-down gesture.
+> **NOTE**
+>
+> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
@@ -19,11 +20,11 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number | stri
- Parameters
- | Name | Value Type | Mandatory | Default Value | Description |
+ | Name| Value Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
- | refreshing | boolean | Yes| - | Whether the current component is being refreshed. |
- | offset | Length | No| 16 | Distance to the top of the parent component from the **** component that comes to rest after a successful pull-down gesture. |
- | friction | number | No| 62 | Coefficient of friction, which indicates the **** component's sensitivity to the pull-down gesture. The value ranges from 0 to 100.
- **0**: The **** component is not sensitive to the pull-down gesture.
- **100**: The **** component is highly sensitive to the pull-down gesture.
- Value greater than **100**: The **** component is much more sensitive to the pull-down gesture. |
+ | refreshing | boolean | Yes| - | Whether the current component is being refreshed.|
+ | offset | Length | No| 16 | Distance to the top of the parent component from the **** component that comes to rest after a successful pull-down gesture.|
+ | friction | number \| string | No| 62 | Coefficient of friction, which indicates the **** component's sensitivity to the pull-down gesture. The value ranges from 0 to 100.
- **0** indicates that the **\** component is not sensitive to the pull-down gesture.
- **100** indicates that the **\** component is highly sensitive to the pull-down gesture.
- A larger value indicates a more sensitive response of the **\** component to the pull-down gesture.|
@@ -32,23 +33,24 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number | stri
| Name| Description|
| -------- | -------- |
-| onStateChange(callback: (state: RefreshStatus) => void)| Triggered when the refresh status changes.
**state** indicates the refresh status. |
-| onRefreshing(callback: () => void)| Triggered when the component enters the refresh state. |
+| onStateChange(callback: (state: RefreshStatus) => void)| Triggered when the refresh status changes.
**state**: refresh status.|
+| onRefreshing(callback: () => void)| Triggered when the component enters the refresh state.|
- RefreshStatus enums
- | Name | Description |
+ | Name| Description|
| -------- | -------- |
- | Inactive | The component is not pulled down. This is the default value. |
- | Drag | The component is being pulled down, but the pulled distance is shorter than the minimum length required to trigger the refresh. |
- | OverDrag | The component is being pulled down, and the pulled distance exceeds the minimum length required to trigger the refresh. |
- | Refresh | The pull-down ends, and the component rebounds to the minimum length required to trigger the refresh and enters the refresh state. |
- | Done | The refresh is complete, and the component returns to the initial state (top). |
+ | Inactive | The component is not pulled down. This is the default value.|
+ | Drag | The component is being pulled down, but the pulled distance is shorter than the minimum length required to trigger the refresh.|
+ | OverDrag | The component is being pulled down, and the pulled distance exceeds the minimum length required to trigger the refresh.|
+ | Refresh | The pull-down ends, and the component rebounds to the minimum length required to trigger the refresh and enters the refresh state.|
+ | Done | The refresh is complete, and the component returns to the initial state (top).|
## Example
-```
+```ts
+// xxx.ets
@Entry
@Component
struct RefreshExample {
diff --git a/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md b/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md
index 67d034e063b70c2447d488356a8b75094e516426..410181d6801fb0a478419b90f7c5e3659ab5715a 100644
--- a/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md
+++ b/en/application-dev/reference/arkui-ts/ts-motion-path-animation.md
@@ -1,12 +1,12 @@
# Motion Path Animation
+You can apply a motion path animation to a component, by setting the motion path of the component in a translation animation.
> **NOTE**
>
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
-The attributes below can be used to set the motion path of the component in a translation animation.
## Attributes
@@ -19,7 +19,8 @@ The attributes below can be used to set the motion path of the component in a tr
## Example
-```
+```ts
+// xxx.ets
@Entry
@Component
struct MotionPathExample {
diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md
index 4e27ab2eb1aaf983c0128787925377339d67ad3e..d049ce9afe2f55887fd50d445ae950f14850f200 100644
--- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md
+++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md
@@ -1,8 +1,10 @@
# Component ID
+**id** identifies a component uniquely within an application. This module provides APIs for obtaining the attributes of or sending events to the component with the specified ID.
->  **NOTE**
-> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
+> **NOTE**
+>
+> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
@@ -12,93 +14,250 @@ None
## Attributes
- | Name | Type | Default Value | Description |
+| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
-| id | string | '' | Unique ID of the component. The uniqueness is ensured by the user. |
+| id | string | '' | Unique ID you assigned to the component.|
## APIs
-### getInspectorByKey
+### getInspectorByKey9+
getInspectorByKey(id: string): string
Obtains all attributes of the component with the specified ID, excluding the information about child components.
- Parameters
- | Name | Type | Mandatory | Default Value | Description |
+ | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
- | id | string | Yes | - | ID of the component whose attributes are to be obtained. |
+ | id | string | Yes| - | ID of the component whose attributes are to be obtained.|
- Return value
- | Type | Description |
+ | Type| Description|
| -------- | -------- |
- | string | JSON string of the component attribute list. |
+ | string | JSON string of the component attribute list.|
+### getInspectorTree9+
-### sendEventByKey
+getInspectorTree(): string
+
+Obtains the component tree and component attributes.
+
+- Return value
+
+ | Type | Description |
+ | ------ | ---------------------------------- |
+ | string | JSON string of the component tree and component attribute list.|
+
+### sendEventByKey9+
sendEventByKey(id: string, action: number, params: string): boolean
Sends an event to the component with the specified ID.
- Parameters
- | Name | Type | Mandatory | Default Value | Description |
+ | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
- | id | string | Yes | - | ID of the component for which the event is to be sent. |
- | action | number | Yes | - | Type of the event to be sent. The options are as follows:
- Click event: 10.
- LongClick: 11. |
- | params | string | Yes | - | Event parameters. If there is no parameter, pass an empty string **""**. |
+ | id | string | Yes| - | ID of the component to which the event is to be sent.|
+ | action | number | Yes| - | Type of the event to be sent. The options are as follows:
- **10**: click event.
- **11**: long-click event.|
+ | params | string | Yes| - | Event parameters. If there is no parameter, pass an empty string **""**.|
- Return value
- | Type | Description |
+ | Type| Description|
| -------- | -------- |
- | boolean | Returns **false** if the component with the specified ID cannot be found; returns **true** otherwise. |
+ | boolean | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
+
+### sendTouchEvent9+
+
+sendTouchEvent(event: TouchObject): boolean
+
+Sends a touch event.
+
+- Parameters
+
+ | Name | Type | Mandatory| Default Value| Description |
+ | ----- | ----------- | ---- | ------ | ------------------------------------------------------------ |
+ | event | TouchObject | Yes | - | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
+
+- Return value
+
+ | Type | Description |
+ | ------- | ------------------------------------------- |
+ | boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
+
+### sendKeyEvent9+
+
+sendKeyEvent(event: KeyEvent): boolean
+
+Sends a key event.
+
+- Parameters
+
+ | Name | Type | Mandatory| Default Value| Description |
+ | ----- | -------- | ---- | ------ | ------------------------------------------------------------ |
+ | event | KeyEvent | Yes | - | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
+
+- Return value
+
+ | Type | Description |
+ | ------- | --------------------------------------------- |
+ | boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
+
+### sendMouseEvent9+
+
+sendMouseEvent(event: MouseEvent): boolean
+
+Sends a mouse event.
+
+- Parameters
+
+ | Name | Type | Mandatory| Default Value| Description |
+ | ----- | ---------- | ---- | ------ | ------------------------------------------------------------ |
+ | event | MouseEvent | Yes | - | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
+
+- Return value
+ | Type | Description |
+ | ------- | --------------------------------------------- |
+ | boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
## Example
-
-```
+```ts
+// xxx.ets
+class Utils {
+ static rect_left;
+ static rect_top;
+ static rect_right;
+ static rect_bottom;
+ static rect_value;
+
+ static getComponentRect(key) {
+ let strJson = getInspectorByKey(key);
+ let obj = JSON.parse(strJson);
+ console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj));
+ let rectInfo = JSON.parse('[' + obj.$rect + ']')
+ console.info("[getInspectorByKey] rectInfo is: " + rectInfo);
+ this.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0]
+ this.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1]
+ this.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0]
+ this.rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1]
+ return this.rect_value = {
+ "left": this.rect_left, "top": this.rect_top, "right": this.rect_right, "bottom": this.rect_bottom
+ }
+ }
+}
+
@Entry
@Component
struct IdExample {
+ @State text: string = ''
+
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+
Button() {
- Text('click')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }
- .type(ButtonType.Capsule)
- .margin({
- top: 20
- }).onClick(() => {
+ Text('onKeyTab').fontSize(25).fontWeight(FontWeight.Bold)
+ }.margin({ top: 20 }).backgroundColor('#0D9FFB')
+ .onKeyEvent(() => {
+ this.text = "onKeyTab"
+ })
+
+ Button() {
+ Text('click to start').fontSize(25).fontWeight(FontWeight.Bold)
+ }.margin({ top: 20 })
+ .onClick(() => {
console.info(getInspectorByKey("click"))
console.info(getInspectorTree())
+ this.text = "Button 'click to start' is clicked"
setTimeout(() => {
- sendEventByKey("longclick", 11, "")
+ sendEventByKey("longClick", 11, "")
}, 2000)
}).id('click')
Button() {
- Text('longclick')
- .fontSize(25)
- .fontWeight(FontWeight.Bold)
- }
- .type(ButtonType.Capsule)
- .margin({
- top: 20
- })
- .backgroundColor('#0D9FFB')
+ Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
+ }.margin({ top: 20 }).backgroundColor('#0D9FFB')
.gesture(
- LongPressGesture().onActionEnd(() => {
- console.info('long clicked')
- }))
- .id('longclick')
+ LongPressGesture().onActionEnd(() => {
+ console.info('long clicked')
+ this.text = "Button 'longClick' is longclicked"
+ setTimeout(() => {
+ let rect = Utils.getComponentRect('onTouch')
+ let touchPoint: TouchObject = {
+ id: 1,
+ x: rect.left + (rect.right - rect.left) / 2,
+ y: rect.top + (rect.bottom - rect.top) / 2,
+ type: TouchType.Down,
+ screenX: rect.left + (rect.right - rect.left) / 2,
+ screenY: rect.left + (rect.right - rect.left) / 2,
+ }
+ sendTouchEvent(touchPoint)
+ touchPoint.type = TouchType.Up
+ sendTouchEvent(touchPoint)
+ }, 2000)
+ })).id('longClick')
+
+ Button() {
+ Text('onTouch').fontSize(25).fontWeight(FontWeight.Bold)
+ }.type(ButtonType.Capsule).margin({ top: 20 })
+ .onClick(() => {
+ console.info('onTouch is clicked')
+ this.text = "Button 'onTouch' is clicked"
+ setTimeout(() => {
+ let rect = Utils.getComponentRect('onMouse')
+ let mouseEvent: MouseEvent = {
+ button: MouseButton.Left,
+ action: MouseAction.Press,
+ x: rect.left + (rect.right - rect.left) / 2,
+ y: rect.top + (rect.bottom - rect.top) / 2,
+ screenX: rect.left + (rect.right - rect.left) / 2,
+ screenY: rect.top + (rect.bottom - rect.top) / 2,
+ timestamp: 1,
+ target: {
+ area: {
+ width: 1,
+ height: 1,
+ position: {
+ x: 1,
+ y: 1
+ },
+ globalPosition: {
+ x: 1,
+ y: 1
+ }
+ }
+ },
+ source: SourceType.Mouse
+ }
+ sendMouseEvent(mouseEvent)
+ }, 2000)
+ }).id('onTouch')
+
+ Button() {
+ Text('onMouse').fontSize(25).fontWeight(FontWeight.Bold)
+ }.margin({ top: 20 }).backgroundColor('#0D9FFB')
+ .onMouse(() => {
+ console.info('onMouse')
+ this.text = "Button 'onMouse' in onMouse"
+ setTimeout(() => {
+ let keyEvent: KeyEvent = {
+ type: KeyType.Down,
+ keyCode: 2049,
+ keyText: 'tab',
+ keySource: 4,
+ deviceId: 0,
+ metaKey: 0,
+ timestamp: 0
+ }
+ sendKeyEvent(keyEvent)
+ }, 2000)
+ }).id('onMouse')
+
+ Text(this.text).fontSize(25).padding(15)
}
- .width('100%')
- .height('100%')
+ .width('100%').height('100%')
}
}
```
diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md
index 9d801b2503cc4225907879d5eba7596c120db3b6..5be81d94fdc351f56722eb6a106ca5c0157b658e 100644
--- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md
+++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md
@@ -1,8 +1,10 @@
# Popup Control
+The popup attribute defines the popup displayed when a component is clicked.
->  **NOTE**
-> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
+> **NOTE**
+>
+> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
@@ -13,48 +15,52 @@ None
## Attributes
-| Name | Type | Default Value | Description |
+| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
-| bindPopup | show: boolean,
popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the current popup. |
+| bindPopup | show: boolean,
popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the popup.|
-- PopupOptions attributes
- | Name | Type | Mandatory | Default Value | Description |
+- PopupOptions
+ | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
- | message | string | Yes | - | Content of the popup message. |
- | placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. |
- | primaryButton | {
value: string,
action: () => void
} | No | - | First button.
**value**: text of the primary button in the popup.
**action**: callback function for clicking the primary button. |
- | secondaryButton | {
value: string,
action: () => void
} | No | - | Second button.
**value**: text of the secondary button in the popup.
**action**: callback function for clicking the secondary button. |
- | onStateChange | (isVisible: boolean) => void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
+ | message | string | Yes| - | Content of the popup message.|
+ | placementOnTop | boolean | No| false | Whether to display the popup above the component. The default value is **false**.|
+ | primaryButton | {
value: string,
action: () => void
} | No| - | Primary button.
**value**: text of the primary button in the popup.
**action**: callback for clicking the primary button.|
+ | secondaryButton | {
value: string,
action: () => void
} | No| - | Secondary button.
**value**: text of the secondary button in the popup.
**action**: callback for clicking the secondary button.|
+ | onStateChange | (isVisible: boolean) => void | No| - | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.|
- CustomPopupOptions8+
- | Name | Type | Mandatory | Default Value | Description |
+ | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
- | builder | () => any | Yes | - | Builder of the tooltip content. |
- | placement | Placement | No | Placement.Bottom | Preferred position of the tooltip component. If the set position is insufficient for holding the component, it will be automatically adjusted. |
- | maskColor | [Color](../../ui/ts-types.md) | No | - | Color of the tooltip mask. |
- | popupColor | [Color](../../ui/ts-types.md) | No | - | Color of the tooltip. |
- | enableArrow | boolean | No | true | Whether to display arrows. Arrows are displayed only for tooltips in the up and down directions. |
- | autoCancel | boolean | No | true | Whether to automatically close the tooltip when an operation is performed on the page. |
- | onStateChange | (isVisible: boolean) => void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
+ | builder | () => any | Yes| - | Builder of the popup content.|
+ | placement | Placement | No| Placement.Bottom | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.|
+ | maskColor | [ResourceColor](../../ui/ts-types.md) | No| - | Color of the popup mask.|
+ | popupColor | [ResourceColor](../../ui/ts-types.md) | No| - | Color of the popup.|
+ | enableArrow | boolean | No| true | Whether to display an arrow.
Since API version 9, if the location set for the arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.|
+ | autoCancel | boolean | No| true | Whether to automatically close the popup when an operation is performed on the page.|
+ | onStateChange | (isVisible: boolean) => void | No| - | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.|
- Placement8+ enums
- | Name | Description |
+ | Name| Description|
| -------- | -------- |
- | Left | The tooltip is on the left of the component. |
- | Right | The tooltip is on the right of the component. |
- | Top | The tooltip is on the top of the component. |
- | Bottom | The tooltip is at the bottom of the component. |
- | TopLeft | The tooltip is in the upper left corner of the component. |
- | TopRight | The tooltip is in the upper right corner of the component. |
- | BottomLeft | The tooltip is in the lower left corner of the component. |
- | BottomRight | The tooltip is in the lower right corner of the component. |
+ | Left | The popup is on the left of the component, vertically aligned with the component on the left.|
+ | Right | The popup is on the right of the component, vertically aligned with the component on the right.|
+ | Top | The popup is at the top of the component, horizontally aligned with the component at the top.|
+ | Bottom | The popup is at the bottom of the component, horizontally aligned with the component at the bottom.|
+ | TopLeft | The popup is at the top of the component and, since API version 9, aligned with the left of the component.|
+ | TopRight | The popup is at the top of the component and, since API version 9, aligned with the right of the component.|
+ | BottomLeft | The popup is at the bottom of the component and, since API version 9, aligned with the left of the component.|
+ | BottomRight | The popup is at the bottom of the component and, since API version 9, aligned with the right of the component.|
+ | LeftTop9+ | The popup is on the left of the component and aligned with the top of the component.|
+ | LeftBottom9+ | The popup is on the left of the component and aligned with the bottom of the component.|
+ | RightTop9+ | The popup is on the right of the component and aligned with the top of the component.|
+ | RightBottom9+ | The popup is on the right of the component and aligned with the bottom of the component.|
## Example
-
-```
+```ts
+// xxx.ets
@Entry
@Component
struct PopupExample {
@@ -65,7 +71,7 @@ struct PopupExample {
@Builder popupBuilder() {
Row({ space: 2 }) {
Image('/resource/ic_public_thumbsup.svg').width(24).height(24).margin({ left: -5 })
- Text('Custom Popup').fontSize(12)
+ Text('Custom Popup').fontSize(10)
}.width(100).height(50).backgroundColor(Color.White)
}
diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md
index 2e706b7617e79deb17393ebd3ac1a86e42374e80..f6ef8fc8ba202071cfa01c1f559e35d4654e5230 100644
--- a/en/application-dev/security/accesstoken-guidelines.md
+++ b/en/application-dev/security/accesstoken-guidelines.md
@@ -24,13 +24,13 @@ The table below lists only the API used in this guide. For more information, see
## Declaring Permissions
-Declare the permissions required by the app one by one in the project configuration file. The app cannot obtain the permissions that are not declared in the configuration file. The ability framework provides two models: Feature Ability (FA) model and Stage model. For more information, see [Ability Framework Overview](../ability/ability-brief.md).
+Declare the permissions required by the app one by one in the project configuration file. The app cannot obtain the permissions that are not declared in the configuration file. The ability framework provides two models: Feature Ability (FA) model and stage model. For more information, see [Ability Framework Overview](../ability/ability-brief.md).
Note that the app bundle structure and configuration file vary with the ability framework model.
### FA Model
-For the apps based on the FA model, declare the permissions in the **config.json** file.
+For the apps based on the FA model, declare the required permissions in the **config.json** file.
**Description of config.json**
@@ -75,7 +75,7 @@ For the apps based on the FA model, declare the permissions in the **config.json
### Stage Model
-For the apps based on the stage model, declare the permissions in the **module.json5** file.
+For the apps based on the stage model, declare the required permissions in the **module.json5** file.
**Example**
diff --git a/en/application-dev/security/hapsigntool-guidelines.md b/en/application-dev/security/hapsigntool-guidelines.md
index cccb231fef257d05f7e818886c97f57dbfb0878d..f161b4fc7292d5a0a29b37da8aa2119db9f9be00 100644
--- a/en/application-dev/security/hapsigntool-guidelines.md
+++ b/en/application-dev/security/hapsigntool-guidelines.md
@@ -104,7 +104,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -issuerKeyPwd # Key password of the issuer. It is optional.
├── -subject # Certificate subject. It is mandatory.
├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days.
- ├── -signAlg # Signature algoritym, which can be SHA256withECDSA or SHA384withECDSA.
+ ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA.
├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional.
├── -issuerKeystorePwd # KS password of the issuer. It is optional.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory.
@@ -126,7 +126,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -issuerKeyPwd # Key password of the issuer. It is optional.
├── -subject # Certificate subject. It is mandatory.
├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days.
- ├── -signAlg # Signature algoritym, which can be SHA256withECDSA or SHA384withECDSA.
+ ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA.
├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional.
├── -issuerKeystorePwd # KS password of the issuer. It is optional.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory.
diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md
index 179073eec8928e709c45fc558344a1fef6898085..9578c8d43b2a216171ec36c2f5056600d4e3ab9f 100644
--- a/en/application-dev/security/permission-list.md
+++ b/en/application-dev/security/permission-list.md
@@ -97,7 +97,7 @@ For details about permission usage examples, see [Access Control Development](ac
| ohos.permission.EDM_MANAGE_DATETIME | normal | system_grant | FALSE | Allows the device administrator app to set the system time. |
| ohos.permission.NFC_TAG | normal | system_grant | FALSE | Allows an app to read NFC tag information. |
| ohos.permission.NFC_CARD_EMULATION | normal | system_grant | FALSE | Allows an app to implement card emulation. |
-| ohos.permission.PERMISSION_USED_STATS | system_core | system_grant | TRUE | Allows a system application to access the permission usage records. |
+| ohos.permission.PERMISSION_USED_STATS | system_basic | system_grant | TRUE | Allows a system application to access the permission usage records. |
| ohos.permission.NOTIFICATION_AGENT_CONTROLLER | system_core | system_grant | TRUE | Allows an app to send agent-powered notifications. |
| ohos.permission.ANSWER_CALL | system_basic | user_grant | TRUE | Allows an app to answer incoming calls. |
| ohos.permission.READ_CALENDAR | normal | user_grant | TRUE | Allows an app to read calendar data. |
@@ -129,3 +129,5 @@ For details about permission usage examples, see [Access Control Development](ac
| ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | Allows an app to query the unique identifier of a device. |
| ohos.permission.DUMP | system_core | system_grant | TRUE | Allows the basic system information and SA service information to be exported. |
| ohos.permission.DISTRIBUTED_SOFTBUS_CENTER | system_basic | system_grant | FALSE | Allows networking between different devices. |
+| ohos.permission.ACCESS_DLP_FILE | system_core | system_grant | TRUE | Allows configuration and management of the permissions on .dlp files. |
+| ohos.permission.PROVISIONING_MESSAGE | system_core | system_grant | TRUE | Allows activiation of the Super Device Manager application. |
diff --git a/en/application-dev/ui/ts-component-based-builder.md b/en/application-dev/ui/ts-component-based-builder.md
index a07b244ffdc2bd9105102058e6881b14289fdf34..d626bde6074c5e3db373a00f3a78bf6e554cf46f 100644
--- a/en/application-dev/ui/ts-component-based-builder.md
+++ b/en/application-dev/ui/ts-component-based-builder.md
@@ -4,16 +4,17 @@
The **@Builder** decorated method is used to define the declarative UI description of a component and quickly generate multiple layouts in a custom component. The functionality and syntax of the **@Builder** decorator are the same as those of the [build Function](ts-function-build.md).
-```
+```ts
+// xxx.ets
@Entry
@Component
struct CompA {
- size : number = 100;
+ size1 : number = 100;
@Builder SquareText(label: string) {
Text(label)
- .width(1 * this.size)
- .height(1 * this.size)
+ .width(1 * this.size1)
+ .height(1 * this.size1)
}
@Builder RowOfSquareTexts(label1: string, label2: string) {
@@ -21,8 +22,8 @@ struct CompA {
this.SquareText(label1)
this.SquareText(label2)
}
- .width(2 * this.size)
- .height(1 * this.size)
+ .width(2 * this.size1)
+ .height(1 * this.size1)
}
build() {
@@ -32,12 +33,12 @@ struct CompA {
this.SquareText("B")
// or as long as tsc is used
}
- .width(2 * this.size)
- .height(1 * this.size)
+ .width(2 * this.size1)
+ .height(1 * this.size1)
this.RowOfSquareTexts("C", "D")
}
- .width(2 * this.size)
- .height(2 * this.size)
+ .width(2 * this.size1)
+ .height(2 * this.size1)
}
}
```
@@ -51,7 +52,8 @@ In certain circumstances, you may need to add a specific function, such as a cli
### Component Initialization Through Parameters
When initializing a custom component through parameters, assign a **@Builder** decorated method to the **@BuilderParam** decorated attribute — **content**, and call the value of **content** in the custom component. If no parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, `content: this.specificParam`), define the type of the attribute as a function without a return value (for example, `@BuilderParam content: () => void`). If any parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, `callContent: this.specificParam1("111")`), define the type of the attribute as `any` (for example,`@BuilderParam callContent: any;`).
-```
+```ts
+// xxx.ets
@Component
struct CustomContainer {
header: string = "";
@@ -100,7 +102,8 @@ struct CustomContainerUser {
In a custom component, use the **@BuilderParam** decorated attribute to receive a trailing closure. When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (`CustomComponent(){}`). You can consider a trailing closure as a container and add content to it. For example, you can add a component (`{Column(){Text("content")}`) to a trailing closure. The syntax of the closure is the same as that of [build](../ui/ts-function-build.md). In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute.
Example: Add a **\** component and a click event to the closure, and call the **specificParam** method decorated by **@Builder** in the new **\** component. After the **\** component is clicked, the value of the component's `header` attribute will change to `changeHeader`. In addition, when the component is initialized, the content of the trailing closure will be assigned to the `closer` attribute decorated by **@BuilderParam**.
-```
+```ts
+// xxx.ets
@Component
struct CustomContainer {
header: string = "";
diff --git a/en/application-dev/ui/ts-custom-component-initialization.md b/en/application-dev/ui/ts-custom-component-initialization.md
index 2dcb83e536762e8ca424a346c1132bcc2380fefd..9c68e81b41aeac32ff00f545a70df3f69c64fcd4 100644
--- a/en/application-dev/ui/ts-custom-component-initialization.md
+++ b/en/application-dev/ui/ts-custom-component-initialization.md
@@ -6,14 +6,14 @@ The member variables of a component can be initialized in either of the followin
- Local initialization. For example:
- ```
+ ```ts
@State counter: Counter = new Counter()
```
- Initialization using constructor parameters. For example:
- ```
- MyComponent(counter: $myCounter)
+ ```ts
+ MyComponent({counter: $myCounter})
```
@@ -73,43 +73,57 @@ As indicated by the preceding table:
## Example
-```
+```ts
+// xxx.ets
+class ClassA {
+ public a:number
+ constructor(a: number) {
+ this.a = a
+ }
+}
@Entry
@Component
struct Parent {
- @State parentState: ClassA = new ClassA()
- build() {
- Row() {
- CompA({aState: new ClassA, aLink: $parentState}) // valid
- CompA({aLink: $parentState}) // valid
- CompA() // invalid, @Link aLink remains uninitialized
- CompA({aLink: new ClassA}) // invalid, @Link aLink must be a reference ($) to either @State or @Link variable
- }
+ @State parentState: ClassA = new ClassA(1)
+
+ build() {
+ Column() {
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ CompA({ aState: new ClassA(2), aLink: $parentState })
+ }
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ CompA({ aLink: $parentState })
+ }
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ CompA({ aState: new ClassA(3), aLink: $parentState })
+ }
}
+ }
}
@Component
struct CompA {
- @State aState: boolean = false // must initialize locally
- @Link aLink: ClassA // must not initialize locally
-
- build() {
- Row() {
- CompB({bLink: $aLink, // valid init a @Link with reference of another @Link,
- bProp: this.aState}) // valid init a @Prop with value of a @State
- CompB({aLink: $aState, // invalid: type mismatch expected ref to ClassA, provided reference to boolean
- bProp: false}) // valid init a @Prop by constants value
- }
+ @State aState: any = false
+ @Link aLink: ClassA
+
+ build() {
+ Column() {
+ CompB({ bLink: $aLink, bProp: this.aState })
+ CompB({ bLink: $aState, bProp: false })
}
+ }
}
@Component
struct CompB {
- @Link bLink: ClassA = new ClassA() // invalid, must not initialize locally
- @Prop bProp: boolean = false // invalid must not initialize locally
-
- build() {
- ...
- }
+ @Link bLink: ClassA
+ @Prop bProp: boolean
+
+ build() {
+ Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
+ Text(JSON.stringify(this.bLink.a)).fontSize(30)
+ Text(JSON.stringify(this.bProp)).fontSize(30).fontColor(Color.Red)
+ }.margin(10)
+ }
}
```
diff --git a/en/application-dev/ui/ui-ts-creating-simple-page.md b/en/application-dev/ui/ui-ts-creating-simple-page.md
index 4e9ee4b92152eade3066c4a79cb328cf8b998a57..6c934f4c56b2c66f59d746fc1752e4acf24131bf 100644
--- a/en/application-dev/ui/ui-ts-creating-simple-page.md
+++ b/en/application-dev/ui/ui-ts-creating-simple-page.md
@@ -7,7 +7,8 @@ In this section, we will develop an infographic food details page, by building c
## Building the Stack Layout
1. Create a food name.
- Delete the code of the build method in the project template, create a <Stack> component, and place the **\** component in the braces of the **\** component so that the <Text> component becomes a child component of the <Stack> component. A **\** component consists of one or more child components. The latter child component overwrites the former one.
+
+ Delete the code of the **build** method in the project template, create a **\** component, and place the **\** component in the braces of the **\** component. When the **\** component contains multiple child components, the latter child component overwrites the former one.
```
@Entry
@@ -23,10 +24,11 @@ In this section, we will develop an infographic food details page, by building c
}
```
- 
+
2. Display food pictures.
- Create an **\** component and specify a URL for it. The **\** and **\** components are mandatory. To display the **\** component above the **\** component, you need to declare the **\** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where filename indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\** component to reference image resources.
+
+ Create an **\** component and specify a URL for it. The **\** and **\** components are mandatory. To display the **\** component above the **\** component, you need to declare the **\** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\** component to reference image resources.
```
@Entry
@@ -46,9 +48,10 @@ In this section, we will develop an infographic food details page, by building c

3. Access images through resources.
- In addition to specifying the image path, you can also use the media resource symbol $r to reference resources based on the resource qualifier rules in the resources folder. Right-click the resources folder, choose **New** > **Resource Directory**, and set **Resource Type** to **Media (image resource)**. Place Tomato.png in the media folder.
- You can then can reference the application resource in the ` "$r('app.type.name')"` format, that is, `$r('app.media.Tomato')`.
+ In addition to specifying the image path, you can also use the media resource symbol `$r` to reference resources in the **resources** folder based on the resource qualifier rules. Right-click the **resources** folder, choose **New** > **Resource Directory**, and set **Resource Type** to **Media (image resource)**.
+
+ Place **Tomato.png** in the **media** folder. You can then can reference the application resource in the `$r('app.type.name')` format, that is, `$r('app.media.Tomato')`.
```
@@ -68,30 +71,31 @@ In this section, we will develop an infographic food details page, by building c
}
```
-4. Set the width and height of the image, and set the objectFit attribute of the image to ImageFit.Contain, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary.If the image fills the entire screen, the possible causes are as follows:
+4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary. If the image fills the entire screen, the possible causes are as follows:
+
1. The width and height of the image are not set.
2. The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked.
-
- ```
- @Entry
- @Component
- struct MyComponent {
- build() {
- Stack() {
- Image($r('app.media.Tomato'))
- .objectFit(ImageFit.Contain)
- .height(357)
- Text('Tomato')
- .fontSize(26)
- .fontWeight(500)
+
+ ```
+ @Entry
+ @Component
+ struct MyComponent {
+ build() {
+ Stack() {
+ Image($r('app.media.Tomato'))
+ .objectFit(ImageFit.Contain)
+ .height(357)
+ Text('Tomato')
+ .fontSize(26)
+ .fontWeight(500)
+ }
}
}
- }
- ```
+ ```

-5. Set the food image and name layout. Set the alignment mode of the stack to bottom alignment. By default, the stack is center aligned. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
+5. Set the food image and name layout. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
```
@Entry
@@ -112,9 +116,9 @@ In this section, we will develop an infographic food details page, by building c

-6. You can change the background color of the food image by setting the background color of the stack. You can set the background color in either of the following ways:
- 1. By using the built-in enumeration value of Color provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
- 2. By using the parameter of the string type. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**.
+6. You can change the background color of the food image by setting the background color of the **\** component in either of the following ways:
+ 1. Using the built-in **Color** enums provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
+ 2. Using the string-type parameter. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**.
```
@@ -163,7 +167,7 @@ In this section, we will develop an infographic food details page, by building c

-8. Adjust the structure between components and semanticize component names. Create the FoodDetail page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
+8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set.
@@ -202,7 +206,7 @@ In this section, we will develop an infographic food details page, by building c
You can use the Flex layout to build a food composition table. In this way you do not need to worry about the width and height calculation. The size of different cells can be flexibly set based on the proportion.
-1. Create a **ContentTable** component as a child component of the FoodDetail component.
+1. Create a **ContentTable** component as a child component of the **FoodDetail** component.
```
@Component
@@ -239,13 +243,13 @@ You can use the Flex layout to build a food composition table. In this way you d
}
```
-2. Create a Flex component to display two food composition categories in the tomato: Calories and Nutrition.
+2. Create a Flex component to display two food composition categories in the tomato: **Calories** and **Nutrition**.
-Calories contains information about calories. Nutrition contains information about protein, fat, carbohydrates, and vitamin C.
+ **Calories** contains information about calories. **Nutrition** contains information about protein, fat, carbohydrates, and vitamin C.
-Create the Calories class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three Text child components, which represent the category name (Calories), content name (Calories), and contain value (17 kcal), respectively. By default, child components in the Flex component are arranged horizontally.
+ Create the **Calories** class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three **\** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the Flex component are arranged horizontally.
- In the following example, code of FoodImageDisplay is omitted, and only code of ContentTable is provided.
+ In the following example, code of **FoodImageDisplay** is omitted, and only code of **ContentTable** is provided.
```
@@ -281,14 +285,14 @@ Create the Calories class. Create a Flex component and set its height to 280, an

-3. Adjust the layout and set the proportion (layoutWeight) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space flexGrow(1).
+3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space **flexGrow(1)**.
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
- Image($m('Tomato.png'))
+ Image($r('app.media.Tomato'))
.objectFit(ImageFit.Contain)
.height(357)
Text('Tomato')
@@ -337,7 +341,7 @@ Create the Calories class. Create a Flex component and set its height to 280, an

-4. Create the **Nutrient** class in a similar process. Nutrition consists of four parts: Protein, Fat, Carbohydrates, and VitaminC. The names of the last three parts are omitted in the table and represented by spaces.
+4. Create the **Nutrient** class in a similar process. **Nutrition** consists of four parts: **Protein**, **Fat**, **Carbohydrates**, and **VitaminC**. The names of the last three parts are omitted in the table and represented by spaces.
Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**.
@@ -442,7 +446,7 @@ Create the Calories class. Create a Flex component and set its height to 280, an
Currently, all food groups are declared, resulting in code duplication and redundancy. You can use @Builder to build a custom method and abstract the same UI structure declaration. The @Builder decorated method and the build method for the @Component decorated component are used to declare some UI rendering structures and comply with the same eTS syntax. You can define one or more methods decorated by @Builder, but a component decorated by @Component can have only one build method.
- Declare the IngredientItem method decorated by @Builder in ContentTable to declare the UI descriptions for the category name, content name, and content value.
+ Declare the **IngredientItem** method decorated by @Builder in **ContentTable** to declare the UI descriptions for the category name, content name, and content value.
```
@@ -455,9 +459,6 @@ Create the Calories class. Create a Flex component and set its height to 280, an
.fontWeight(FontWeight.Bold)
.layoutWeight(1)
Flex({ alignItems: ItemAlign.Center }) {
- Circle({width: 6, height: 6})
- .margin({right: 12})
- .fill(colorValue)
Text(name)
.fontSize(17.4)
.flexGrow(1)
@@ -470,7 +471,7 @@ Create the Calories class. Create a Flex component and set its height to 280, an
}
```
-When the ` IngredientItem` API is called in the build method of ContentTable, ` this ` needs to be used to invoke the method in the scope of the component to distinguish the global method call.
+ When the `IngredientItem` API is called in the **build** method of **ContentTable**, `this` needs to be used to invoke the method in the scope of the component to distinguish the global method call.
```
@@ -491,7 +492,7 @@ When the ` IngredientItem` API is called in the build method of ContentTable,
}
```
-The overall code of the ContentTable component is as follows:
+ The overall code of the **ContentTable** component is as follows:
```
diff --git a/en/contribute/documentation-contribution.md b/en/contribute/documentation-contribution.md
index 8a5eb74e52b929e155418875cef25dfde9ebdc15..430587fe0ffa3386cf17d64f49af4f9d7f1e2bd4 100755
--- a/en/contribute/documentation-contribution.md
+++ b/en/contribute/documentation-contribution.md
@@ -17,7 +17,7 @@ OpenHarmony has the right to modify the adopted content according to the communi
[Creative Commons License version 4.0](https://creativecommons.org/licenses/by/4.0/legalcode)
-## Contribution Methods
+## Contribution Methods
### Submitting Issues for Existing Documents
@@ -65,7 +65,7 @@ You are welcome to contribute documents to the release. For details, see [Writin
You are welcome to share your experience and expertise with other developers to help them get started. For example, you can contribute tutorials and FAQs by using the following templates:
-- [Tutorial Template](template/tutorial-template.md). You can contribute tutorials in the `contribute/tutorial` folder.
-- [FAQ Template](template/faq-template.md). You can contribute FAQs in the `contribute/faqs` folder.
+- [Tutorial Template](https://gitee.com/openharmony/docs/blob/master/en/contribute/template/tutorial-template.md). You can contribute tutorials in the `contribute/tutorial` folder.
+- [FAQ Template](https://gitee.com/openharmony/docs/blob/master/en/contribute/template/faq-template.md). You can contribute FAQs in the `contribute/faqs` folder.
More writing templates are available in the **contribute** folder in the **Docs** repository.
diff --git a/en/contribute/template/concept-overview-template.md b/en/contribute/template/concept-overview-template.md
deleted file mode 100644
index 76b46ec93252db454751976d43397c821ea20f4e..0000000000000000000000000000000000000000
--- a/en/contribute/template/concept-overview-template.md
+++ /dev/null
@@ -1,111 +0,0 @@
-# Overview Template
-
-## Basic Concepts
-
-***[Writing Requirements]***
-
-*Mandatory. Describe basic concepts related to a development task to help developers better understand the task. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Common concepts in the industry are not described.| |
-| Common terms in the industry, rather than internal terms, are used.| |
-
-
-***[Example]***
-
-
-The XX system provides the audio module for your application to implement audio-related features, including audio playback, recording, and volume management.
-
-
-It is considered good practice that you understand the following concepts before starting application development:
-
-
-- Sampling
- Sampling is a process where analog signals are converted into digital signals that can be represented by 0101.
-
-- Sampling rate
- Sampling rate is the number of samples extracted from a continuous signal per second to form a discrete signal. It is measured in Hz. Generally, human hearing range is from 20 Hz to 20 kHz. Common audio sampling rates include 8 kHz, 11.025 kHz, 22.05 kHz, 16 kHz, 37.8 kHz, 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz.
-
-- Channel
- Channels refer to different spatial positions where independent audio signals are recorded or played. The number of channels is the number of audio sources used during audio recording, or the number of speakers used for audio playback.
-
-- Audio frame
- Audio data is in stream form. For the convenience of audio algorithm processing and transmission, it is generally agreed that a data amount in a unit of 2.5 to 60 milliseconds is one audio frame. This unit is called sampling time, and its length is specific to codecs and the application requirements.
-
-
-## Working Principles
-
-***[Writing Requirements]***
-
-*Optional. You can delete this section if the working principles are simple and the basic concepts in the **Overview** section are enough for understanding.*
-
-*Describe the implementation principles, for example, the time for calling the APIs and triggering callbacks related to key steps, to help developers better understand the basic operation principles, carry out development tasks, and locate problems.*
-
-*The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Only principles related to the development task are described.| |
-| Supplementary graphics are used, such as sequence diagrams and flowcharts. The text description is consistent with the figure description.| |
-
-***[Example 1]***
-
-- Semaphore initialization: The system allocates memory for the semaphores configured (the value of *N* can be configured by users and is limited by the memory), initializes all semaphores to be unused semaphores, and adds them to a linked list for the system to use.
-
-- Semaphore creation: The system obtains a semaphore from the linked list of unused semaphores and assigns an initial value to the semaphore.
-
-- Semaphore request: If the counter value is greater than 0, the system allocates a semaphore, decreases the value by 1, and returns a success message. Otherwise, the system blocks the task and adds the task to the end of a task queue waiting for semaphores. The wait timeout period can be set.
-
-- When a semaphore is released, if there is no task waiting for it, the counter is increased by 1. Otherwise, the first task in the wait queue is woken up.
-
-- Semaphore deletion: The system sets a semaphore in use to the unused state and inserts it to the linked list of unused semaphores.
-
-- Semaphore allows only a specified number of tasks to access a shared resource at a time. When the number of tasks accessing the resource reaches the limit, other tasks will be blocked until the semaphore is released.
-
-
-***[Example 2]***
-
-**Working Principles of Mutexes**
-
-In a multi-task environment, multiple tasks may access the same shared resource. However, certain shared resources are not shared, and can only be accessed exclusively by tasks. A mutex can be used to address this issue.
-
-When non-shared resources are accessed by a task, the mutex is locked. Other tasks will be blocked until the mutex is released by the task. The mutex allows only one task to access the shared resources at a time, ensuring integrity of operations on the shared resources.
-
-
-
-## Limitations and Constraints
-
-***[Writing Requirements]***
-
-*Mandatory. Describe the constraints of the development task and the negative impact of the constraints, including but not limited to the following:*
-
-- ***Function Limitations***
- - *Application scope of the function (specify scenarios that are not supported)*
- - *Specification limitations*
-
-- ***Operation Limitations***
-
- - *Operations on known issues*
- - *Potentially risky operations (such as performance deterioration)*
- - *Operations that may cause performance deterioration*
-
-*The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| The function limitations or operation restrictions are clearly specified.| |
-| Only constraints that affect task development or user experience are described.| |
-| Operations that are prone to errors are described in the procedure but not described in this section.| |
-
-***[Example]***
-
-**Limitations and Constraints on Mutexes:**
-
-- Two tasks cannot lock the same mutex. If a task attempts to lock a mutex held by another task, the task will be blocked until the mutex is unlocked.
-
-- Mutexes cannot be used in the interrupt service program.
-
-- When using the LiteOS-A kernel, the xx system must ensure real-time task scheduling and avoid long-time task blocking. Therefore, a mutex must be released as soon as possible.
-
-- When a mutex is held by a task, the task priority cannot be changed by using APIs such as **LOS_TaskPriSet**.
diff --git a/en/contribute/template/figures/how-distributedobject-works.png b/en/contribute/template/figures/how-distributedobject-works.png
new file mode 100644
index 0000000000000000000000000000000000000000..33785a3fd4c66624b298b1aa36959dbf635d2343
Binary files /dev/null and b/en/contribute/template/figures/how-distributedobject-works.png differ
diff --git a/en/contribute/template/guide-template.md b/en/contribute/template/guide-template.md
index 90b5133d0817050586903c8514ddb5e2b838a324..c497b984ff363a56376a5e1d470a177d9e540003 100644
--- a/en/contribute/template/guide-template.md
+++ b/en/contribute/template/guide-template.md
@@ -1,158 +1,405 @@
-# Development Guidelines
+# Development Guide Writing Template
-***[Writing Requirements]***
+> **NOTE**
+>
+> *1. This template provides the recommended development guide document framework and writing instructions for typical knowledge points. In your writing, complete the development task scenario analysis and development guide outline design based on the specific **solution/feature/function/module**, and then write the content based on this template.*
+>
+> *2. Do not add any content between level-1 title (marked with #) and level-2 title (marked with ##).*
+>
+> *3. Delete all the writing instructions in italics from your formal documents.*
+
+
+## *Example* Overview
+
+*Mandatory. Based on the scenario division of the solution/feature/function/module, you need to provide either "Example Overview" or "Example Task Scenario Overview", or both of them.*
+
+*1. "Example Overview" provides an overview that is common to all task scenarios of this solution/feature/function/module and that developers need to understand. If there is nothing in common, delete it.*
+
+*2. "Example Task Scenario Overview" describes the contents directly related to a task scenario. The knowledge points and key writing points are the same as those in "Example Overview". In this section, you need to introduce this specific task scenario and describe basic concepts, working principles, constraints, and samples that are directly related to the task scenario. If there is no specific task scenario, delete it.*
+
+***[General Instructions for Writing the Development Guide]***
+
+***1. Target audience**: internal and external developers (including product managers). Guidelines for UX designers are usually carried by UX design specifications and are not covered in the development guide. If UX design specifications need to be mentioned in the development guide, use hyperlinks.*
+
+***2. Content positioning**: Introduce what the solution/feature/function/module is, why it is required, and how to design, develop, and release related applications/devices. The development guide aims to help developers learn necessary knowledge and achieve specified task objectives in actual development activities.*
-*Mandatory. Describe how a developer completes tasks in a specific scenario. Include one scenario in each section. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
+***3. User-oriented****: Always provide developer-concerned, perceptible, and useful content from the perspective of developers.*
+***4. Task-oriented****: Focus on actual tasks of developers, and provide complete, correct guidance that is easy to follow.*
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Each section covers only one scenario. If there are multiple scenarios, provide development guidelines for each scenario in separate sections. For example, you can use the following sections in **Audio**: **Development Guidelines on Audio Playback**, **Development Guidelines on Volume Management**, and **Development Guidelines on Sound Playback**.| |
-| Use verbs + nouns to describe task operations in titles.| |
+*5. This template only provides the basic document framework. You can adjust the content based on the actual requirements.*
-## When to Use
+### Introduction
+
+*Mandatory.*
+
+***[Developers' Concerns]***
+
+*What is the solution/feature/function/module (definition)? What problems can it solve or what benefits can it bring (purpose/customer benefits - why)? *
+
+***[Key Writing Points]***
+
+- *Provide easy-to-understand and scenario-specific descriptions. Refer to the SCQA method below to introduce the scenarios and characteristics of the solution/feature/function/module.*
+ - *S: situation. Introduce a familiar scenario.*
+ - *C: complication. Describe the conflict between the situation and requirement.*
+ - *Q: question. Ask a question. What can I do in such a case?*
+ - *A: answer. Describe the solution.*
+
+- *Visualize abstract concepts. You can provide content from the perspective of consumers for better understanding, for example, scenario effect in UX.*
***[Writing Requirements]***
-*Mandatory. Describe in which scenario, what problem is solved, and what the final effect is. Use the SCQA method.*
+- *Provide clear content. Avoid vague, obscure, and ambiguous expressions.*
+
+- *Use only necessary terms, acronyms, abbreviations, and proper nouns, and provide explanations or links to the glossary.*
+
+- *Use consistent terms, acronyms, abbreviations, and proper nouns throughout the document.*
+
-- *S: situation. Introduce a familiar scenario.*
+### Basic Concepts
-- *C: complication. Describe the conflict between the situation and requirement.*
+*Optional. Describe the basic concepts that are common to all task scenarios.*
-- *Q: question. Ask a question. What can I do in such a case?*
+***[Developers' Concerns]***
-- *A: answer. Describe the solution.*
+*What are the unique concepts that I need to know when using the solution/feature/function/module?*
-*The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
+***[Key Writing Points]***
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Clearly describe the background, what operations are done when and where, what problems are solved, and what benefits are delivered.| |
+- *Provide only the concepts that are mandatory in development tasks.*
+
+- *Describe here concepts used in multiple chapters such as the operation mechanism, restrictions, and development process. If a concept is used only in a chapter, describe the concept in that chapter only.*
+
+- *Do not describe common concepts in the industry. Use common terms in the industry instead of jargon.*
+
+- *If there are logical relationships between concepts, you are advised to use figures to describe the relationships.*
+
+***[Writing Requirements]***
+
+- *Provide clear content. Avoid vague, obscure, and ambiguous expressions.*
+
+- *Use only necessary terms, acronyms, abbreviations, and proper nouns, and provide explanations or links to the glossary.*
+
+- *Use consistent terms, acronyms, abbreviations, and proper nouns throughout the document.*
***[Example]***
-You can use APIs described in this section to convert audio data into audible analog signals, play the audio signals using output devices, and manage playback tasks.
+Before developing relational databases, you must understand the following basic concepts:
+
+- **RDB**
+
+A type of database based on the relational model of data. The RDB stores data in rows and columns. An RDB is also called RDB store.
+
+- **Predicate**
+
+ Property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions.
+
+- **Result set**
+
+ A set of query results used to access the data. You can access the required data in a result set in flexible modes.
+
+
+### Working Principles
+
+*Optional. Describe the working principles that are common to all task scenarios.*
+
+***[Developers' Concerns]***
+
+*How does the solution/feature/function/module work? What are the API calling and triggering time of key steps? I want to understand its principles for better use and debugging.*
+***[Key Writing Points]***
-## Available APIs
+- *If the principle is simple and can be understood from the content under "Basic Concepts", do not provide this section.*
+
+- *Describe only the mechanisms and principles that are visible in the development tasks (use or access). Do not provide internal implementation that is invisible to developers.*
+
+- *If necessary, use sequence diagrams and flowcharts. Ensure that the text description matches the figure description.*
+
+- *Be careful not to disclose internal information.*
***[Writing Requirements]***
-*Mandatory. Describe APIs involved in the development guideline to help developers have a general understanding of the APIs, thereby improving development efficiency. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
+- *Provide clear content. Avoid vague, obscure, and ambiguous expressions.*
+
+- *Use only necessary terms, acronyms, abbreviations, and proper nouns, and provide explanations or links to the glossary.*
+
+- *Use consistent terms, acronyms, abbreviations, and proper nouns throughout the document.*
+
+***[Example]***
+
+The distributed data objects are encapsulated into JS objects in distributed in-memory databases, which allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization.
+
+**Figure 1** Working mechanism
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Include only APIs relevant to the development task.| |
-| If there are more than 10 APIs, you can provide only main APIs.| |
+
+
+
+### Constraints
+
+*Optional. Describe constraints that are common to all task scenarios.*
+
+***[Developers' Concerns]***
+
+*What are the constraints for using the solution/feature/function/module? How well is the solution/feature/function/module implemented? Can it meet my requirements?*
+
+***[Key Writing Points]***
+
+- *Describe perceptible constraints that affect development activities, including but not limited to the following:*
+ - ***Function constraints***
+ - *Application scope of the solution/feature/function/module (Specify scenarios that are not supported.)*
+ - *Specification constraints*
+ - ***Operation constraints***
+ - *Operations on known issues*
+ - *Potentially risky operations (such as performance deterioration)*
+
+- *Describe operations that are prone to errors in the procedure, but not in this section.*
***[Example]***
-The **AudioRenderer** class provides open audio playback capabilities. For details about the APIs, see the API reference.
+- Data synchronization can be implemented across devices only for the applications with the same bundleName.
+
+- Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects.
-**Table 1** Audio playback APIs
+- The maximum size of a distributed data object is 500 KB.
-| API| Description|
-| -------- | -------- |
-| AudioRenderer(AudioRendererInfo audioRendererInfo, PlayMode pm) throws IllegalArgumentException | A constructor used to create an **AudioRenderer** instance based on the specified playback parameters, the specified playback mode, and the default playback device.|
-| AudioRenderer(AudioRendererInfo audioRendererInfo, PlayMode pm, AudioDeviceDescriptor outputDevice) throws IllegalArgumentException | A constructor used to create an **AudioRenderer** instance based on the specified playback parameters, playback mode, and playback device.|
-| boolean play() | Plays audio streams.|
-| boolean write(byte[] data, int offset, int size) | Writes audio data in the specified byte array into an audio receiver for playback.|
+### Samples
-## How to Develop
+*Optional. Provide samples that are common to all task scenarios.*
+
+***[Developers' Concerns]***
+
+*What sample code, codelabs, and demo projects are available?*
+
+***[Key Writing Points]***
+
+*Provide links (generally Gitee links) to the released sample code, codelabs, and demo projects. Do not include project packages into the document as an attachment.*
+
+***[Example]***
+
+The following sample is provided to help you better understand how to develop abilities:
+
+- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
+
+
+## Setting Up the Environment
+
+*Optional.*
+
+*Based on the analysis and breakdown of a specific task scenario, you can place the environment setup content under "Prerequisites" or "Preparations" and close to the "How to Develop" of the specific scenario.*
+
+*Specify how to prepare the development environment, including software and hardware configuration requirements, tool requirements, and device requirements.*
+
+*Delete this section if no special requirements are involved.*
+
+
+### Environment Requirements
***[Writing Requirements]***
- *Mandatory. Describe the overall process to help developers quickly complete the task. The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one.*
-
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| **Writing a Development Procedure**| |
-| Complete: All mandatory steps are provided.| |
-| Clear: The logic of the writing is clear and reasonable. The overview, preparations, and operations in the document are described by following certain logic, and the chapters are not broken or contradictory.| |
-| Sentence pattern for tasks: Use verbs + nouns to describe actions in titles or sentences.| |
-| Prevention in advance: Describe the restrictions, error-prone operations, and potential risks in advance. Use general icons and styles.| |
-| Clear steps-1: Describe the purpose of each step, no matter whether it is simple or not.| |
-| Clear steps-2: Specify the environment, tools, operations, and how-to.| |
-| If an operation is optional, specify the optional conditions.| |
-| After the development procedure is complete, specify the expected results.| |
-| **Writing a Code Segment**| |
-| If a code segment involves commands to be copied by developers, display the commands in editable mode, instead of using screenshots. Use code snippets to wrap the commands.| |
-| Highlight key code segments in blue (RGB: 0.0.255), and comment out key steps.| |
-| The code display meets the code indentation requirements.| |
-| If an API call is involved in a step, provide the API and its usage description or sample code. The code comes from specific instances.| |
+*Describe the software and hardware configurations required by the development environment so that developers can prepare the environment in advance. You can use subtitles if there is a large amount of content.*
***[Example]***
-1. Use **AudioStreamInfo.Builder** to create an **AudioStreamInfo** instance for audio stream parameters. The following example uses the default values of the input parameters for **AudioStreamInfo.Builder**. You need to set the parameters based on the audio stream specification.
- ```
- AudioStreamInfo audioStreamInfo = new AudioStreamInfo.Builder()
- .sampleRate(AudioStreamInfo.SAMPLE_RATE_UNSPECIFIED)
- .audioStreamFlag(AudioStreamInfo.AudioStreamFlag.AUDIO_STREAM_FLAG_NONE)
- .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_INVALID)
- .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_INVALID)
- .streamUsage(AudioStreamInfo.StreamUsage.STREAM_USAGE_UNKNOWN)
- .build();
- ```
+The following table describes the environment configuration requirements specific to the Hi3861 development board.
+
+ **Table 1** Hi3861 development environment-specific requirements
+
+| Platform Type| Development Tool| Function| How to Obtain|
+| -------- | -------- | -------- | -------- |
+| Linux server| SCons3.0.4+ | Executes script compilation.| Internet|
+| Linux server| build-essential | Provides a basic software package for compilation and building.| Internet|
+
+
+### Setting Up the Environment
+
+***[Writing Requirements]***
+
+*Describe the procedure for setting up the development environment. If there is a large amount of content, use subtitles, for example, "Setting Up the Basic Build Environment" and "Setting Up the Compilation Tool Environment".*
+
+***[Example]***
+
+1. Start a Linux server.
- Example code for playing a PCM stream:
+2. Run the following command to install the tool installation package:
+
```
- AudioStreamInfo audioStreamInfo = new AudioStreamInfo.Builder().sampleRate(44100)// 44.1 kHz
- .audioStreamFlag(AudioStreamInfo.AudioStreamFlag.AUDIO_STREAM_FLAG_MAY_DUCK)// Set audio ducking.
- .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT)//16-bit PCM
- .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_OUT_STEREO)// Set the dual output channel.
- .streamUsage(AudioStreamInfo.StreamUsage.STREAM_USAGE_MEDIA)// Set the stream to be used for media.
- .build();
+ xxxxx
```
-2. Build the playback parameter structure via **AudioRendererInfo** for the audio stream created in Step 1, and use **AudioRendererInfo.Builder** to create an instance. The following example uses the default parameter values of the **AudioRendererInfo.Builder** instance. You need to set the playback parameters based on the audio playback specification.
+
+3. Run the following command to check whether the tool is successfully installed.
+
```
- AudioRendererInfo audioRendererInfo = new AudioRendererInfo.Builder()
- .audioStreamInfo(audioStreamInfo)
- .audioStreamOutputFlag(AudioRendererInfo.AudioStreamOutputFlag.AUDIO_STREAM_OUTPUT_FLAG_NONE)
- .bufferSizeInBytes(0)
- .distributedDeviceId("")
- .isOffload(false)
- .sessionID(AudioRendererInfo.SESSION_ID_UNSPECIFIED)
- .build();
+ xxxxx
```
- Example code for playing a PCM stream:
- ```
- AudioRendererInfo audioRendererInfo = new AudioRendererInfo.Builder()
- .audioStreamInfo(audioStreamInfo)
- .audioStreamOutputFlag(AudioRendererInfo.AudioStreamOutputFlag.AUDIO_STREAM_OUTPUT_FLAG_DIRECT_PCM)// Set direct PCM output.
- .bufferSizeInBytes(100)
- .distributedDeviceId("E54***5E8")// Use distributed device E54***5E8 for playback.
- .isOffload(false)// Value false indicates that the audio stream is transmitted to the buffer on a segment-by-segment basis for several times and then played. Value true indicates that the audio stream is transmitted to the HAL layer at a time.
- .build();
- ```
-
-3. Specify the playback mode based on the audio stream to be played. The playback modes differ only in the data writing process. Create an **AudioRenderer** instance using a constructor that fits your need.
-4. After the playback task is complete, call the **release()** method on the **AudioRenderer** instance to release resources.
+### Verifying the Environment
+
+***[Writing Requirements]***
+
+*Optional. Provide the criteria for checking whether the environment is set up successfully. You can also provide the criteria along with the environment setup procedure, as provided in the preceding example.*
+
+
+## *Example Task Scenario* Development (Use a specific scenario name. If there is only one scenario, use the solution/feature/function/module name.)
+
+*Mandatory.*
+
+***[Developers' Concerns]***
+
+*How do I use or access the solution/feature/function/module?*
+
+***[Key Writing Points]***
+
+*Provide scenarios that are close to actual development scenarios.*
+
+- *Task scenarios are what developers need to use to achieve development objectives.*
+
+- *There can be one or more task scenarios. You can use multiple "Development Guidelines" sections. Follow the hierarchical logic when writing the guidelines, that is, a task scenario -> a subtask scenario -> task logic ("Development Process") -> operation procedure ("How to Develop").*
+
+### *Example Task Scenario* Overview
+
+*Based on the scenario division of the solution/feature/function/module, you can provide either "Example Task Scenario Overview" or "Example Overview", or both of them.*
+
+*1. "Example Overview" provides an overview that is common to all task scenarios of this solution/feature/function/module and that developers need to understand. If there is nothing in common, delete it.*
+
+*2. "Example Task Scenario Overview" describes the contents directly related to a task scenario. The knowledge points and key writing points are the same as those in "Example Overview". In this section, you need to introduce this specific task scenario and describe basic concepts, working principles, constraints, and samples that are directly related to the task scenario. If there is no specific task scenario, delete it.*
+
+### Development Process
+
+***[Key Writing Points]***
+
+- *Optional. If there are many development steps (five or more core operations) or complex logical relationships between steps, provide the development process so that developers can have a panoramic view of the operations to be performed.*
+
+- *Provide flowcharts and tables if necessary.*
-## (Optional) Commissioning and Verification
+### Available APIs
***[Writing Requirements]***
-*Optional. After the development is complete, perform commissioning and verification to ensure that the operation is successful. The operation procedure requirements are the same as those in **Development Guidelines**. Other specific writing requirements are as follows. After finishing the writing, check your content against these requirements one by one.*
+- *Optional. Describe the key APIs in the development steps and provide the API introduction, so that developers can have a general understanding of development.*
-| Requirement| Satisfied or Not|
-| -------- | -------- |
-| Describe the final service commissioning process. The operation result of each step should be verified after the corresponding development task is complete.| |
-| Specify the criteria for development success.| |
+- *If there are more than 10 APIs, provide the main APIs only.*
+
+- *Ensure that the APIs and their functions of the corresponding version are supported when the document is released.*
+
+***[Example]***
+
+Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-notification.md).
+
+**Table 1** APIs for notification enabling
+
+| API | Description |
+| ------------------------------------------------------------ | ---------------- |
+| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.|
+| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. |
+
+
+### How to Develop
+
+***[Writing Requirements]***
+
+*Mandatory.*
+
+- *Completeness and Correctness*
+ - *Describe the complete development process (for example, steps related to the code, resources, third-party libraries, and application configuration files in the HAP) so that developers can correctly complete the development. Do not omit key configuration operations.*
+ - *Ensure that the code snippet provided in the document can be built with the context in DevEco Studio.*
+ - *Ensure that the complete sample code provided in the document can be run in DevEco Studio, and the execution result is the same as that described in the document.*
+
+- *Clarity*
+ - *Provide a clear execution owner (who), operation purpose (why), operation content (what/how), and scenario (when/where) for each step. Use imperative sentence to describe steps.*
+ - *Clearly provide the APIs (if involved) in steps, as well as their usage description and sample code.*
+ - *Provide development suggestions or precautions for key steps and sample code (comments for sample code).*
+ *Think about what questions may be raised when developers are performing the operations.* *These problems are obstacles to developers.* *Provide support information in the document to help them handle these obstacles.* *Examples of support information:*
+ - *Branch selection principle. Provide principles or suggestions for selecting branches and parameters.*
+
+ - *Necessary supplementary description. Describe possible special operations, required operation permissions, high efficiency skills, and concise and clear background knowledge.*
+
+ - *Precautions. Describe operations that may adversely affect other functions or system performance and reliability, and operations that may cause data loss or security problems.* *Provide this type of information in a style different from that of the body prior to the operation procedure.*
+
+ - *Error prevention/correction information. Provide guidance for preventing, locating, or rectifying typical problems that may occur in the development process.* *This type of information can be provided in "How to Develop" or "FAQs", depending on the content amount.*
+
+- *Standardization*
+ - *Provide both logically and syntactically correct sample code and write it in a standard manner. Anonymize sensitive information, such as mobile numbers, ID cards, and account names, for example, 186\*\*\*\*\*\*\*\*. Use private IP addresses or a corresponding format, for example, xx.xx.xx.xx and www.example.com, rather than real IP addresses and domain names.*
+ - *Provide code that complies with the code indentation requirements. Do not use the **Tab** key to indent code. Instead, use four spaces, to avoid incorrect display.*
+
+**[Example (Excerpt)]**
+
+1. Import the required modules.
+
+ ```javascript
+ import formBindingData from '@ohos.application.formBindingData'
+ import formInfo from '@ohos.application.formInfo'
+ import formProvider from '@ohos.application.formProvider'
+ ```
+
+2. Implement the lifecycle callbacks of **LifecycleForm**.
+
+ ```javascript
+ export default {
+ onCreate(want) {
+ console.log('FormAbility onCreate');
+ // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
+ let obj = {
+ "title": "titleOnCreate",
+ "detail": "detailOnCreate"
+ };
+ let formData = formBindingData.createFormBindingData(obj);
+ return formData;
+ },
+ onCastToNormal(formId) {
+ // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion.
+ console.log('FormAbility onCastToNormal');
+ },
+ }
+ ```
+
+
+### Verification
-## Development Example
***[Writing Requirements]***
-*Provide a complete sample, briefly describe the principle and implementation of the sample, and provide a link to the source code repository.*
+- *Optional. After the development is complete, provide a guide to check whether the operation is successful if there is an independent commissioning and verification operation. The operation procedure is the same as that described in "How to Develop."*
+
+- *Provide only the final service commissioning. You are advised to verify the operation result of each subtask after the development is complete.*
+
+
+## FAQs
+
+*Optional.*
+
+***[Developers' Concerns]***
+
+*What are the typical problems that may occur in the development process of the solution/feature/function/module? How do I locate and solve these problems?*
+
+***[Key Writing Points]***
+
+*Describe the problems that may occur during the development and the solutions to them.*
+
+- *Delete this section if there are no common problems.*
+
+- *It is recommended that common problems in each task scenario be described in a separate chapter. Common problems related to a single task scenario be described in the corresponding chapter.*
+
+
+
+### 1. XX problem (simple problem)
+
+XXX
+
+
+### 2. XX problem (complex problem)
+
+**Symptom**
+
+XXX
+
+**Possible Causes**
-The following sample is provided to help you better understand how to xx:
+XXX
-- xxx (A link to the source code repository)
+**Solution**
- This sample xxx.
+XXX
diff --git a/en/design/hdi-design-specifications.md b/en/design/hdi-design-specifications.md
index c2958495278c0cde9dc7c259fdba56ed56bef720..dcaf228795c5ffb81a5ddfc90a24aaaf9c7a8237 100644
--- a/en/design/hdi-design-specifications.md
+++ b/en/design/hdi-design-specifications.md
@@ -2,7 +2,7 @@
## Overview
-Hardware device interface (HDI) provides a set of interfaces that function as a bridge between a driver and a system service for data transmission. They have a direct impact on system efficiency, stability, compatibility, and reliability, as well as data accuracy and integrity. This document aims to standardize the design and development of OpenHarmony HDIs, thereby ensuring consistent styles and complete functionalities for the HDIs.
+Hardware device interface (HDI) provides a set of interfaces that function as a bridge between drivers and system services for data transmission. They have a direct impact on system efficiency, stability, compatibility, and reliability, as well as data accuracy and integrity. This document aims to standardize the design and development of OpenHarmony HDI interfaces, thereby ensuring consistent styles and complete functionalities for the interfaces.
This document is developed by the [driver SIG](https://gitee.com/openharmony/community/blob/master/sig/sig-driver/sig_driver.md) and approved by the [PMC](https://gitee.com/link?target=https%3A%2F%2Fwww.openharmony.cn%2Fcommunity%2Fpmc%2F). Any revision to this document must be reviewed by the driver SIG and approved by the PMC.
**Acronyms**
@@ -21,10 +21,10 @@ This document is developed by the [driver SIG](https://gitee.com/openharmony/com
**Note**: an explanation to a rule or rec
**Change History**
-
| Version | Change Description |
| --- | --------------------- |
| v1.0 Beta | This issue is the initial version. |
+| v1.0 | This issue is the official version. |
## Scope and Definition
@@ -35,19 +35,19 @@ Located between the system service layer and the device driver layer, HDI provid
## General Rules
-### HDI Version Control
+### Version Control
-The HDI version number must be in the format of `major.minor`, where the `major` version number must be an integer increased in ascending order and the `minor` version number is a one-digit integer.
+The HDI version number must be in the format of `major.minor`, where `major` must be an integer increased in ascending order and `minor` is a one-digit integer.
-- A change in the `major` version number indicates architecture adjustment or interface definition that is not backward compatible.
+- A change in `major` indicates architecture adjustment or interface definition that is not backward compatible.
-- A change in the `minor` version number indicates enhanced or extended interface definitions that are backward compatible.
+- A change in `minor` indicates enhanced or extended interface definitions that are backward compatible.
When `major` changes, `minor` is reset to `0`.
[Example]
-For released vibrator HDIs:
+For released vibrator interfaces:
```cpp
package ohos.hdi.vibrator.v1_0;
@@ -58,7 +58,7 @@ interface IVibrator {
}
```
-If the update to the existing HDIs does not affect version compatibility, for example, adding a function, adding an enum definition, or changing a variable name, change only the `minor`, for example, to `ohos.hdi.vibrator.v1_1`, as follows:
+If the update to the existing interfaces does not affect version compatibility, for example, adding a function, adding an enum definition, or changing a variable name, change only `minor`, for example, to `ohos.hdi.vibrator.v1_1`, as follows:
```cpp
package ohos.hdi.vibrator.v1_1;
@@ -80,20 +80,21 @@ interface IVibrator {
}
```
-### HDI Review and Control
+### Review and Control
-HDIs are provided to implement upper-layer system service requirements and perform hardware operations (such as initialization). New and updated HDIs must be fully reviewed and strictly controlled. Only HDIs that meet universal requirements can be added.
+HDI interfaces are provided to implement upper-layer system service requirements and perform hardware operations (such as initialization). New and updated interfaces must be fully reviewed and strictly controlled. Only interfaces that meet universal requirements can be added.
-Table 1 HDI review and control roles
+Table 1 Interface review and control roles
-| **Role**| **Responsibility** |
-| ------------ | ------------------------------------------------------------ |
-| Contributor | Write HDI code and submit the code and design documents for review. |
-| Committer | Review and approve the HDI code, and submit HDIs to the domain SIG for further review. |
-| Domain SIG | Comment on the commits of new HDI code. Review and approve new HDIs, and submit the updated HDIs to the driver SIG for further review. |
-| Driver SIG | Review and approve the updated HDIs. |
+| **Role** | **Responsibility** |
+| ----------- | ------------------------------------------------ |
+| Contributor | Write HDI code and submit the code and design documents for review. |
+| Committer | Review the HDI code, and submit the code to the domain SIG for further review. |
+| Domain SIG | Review the new or updated HDI code.|
+| Driver SIG | Review the new or updated HDI code. |
+| PMC | Revise and publish this design specifications. |
-#### HDI Release
+### Release
- HDI review process
@@ -101,10 +102,10 @@ Table 1 HDI review and control roles
The main process is as follows:
- 1. The contributor commits code and initiates a review. In addition to the code of new or updated HDIs, the contributor must provide information about the HDI requirement source, usage scenario, permission design, and privacy protection design. For details, see "Review application composites" below. To increase the review efficiency, the contributor can email the design documents to the committer, domain SIG, and driver SIG before submitting the review application.
- 2. The committer reviews the code and HDIs.
- 3. The domain SIG reviews the new or updated HDIs.
- 4. The driver SIG reviews and approves the new or updated HDIs.
+ 1. The contributor commits code and initiates a review. In addition to the code of new or updated HDI interfaces, the contributor must provide information about the HDI requirement source, usage scenario, permission design, and privacy protection design. For details, see "Review application composites" below. To increase the review efficiency, the contributor can email the design documents to the committer, domain SIG, and driver SIG before submitting the review application.
+ 2. The committer reviews the code and HDI interfaces.
+ 3. The domain SIG reviews the new or updated HDI interfaces.
+ 4. The driver SIG reviews and approves the new or updated HDI interfaces.
5. The review is complete, and the code is merged.
- Review application composites
@@ -115,9 +116,9 @@ Table 1 HDI review and control roles
- **HDI version differences, with a clear addition or change scope**
- - Complete interface context, which must be provided in the design document to specify when and how to use each HDI
+ - Complete interface context, which must be provided in the design document to specify when and how to use each interface
- - Resource status transition diagram in the design document for resource-oriented HDIs
+ - Resource status transition diagram in the design document for resource-oriented interfaces
- Compliance with the HDI design constraints proposed in this document
@@ -125,13 +126,13 @@ Table 1 HDI review and control roles
1. Change `major` for any release that is incompatible with earlier versions.
- 2. Change `minor` for any HDI released for function extension.
+ 2. Change `minor` for any interface released for function extension.
- 3. To deprecate any released HDI:
+ 3. To deprecate any released interface:
- The `deprecated` flag must be provided.
- - The deprecated HDIs must be retained in at least four OpenHarmony HDI versions.
+ - The deprecated interfaces must be retained in at least four OpenHarmony HDI versions.
## HDI Design Constraints
@@ -143,7 +144,7 @@ Multiple nouns with similar semantic meanings are not allowed to represent the s
#### [Rule] Keep the parameter sequence consistent.
-The sequence of a parameter or parameter group in multiple HDIs must be the same.
+The sequence of a parameter or parameter group in multiple interfaces must be the same.
For object-oriented C programming, place the interface object as the first parameter by convention.
@@ -239,7 +240,7 @@ Camel case is the practice of writing words without spaces. It indicates the sep
#### [Rule] Follow the single responsibility principle.
-The functionalities of each HDI must be stable and clear, and the trigger source of interface changes must be unique.
+The functionalities of each interface must be stable and clear, and the trigger source of interface changes must be unique.
[Example]
@@ -271,7 +272,7 @@ When defining an interface parameter, consider whether to pass the parameter sep
If no, pass the parameter separately.
-3. Does a parameter group occur in multiple HDIs?
+3. Does a parameter group occur in multiple interfaces?
If yes, you can pass these parameters as a struct. In this case, you also need to consider whether these parameter groups are cohesive.
@@ -292,9 +293,9 @@ struct AudioSampleAttributes
};
```
-#### [Rule] Make HDIs of different device types independent from each other.
+#### [Rule] Make interfaces of different device types independent from each other.
-HDIs are managed by driver type, such as `Camera`, `Input`, `Display`, `Audio`, `Sensor`, and `Storage`. HDIs of different device types should not depend on each other. It is recommended that common capabilities that may be used by more than two types of driver modules be abstracted as common interfaces and archived to the common interface capability library for management.
+Interfaces are managed by driver type, such as `Camera`, `Input`, `Display`, `Audio`, `Sensor`, and `Storage`. Interfaces of different device types should not depend on each other. It is recommended that common capabilities that may be used by more than two types of driver modules be abstracted as common interfaces and archived to the common interface capability library for management.
[Exceptions]
@@ -373,7 +374,7 @@ The correct practice is to copy the data to the memory managed by the service be
#### [Rule] Consider reentrancy.
-HDIs often need to support multiple clients, and a single client may have concurrent requests. Therefore, you must consider reentrancy during HDI design. To ensure correct processing of reentrant interfaces, use locks or semaphores to protect critical resources.
+Interfaces often need to support multiple clients, and a single client may have concurrent requests. Therefore, you must consider reentrancy during HDI design. To ensure correct processing of reentrant interfaces, use locks or semaphores to protect critical resources.
[Example]
@@ -399,28 +400,28 @@ The correct practice is to design and implement the callback interface using a c
### Compatibility
-#### [Rule] Verify the version number before the client calls an HDI.
+#### [Rule] Verify the version number before the client calls an interface.
-Due to the independent component update policy, the version number of an HDI on the client may be different from that on the server. This requires the client to verify the version number on the server and use the matching version to call the HDI on the server.
+Due to the independent component update policy, the version number of an interface on the client may be different from that on the server. This requires the client to verify the version number on the server and use the matching version to call the interface on the server.
[Example]
-Assume that the TP module provides HDIs of versions 1.0 and 1.1. The later version has new interfaces. The components on the client have updated to 1.1, and the server still uses 1.0. If the client directly calls an interface of 1.1 on the server, an error may occur. Instead, the client must use the service version query interface to check the server version. If the server version is 1.0, the client must use the HDI of 1.0 to call the server.
+Assume that the TP module provides interfaces of versions 1.0 and 1.1. The later version has new interfaces. The components on the client have updated to 1.1, and the server still uses 1.0. If the client directly calls an interface of 1.1 on the server, an error may occur. Instead, the client must use the service version query interface to check the server version. If the server version is 1.0, the client must use the interface of 1.0 to call the server.
-#### [Rule] Release HDIs in .idl format.
+#### [Rule] Release HDI interfaces in .idl format.
-Currently, Unix-like drivers use virtual file system (VFS) interfaces to expose internal interfaces. The user mode and kernel mode communicate with each other using system calls. They are packed in different images, and two sets of interfaces are maintained separately. To ensure the consistency of the interface definition and parameter format between the two and consider the design objective of cross-kernel hardware driver foundation (HDF) deployment, release HDIs in .idl format and use a tool to generate interfaces of the target form. In addition, the user-mode caller is not allowed to operate the driver VFS interfaces through the file interface. This causes the framework to strongly depend on the kernel and violates the principle of depending on the interface instead of the implementation.
+Currently, Unix-like drivers use virtual file system (VFS) interfaces to expose internal interfaces. The user mode and kernel mode communicate with each other using system calls. They are packed in different images, and two sets of interfaces are maintained separately. To ensure the consistency of the interface definition and parameter format between the two and consider the design objective of cross-kernel hardware driver foundation (HDF) deployment, release interfaces in .idl format and use a tool to generate interfaces of the target form. In addition, the user-mode caller is not allowed to operate the driver VFS interfaces through the file interface. This causes the framework to strongly depend on the kernel and violates the principle of depending on the interface instead of the implementation.
-Recommended practice: The driver provides HDIs in .idl format and encapsulates the access to the kernel device in the HDI implementation.
+Recommended practice: The driver provides interfaces in .idl format and encapsulates the access to the kernel device in the interface implementation.
[Example]
-An input device provides query interfaces for attributes such as the device type and data precision. The input service should not directly access the VFS interface created by the kernel in open-ioctl mode. Instead, the input driver should provide an HDI to abstract the input device as an object. Then the input service calls this HDI to implement the required functionalities.
+An input device provides query interfaces for attributes such as the device type and data precision. The input service should not directly access the VFS interface created by the kernel in open-ioctl mode. Instead, the input driver should provide an interface to abstract the input device as an object. Then the input service calls this interface to implement the required functionalities.
### Documentation
-#### [Rule] Release HDIs in .idl format.
-To ensure interface compatibility and consistency, release HDIs in .idl format. It is prohibited to directly release interfaces in C/C++ header files.
+#### [Rule] Release HDI interfaces in .idl format.
+To ensure interface compatibility and consistency, release interfaces in .idl format. It is prohibited to directly release interfaces in C/C++ header files.
#### [Rule] Provide an interface description during interface release.
@@ -442,7 +443,7 @@ GetExecutorInfo([out] struct ExecutorInfo executorInfo);
### Programming Languages
-To ensure data interworking between HDIs implemented in different programming languages, follow the restrictions below when using data types in the HDI description.
+To ensure data interworking between interfaces implemented in different programming languages, follow the restrictions below when using data types in the interface description.
#### Constraints on using basic data types
@@ -470,7 +471,7 @@ To ensure data interworking between HDIs implemented in different programming la
#### Constraints on Using Array Types
-| IDL Array Data Type| C++ Data Type | C Data Type |
+| IDL Array Data Type | C++ Data Type | C Data Type |
| --------- | -------------- | ----------- |
| T[] | std::vector | T*,int size |
@@ -480,7 +481,3 @@ To ensure data interworking between HDIs implemented in different programming la
| ------- | ------- | ------ |
| struct | struct | struct |
| enum | enum | enum |
-
-
-## Supplementary Notes
-The beta period of this document is one month from the release date. During this period, your comments are well welcome.
diff --git a/en/device-dev/driver/driver-peripherals-lcd-des.md b/en/device-dev/driver/driver-peripherals-lcd-des.md
index 06941d7c81bcd714357cb6a9e5e22997aa91a2ad..d5ba25a559c9c255a829ac083e869c0b28db9b00 100644
--- a/en/device-dev/driver/driver-peripherals-lcd-des.md
+++ b/en/device-dev/driver/driver-peripherals-lcd-des.md
@@ -319,7 +319,7 @@ static struct PanelInfo g_panelInfo = {
.vsw = VERTICAL_SYNC_WIDTH, /* vertical sync width */
.frameRate = FRAME_RATE, /* frame rate */
.intfType = MIPI_DSI, /* panel interface type */
- .intfSync = OUTPUT_USER, /* output timming type */
+ .intfSync = OUTPUT_USER, /* output timing type */
/* MIPI configuration */
.mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT },
/* backlight config info */
diff --git a/en/device-dev/driver/driver-platform-mmc-develop.md b/en/device-dev/driver/driver-platform-mmc-develop.md
index 10445936ef0e8f53cc95968c40f1c9dd2aae29c7..b222b2081ea95ca1c17fe48e4d1e9413ff44f139 100644
--- a/en/device-dev/driver/driver-platform-mmc-develop.md
+++ b/en/device-dev/driver/driver-platform-mmc-develop.md
@@ -3,7 +3,7 @@
## Overview
-In the Hardware Driver Foundation (HDF), the MultiMedia Card (MMC) uses the independent service mode for API adaptation. In this mode, each device independently publishes a service to process external access requests. When receiving an access request, the HDF DeviceManager extracts parameters from the request to call the internal APIs of the target device. In the independent service mode, the HDF DeviceManager provides service management capabilities. However, you need to configure a node for each device, which increases memory usage.
+In the Hardware Driver Foundation (HDF), the MultiMedia Card (MMC) uses the independent service mode for API adaptation. In this mode, each device independently publishes a service to process external access requests. When receiving an access request, the HDF DeviceManager extracts parameters from the request to call the internal APIs of the target device. In the independent service mode, the HDF DeviceManager provides service management capabilities. However, you need to configure a node for each device, which increases memory usage.
**Figure 1** Independent service mode
@@ -14,7 +14,7 @@ In the Hardware Driver Foundation (HDF), the MultiMedia Card (MMC) uses the inde
**MmcCntlrOps**:
-
+
```
struct MmcCntlrOps {
int32_t (*request)(struct MmcCntlr *cntlr, struct MmcCmd *cmd);
@@ -37,23 +37,23 @@ struct MmcCntlrOps {
**Table 1** Description of callback functions in MmcCntlrOps
-| Function| Input Parameter| Return Value| Description|
+| Function| Input Parameter| Return Value| Description|
| -------- | -------- | -------- | -------- |
-| doRequest | **cntlr**: structure pointer to the MMC controller at the core layer.
**cmd**: structure pointer to the command to execute.| HDF_STATUS| Processes the request.|
-| setClock | **cntlr**: structure pointer to the MMC controller at the core layer.
**clock**: clock frequency to set.| HDF_STATUS| Sets the clock frequency.|
-| setPowerMode | **cntlr**: structure pointer to the MMC controller at the core layer.
**mode**: power consumption mode, which is an enumerated value.| HDF_STATUS| Sets the power consumption mode.|
-| setBusWidth | **cntlr**: structure pointer to the MMC controller at the core layer.
**width**: bus width, which is an enumerated value.| HDF_STATUS| Sets the bus width.|
-| setBusTiming | **cntlr**: structure pointer to the MMC controller at the core layer.
**timing**: bus timing, which is an enumerated value.| HDF_STATUS| Sets the bus timing.|
-| setSdioIrq | **cntlr**: structure pointer to the MMC controller at the core layer.
**enable**: whether to enable Secure Digital Input Output (SDIO) interrupts.| HDF_STATUS| Enables or disables SDIO interrupts.|
-| hardwareReset | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Resets hardware.|
-| systemInit | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Performs system initialization.|
-| setEnhanceSrobe | **cntlr**: structure pointer to the MMC controller at the core layer.
**enable**: whether to enable the enhanced strobe feature.| HDF_STATUS| Sets the enhanced strobe feature.|
-| switchVoltage | **cntlr**: structure pointer to the MMC controller at the core layer.
**volt**: voltage to set, which can be 3.3 V, 1.8 V, or 1.2 V.| HDF_STATUS| Sets the voltage.|
-| devReadOnly | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is read-only.|
-| cardPluged | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is removed.|
-| devBusy | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is being used.|
-| tune | **cntlr**: structure pointer to the MMC controller at the core layer.
**cmdCode**: command code of the uint32_t type.| HDF_STATUS| Tunes the oscillator circuit frequency. |
-| rescanSdioDev | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Scans and adds an SDIO device.|
+| doRequest | **cntlr**: structure pointer to the MMC controller at the core layer.
**cmd**: structure pointer to the command to execute.| HDF_STATUS| Processes the request.|
+| setClock | **cntlr**: structure pointer to the MMC controller at the core layer.
**clock**: clock frequency to set.| HDF_STATUS| Sets the clock frequency.|
+| setPowerMode | **cntlr**: structure pointer to the MMC controller at the core layer.
**mode**: power consumption mode, which is an enumerated value.| HDF_STATUS| Sets the power consumption mode.|
+| setBusWidth | **cntlr**: structure pointer to the MMC controller at the core layer.
**width**: bus width, which is an enumerated value.| HDF_STATUS| Sets the bus width.|
+| setBusTiming | **cntlr**: structure pointer to the MMC controller at the core layer.
**timing**: bus timing, which is an enumerated value.| HDF_STATUS| Sets the bus timing.|
+| setSdioIrq | **cntlr**: structure pointer to the MMC controller at the core layer.
**enable**: whether to enable Secure Digital Input Output (SDIO) interrupts.| HDF_STATUS| Enables or disables SDIO interrupts.|
+| hardwareReset | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Resets hardware.|
+| systemInit | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Performs system initialization.|
+| setEnhanceSrobe | **cntlr**: structure pointer to the MMC controller at the core layer.
**enable**: whether to enable the enhanced strobe feature.| HDF_STATUS| Sets the enhanced strobe feature.|
+| switchVoltage | **cntlr**: structure pointer to the MMC controller at the core layer.
**volt**: voltage to set, which can be 3.3 V, 1.8 V, or 1.2 V.| HDF_STATUS| Sets the voltage.|
+| devReadOnly | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is read-only.|
+| cardPluged | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is removed.|
+| devBusy | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is being used.|
+| tune | **cntlr**: structure pointer to the MMC controller at the core layer.
**cmdCode**: command code of the uint32_t type.| HDF_STATUS| Tunes the oscillator circuit frequency.|
+| rescanSdioDev | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Scans and adds an SDIO device.|
## How to Develop
@@ -75,7 +75,6 @@ The MMC module adaptation involves the following steps:
> For details about the functions in **MmcCntlrOps**, see [Available APIs](#available-apis).
4. Debug the driver.
-
(Optional) For new drivers, verify the basic functions, for example, check the information returned after the **MmcCntlrOps** instance is attached and whether the device starts successfully.
@@ -88,7 +87,7 @@ The following uses **himci.c** as an example to present the information required
Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
MMC driver entry example:
-
+
```
struct HdfDriverEntry g_mmcDriverEntry = {
.moduleVersion = 1,
@@ -106,7 +105,7 @@ The following uses **himci.c** as an example to present the information required
- **device_info.hcs** configuration example
-
+
```
root {
device_info {
@@ -147,7 +146,7 @@ The following uses **himci.c** as an example to present the information required
- **mmc_config.hcs** configuration example
-
+
```
root {
platform {
@@ -196,15 +195,15 @@ The following uses **himci.c** as an example to present the information required
}
}
}
- }
- ```
-
+ }
+ ```
+
3. Initialize the **MmcCntlr** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **MmcCntlrOps** in **MmcCntlr** (so that the underlying driver functions can be called).
- Defining a custom structure
To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **mmc_config.hcs** file to initialize the members in the custom structure and passes important parameters to the **MmcCntlr** object at the core layer.
-
+
```
struct HimciHost {
struct MmcCntlr *mmc;// (Mandatory) Core layer structure
@@ -257,7 +256,7 @@ The following uses **himci.c** as an example to present the information required
- Instantiating **MmcCntlrOps** in **MmcCntlr** (other members are initialized by **Bind**)
-
+
```
static struct MmcCntlrOps g_himciHostOps = {
.request = HimciDoRequest,
@@ -300,7 +299,7 @@ The following uses **himci.c** as an example to present the information required
Initializes the custom structure **HimciHost** object and **MmcCntlr**, and calls the **MmcCntlrAdd** function at the core layer. **MmcCntlr**, **HimciHost**, and **HdfDeviceObject** assign values with each other so that other functions can be converted successfully.
-
+
```
static int32_t HimciMmcBind(struct HdfDeviceObject *obj)
{
@@ -347,7 +346,7 @@ The following uses **himci.c** as an example to present the information required
Implements **ProcMciInit**.
-
+
```
static int32_t HimciMmcInit(struct HdfDeviceObject *obj)
{
@@ -377,7 +376,7 @@ The following uses **himci.c** as an example to present the information required
Releases the memory and deletes the controller. This function assigns values to the **Release** function in the driver entry structure. If the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the value assignment operations.
-
+
```
static void HimciMmcRelease(struct HdfDeviceObject *obj)
{
diff --git a/en/device-dev/driver/driver-platform-regulator-develop.md b/en/device-dev/driver/driver-platform-regulator-develop.md
index 960c3b88bfaf225ec1f911a22be8ffad0b25037b..022df8b238b518c4560789843391f751b1fabb5a 100644
--- a/en/device-dev/driver/driver-platform-regulator-develop.md
+++ b/en/device-dev/driver/driver-platform-regulator-develop.md
@@ -5,23 +5,18 @@
### Regulator
-The regulator module controls the voltage and current supplies of some devices in the system.
-
-### Basic Concepts
-
The regulator module controls the voltage and current supplies of some devices in the system. In an embedded system (especially a mobile phone), it is important to control the power consumption, which directly affects the battery endurance. You can use a regulator to shut down the power supply to an idle module in the system or reduce the voltage and current for the module.
### Working Principles
-In the Hardware Driver Foundation (HDF), the regulator module uses the unified service mode for API adaptation. In this mode, a device service is used as the regulator manager to handle external access requests in a unified manner, which is reflected in the configuration file. The unified service mode applies to the scenario where there are many device objects of the same type, for example, when the regulator has more than 10 controllers. If the independent service mode is used, more device nodes need to be configured and more memory resources will be consumed by services.
+In the Hardware Driver Foundation (HDF), the regulator module uses the unified service mode for API adaptation. In this mode, a device service is used as the regulator manager to handle external access requests in a unified manner, which is reflected in the configuration file. The unified service mode applies when there are many device objects of the same type, for example, when the regulator has more than 10 controllers. If the independent service mode is used, more device nodes need to be configured and more memory resources will be consumed by services.
The regulator module is divided into the following layers:
+- Interface layer: provides APIs for opening or closing a device and writing data.
+- Core layer: provides the capabilities of binding, initializing, and releasing devices.
+- Adaptation layer: implements other functions.
-- The interface layer provides APIs for opening or closing a device and writing data.
-- The core layer provides the capabilities of binding, initializing, and releasing devices.
-- The adaptation layer implements other functions.
-
-NOTE
The core layer can call the functions of the interface layer and uses the hook to call functions of the adaptation layer. In this way, the adaptation layer can indirectly call the functions of the interface layer, but the interface layer cannot call the functions of the adaptation layer.
+NOTE
The core layer can call the APIs of the interface layer and uses hooks to call APIs of the adaptation layer. In this way, the adaptation layer can indirectly call the APIs of the interface layer, but the interface layer cannot call the APIs of the adaptation layer.
**Figure 1** Unified service mode
@@ -33,13 +28,12 @@ The regulator module is divided into the following layers:
Currently, the regulator module supports only the kernels (LiteOS) of mini and small systems.
-## Development Guidelines
### When to Use
The regulator module controls the voltage and current supplies of some devices in the system.
-### Available APIs
+## Available APIs
The functions in **RegulatorMethod** are used to call the corresponding regulator driver functions:
@@ -65,31 +59,34 @@ struct RegulatorMethod {
| Method | Input Parameter | Return Value | Description |
-| ------------ | ------------------------------------------------------------ | ------------------ | ---------------- |
+| ------------ | ----------------------------------------------------------- | ----------------- | ---------------- |
| open | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Opens a device. |
| close | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Closes a device. |
| release | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Releases a device handle. |
-| enable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Enabling a Regulator |
-| disable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Disabling a Regulator |
-| forceDisable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Forcibly Disabling a Regulator |
+| enable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Enables a regulator. |
+| disable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Disables a regulator. |
+| forceDisable | **node**: structure pointer to the regulator node at the core layer. | HDF_STATUS| Forcibly disables a regulator. |
| setVoltage | **node**: structure pointer to the regulator node at the core layer.
**minUv**: minimum voltage to set. It is a uint32_t variable.
**maxUv**: maximum voltage to set. It is a uint32_t variable.| HDF_STATUS| Sets the output voltage range.|
-| getVoltage | **node**: structure pointer to the regulator node at the core layer.
**voltage**: pointer to the output voltage value.| HDF_STATUS| Obtains the voltage. |
+| getVoltage | **node**: structure pointer to the regulator node at the core layer.
**voltage**: pointer to the output voltage.| HDF_STATUS| Obtains the voltage. |
| setCurrent | **node**: structure pointer to the regulator node at the core layer.
**minUa**: minimum current to set. It is a uint32_t variable.
**maxUa**: maximum current to set. It is a uint32_t variable.| HDF_STATUS| Sets the output current range.|
| getCurrent | **node**: structure pointer to the regulator node at the core layer.
**regCurrent**: pointer to the output current, which is of the uint32_t type.| HDF_STATUS| Obtains the current. |
| getStatus | **node**: structure pointer to the regulator node at the core layer.
**status**: pointer to the output status, which is of the uint32_t type.| HDF_STATUS| Obtains the device status. |
-### How to Develop
+
+## How to Develop
The regulator module adaptation procedure is as follows:
-- Instantiate the driver entry.
-- Configure attribute files.
-- Instantiate the core layer APIs.
-- Debug the driver.
+1. Instantiate the driver entry.
+2. Configure attribute files.
+3. Instantiate the core layer APIs.
+4. Debug the driver.
+
+## Development Example
1. Instantiate the driver entry.
- Instantiate the driver entry. The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers are collected to form a segment address space similar to an array for the upper layer to invoke.
+ The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
Generally, the HDF calls the **Init()** function to load the driver. If **Init()** fails to be called, the HDF calls **Release** to release driver resources and exit.
@@ -100,7 +97,7 @@ The regulator module adaptation procedure is as follows:
.Init = VirtualRegulatorInit,
.Release = VirtualRegulatorRelease,
};
- // Call HDF_INIT to register the driver entry with the HDF framework.
+ // Call HDF_INIT to register the driver entry with the HDF.
HDF_INIT(g_regulatorDriverEntry);
```
@@ -115,15 +112,15 @@ The regulator module adaptation procedure is as follows:
| Member | Value |
| --------------- | ------------------------------------------------------------ |
| policy | **0**, which indicates that no service is published. |
- | priority | Driver startup priority. The value range is 0 to 200. A larger value indicates a lower priority. If the priorities are the same, the device loading sequence is not ensured.|
+ | priority | Driver startup priority, which ranges form 0 to 200. A larger value indicates a lower priority. If the priorities are the same, the device loading sequence is not ensured.|
| permission | Driver permission. |
- | moduleName | The value is **HDF_PLATFORM_REGULATOR_MANAGER**. |
- | serviceName | The value is **HDF_PLATFORM_REGULATOR_MANAGER**. |
- | deviceMatchAttr | Reserved. |
+ | moduleName | **HDF_PLATFORM_REGULATOR_MANAGER** |
+ | serviceName | **HDF_PLATFORM_REGULATOR_MANAGER** |
+ | deviceMatchAttr | This parameter is reserved. |
Configure regulator controller information from the second node. This node specifies a type of regulator controllers rather than a specific regulator controller. In this example, there is only one regulator device. If there are multiple regulator devices, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **regulator\_config** file.
- - **device_info.hcs** configuration reference
+ - **device_info.hcs** configuration example
```
root {
@@ -132,14 +129,14 @@ The regulator module adaptation procedure is as follows:
hostName = "platform_host";
priority = 50;
device_regulator :: device {
- device0 :: deviceNode { // Configure an HDF device node for each regulator controller.
- policy = 1; // 2: visible in user mode; 1: visible in kernel mode; 0: no service required.
- priority = 50; // Driver startup priority.
- permission = 0644; // Permission to create device nodes of the driver.
+ device0:: deviceNode { // Set an HDF device node for each regulator controller.
+ policy = 1; // Policy for the driver to publish services.
+ priority = 50; // Driver startup priority.
+ permission = 0644; // Permission to create device nodes for the driver.
/* (Mandatory) Driver name, which must be the same as the moduleName in the driver entry. */
moduleName = "HDF_PLATFORM_REGULATOR_MANAGER";
serviceName = "HDF_PLATFORM_REGULATOR_MANAGER"; // (Mandatory) Unique name of the service published by the driver.
- /* (Mandatory) Set the controller private data, which must be same as that in regulator_config.hcs. */
+ /* (Mandatory) Set the controller private data, which must be same as that in regulator_config.hcs. */
deviceMatchAttr = "hdf_platform_regulator_manager";
}
device1 :: deviceNode {
@@ -155,7 +152,7 @@ The regulator module adaptation procedure is as follows:
}
```
- - **regulator\_config.hcs** reference:
+ - **regulator\_config.hcs** configuration example:
```
root {
@@ -184,7 +181,7 @@ The regulator module adaptation procedure is as follows:
minUa = 0;
maxUa = 0;
}
- /* Each regulator controller corresponds to a controller node. If there are multiple regulator controllers, add the corresponding controller nodes one by one.*/
+ /* Each regulator controller corresponds to a controller node. If there are multiple regulator controllers, add the corresponding controller nodes one by one. */
controller_0x130d0001 :: regulator_controller {
device_num = 1;
name = "regulator_adapter_2";
@@ -201,146 +198,152 @@ The regulator module adaptation procedure is as follows:
}
```
-3. Instantiate the APIs of the core layer.
-
- - Initialize the **RegulatorNode** object at the core layer, including initializing the vendor custom structure (passing parameters and data), instantiating **RegulatorMethod** (used to call underlying functions of the driver) in **PinCntlr**, and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**).
-
- - Initializing the vendor custom structure
+3. Instantiate the APIs of the core layer.
- The **RegulatorNode** structure holds parameters and data for the driver. The HDF obtains the values in **regulator\_config.hcs** using **DeviceResourceIface**.
-
- ```
- // RegulatorNode is the controller structure at the core layer. Its members are assigned with values by using the Init function.
- struct RegulatorNode {
- struct RegulatorDesc regulatorInfo;
- struct DListHead node;
- struct RegulatorMethod *ops;
- void *priv;
- struct OsalMutex lock;
- };
-
- struct RegulatorDesc {
- const char *name; /* Regulator name. */
- const char *parentName; /* Regulator parent node name. */
- struct RegulatorConstraints constraints; /* Regulator constraint information. */
- uint32_t minUv; /* Minimum output voltage. */
- uint32_t maxUv; /* Maximum output voltage. */
- uint32_t minUa; /* Minimum output current. */
- uint32_t maxUa; /* Maximum output current. */
- uint32_t status; /* Regulator status, which can be on or off. */
- int useCount;
- int consumerRegNums; /* Number of regulator consumers. */
- RegulatorStatusChangecb cb; /* Variable used to notify the regulator status changes. */
- };
-
- struct RegulatorConstraints {
- uint8_t alwaysOn; /* Whether the regulator is always on. */
- uint8_t mode; /* Voltage or current. */
- uint32_t minUv; /* Minimum output voltage allowed. */
- uint32_t maxUv; /* Maximum output voltage allowed. */
- uint32_t minUa; /* Minimum output current allowed. */
- uint32_t maxUa; /* Maximum output current allowed. */
- };
- ```
-
+ Initialize the **RegulatorNode** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **RegulatorMethod** in **RegulatorNode** (so that the underlying driver functions can be called).
+
+ - Defining a custom structure
+
+ The **RegulatorNode** structure holds parameters and data for the driver. The HDF obtains the values in **regulator_config.hcs** using **DeviceResourceIface**.
+
+
+
+ ```
+ // RegulatorNode is the core layer controller structure. The Init function assigns values to the members of RegulatorNode.
+ struct RegulatorNode {
+ struct RegulatorDesc regulatorInfo;
+ struct DListHead node;
+ struct RegulatorMethod *ops;
+ void *priv;
+ struct OsalMutex lock;
+ };
+
+ struct RegulatorDesc {
+ const char *name; /* Regulator name. */
+ const char *parentName; /* Regulator parent node name. */
+ struct RegulatorConstraints constraints; /* Regulator constraint information. */
+ uint32_t minUv; /* Minimum output voltage. */
+ uint32_t maxUv; /* Maximum output voltage. */
+ uint32_t minUa; /* Minimum output current. */
+ uint32_t maxUa; /* Maximum output current. */
+ uint32_t status; /* Regulator status, which can be on or off. */
+ int useCount;
+ int consumerRegNums; /* Number of regulator consumers. */
+ RegulatorStatusChangecb cb; /* Variable used to notify the regulator status changes. */
+ };
+
+ struct RegulatorConstraints {
+ uint8_t alwaysOn; /* Whether the regulator is always on. */
+ uint8_t mode; /* Voltage or current. */
+ uint32_t minUv; /* Minimum output voltage allowed. */
+ uint32_t maxUv; /* Maximum output voltage allowed. */
+ uint32_t minUa; /* Minimum output current allowed. */
+ uint32_t maxUa; /* Maximum output current allowed. */
+ };
+ ```
+
+
+
+ - Instantiating **RegulatorMethod** (other members are initialized by **Init**)
+
+ ```c
+ // Example of regulator_virtual.c: Instantiate the hooks.
+ static struct RegulatorMethod g_method = {
+ .enable = VirtualRegulatorEnable,
+ .disable = VirtualRegulatorDisable,
+ .setVoltage = VirtualRegulatorSetVoltage,
+ .getVoltage = VirtualRegulatorGetVoltage,
+ .setCurrent = VirtualRegulatorSetCurrent,
+ .getCurrent = VirtualRegulatorGetCurrent,
+ .getStatus = VirtualRegulatorGetStatus,
+ };
+ ```
+
+
+
+ - **Init** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
-
- - Instantiating **RegulatorMethod** (other members are initialized by **Init**)
-
+ Return value:
+
+ **HDF\_STATUS**
+
+ The table below lists some states. For more details, see **HDF\_STATUS** in **/drivers/framework/include/utils/hdf\_base.h**.
+
+ **Table 2** HDF_STATUS
+
+ | State | Description |
+ | ---------------------- | -------------- |
+ | HDF_ERR_INVALID_OBJECT | Invalid controller object.|
+ | HDF_ERR_MALLOC_FAIL | Failed to allocate memory. |
+ | HDF_ERR_INVALID_PARAM | Invalid parameter. |
+ | HDF_ERR_IO | I/O error. |
+ | HDF_SUCCESS | Initialization successful. |
+ | HDF_FAILURE | Initialization failed. |
+
+ Function description:
+
+ Initializes the custom structure and **RegulatorNode** members, and adds the regulator controller by calling the **RegulatorNodeAdd** function at the core layer.
+
+
```c
- // Example of regulator_virtual.c: Instantiate the hook.
- static struct RegulatorMethod g_method = {
- .enable = VirtualRegulatorEnable,
- .disable = VirtualRegulatorDisable,
- .setVoltage = VirtualRegulatorSetVoltage,
- .getVoltage = VirtualRegulatorGetVoltage,
- .setCurrent = VirtualRegulatorSetCurrent,
- .getCurrent = VirtualRegulatorGetCurrent,
- .getStatus = VirtualRegulatorGetStatus,
- };
+ static int32_t VirtualRegulatorInit(struct HdfDeviceObject *device)
+ {
+ int32_t ret;
+ const struct DeviceResourceNode *childNode = NULL;
+ ...
+ DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) {
+ ret = VirtualRegulatorParseAndInit(device, childNode);// (Mandatory) The implementation is as follows:
+ ...
+ }
+ ...
+ }
+
+ static int32_t VirtualRegulatorParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node)
+ {
+ int32_t ret;
+ struct RegulatorNode *regNode = NULL;
+ (void)device;
+
+ regNode = (struct RegulatorNode *)OsalMemCalloc(sizeof(*regNode));// Load the .hcs file.
+ ...
+ ret = VirtualRegulatorReadHcs(regNode, node);// Read .hcs information.
+ ...
+ regNode->priv = (void *)node; // Instantiate the node.
+ regNode->ops = &g_method; // Instantiate OPS.
+
+ ret = RegulatorNodeAdd(regNode); // Add the node.
+ ...
+ }
```
-
-
-
- - **Init** function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration.
+
+ - **Release** function
- Return value:
+ Input parameter:
- **HDF\_STATUS** (The following table lists some states. For more details, see **HDF\_STATUS** in **/drivers/framework/include/utils/hdf\_base.h**.)
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
- **Table 2** HDF\_STATUS
-
- | State | Description |
- | ---------------------- | -------------- |
- | HDF_ERR_INVALID_OBJECT | Invalid controller object.|
- | HDF_ERR_MALLOC_FAIL | Failed to allocate memory. |
- | HDF_ERR_INVALID_PARAM | Invalid parameter. |
- | HDF_ERR_IO | I/O error. |
- | HDF_SUCCESS | Initialization successful. |
- | HDF_FAILURE | Initialization failed. |
-
- Function description:
-
- Initializes the custom structure and **RegulatorNode** members, and adds the regulator controller by calling the **RegulatorNodeAdd** function at the core layer.
-
-
+ Return value:
+
+ No value is return.
+
+ Function description:
+
+ Releases the memory and deletes the controller. This function assigns values to the **Release** function in the driver entry structure. If the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources.
+
```c
- static int32_t VirtualRegulatorInit(struct HdfDeviceObject *device)
+ static void VirtualRegulatorRelease(struct HdfDeviceObject *device)
{
- int32_t ret;
- const struct DeviceResourceNode *childNode = NULL;
- ...
- DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) {
- ret = VirtualRegulatorParseAndInit(device, childNode);// (Mandatory) The implementation is as follows:
- ...
- }
- ...
- }
-
- static int32_t VirtualRegulatorParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node)
- {
- int32_t ret;
- struct RegulatorNode *regNode = NULL;
- (void)device;
-
- regNode = (struct RegulatorNode *)OsalMemCalloc(sizeof(*regNode));// Load the .hcs file.
- ...
- ret = VirtualRegulatorReadHcs(regNode, node);// Read .hcs information.
- ...
- regNode->priv = (void *)node; // Instantiate the node.
- regNode->ops = &g_method; // Instantiate OPS.
-
- ret = RegulatorNodeAdd(regNode); // Add the node.
...
+ RegulatorNodeRemoveAll();// (Mandatory) Call the function at the core layer to release regulator controller devices and services.
}
```
-
- - **Release** function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration.
-
- Return value:
-
- –
-
- Function description:
-
- Releases memory and deletes the controller. This function assigns a value to the **Release** API in the driver entry structure. If the HDF fails to call the **Init()** function to initialize the driver, the **Release()** function can be called to release driver resources.
-
- ```c
- static void VirtualRegulatorRelease(struct HdfDeviceObject *device)
- {
- ...
- RegulatorNodeRemoveAll();// (Mandatory) Call the function at the core layer to release regulator controller devices and services.
- }
- ```
-
-4. (Optional) Debug the driver.
- Verify the basic functions of the new driver, for example, whether the test cases are successful after the driver is loaded.
\ No newline at end of file
+4. Debug the driver.
+
+ (Optional) Verify the basic functions of the new driver, for example, check whether the test cases are successful after the driver is loaded.
+
+
diff --git a/en/device-dev/driver/driver-platform-spi-des.md b/en/device-dev/driver/driver-platform-spi-des.md
index 8c536413b9eb82b92de579038d2f639865f3b157..696087ee948f1d8ac9747942551c1a166fd7cabd 100644
--- a/en/device-dev/driver/driver-platform-spi-des.md
+++ b/en/device-dev/driver/driver-platform-spi-des.md
@@ -1,160 +1,101 @@
-# SPI
+# SPI
-## Overview
-Serial Peripheral Interface \(SPI\) is a serial bus specification used for high-speed, full-duplex, and synchronous communication.
-SPI is developed by Motorola. It is commonly used for communication with flash memory, real-time clocks, sensors, and analog-to-digital \(A/D\) converters.
+## **Overview**
+
+Serial Peripheral Interface (SPI) is a serial bus specification used for high-speed, full-duplex, and synchronous communication. SPI is developed by Motorola. It is commonly used for communication with flash memory, real-time clocks, sensors, and analog-to-digital (A/D) converters.
+
SPI works in controller/device mode. Generally, there is one SPI controller that controls one or more SPI devices. They are connected via four wires:
-- SCLK: clock signals output from the SPI controller
-- MOSI: data output from the SPI controller and input into an SPI device
-- MISO: data output from an SPI device and input into the SPI controller
-- CS: signals enabled by an SPI device and controlled by the SPI controller
-
-
-[Figure 1](#fig89085710359) shows the connection between one SPI controller and two SPI devices \(device A and device B\). In this figure, device A and device B share three pins \(SCLK, MISO, and MOSI\) of the controller. CS0 of device A and CS1 of device B are connected to CS0 and CS1 of the controller, respectively.
-
-**Figure 1** SPI controller/device connection
-
-
-SPI communication is usually initiated by the SPI controller and is operated as follows:
-
-1. A single SPI device is selected at a time via the CS to communicate with the SPI controller.
-2. Clock signals are provided for the selected SPI device via the SCLK.
-3. The SPI controller sends data to SPI devices via the MOSI, and receives data from SPI devices via the MISO.
-
-- SPI can work in one of the following four modes, equivalent to one of the four possible states for Clock Polarity \(CPOL\) and Clock Phase \(CPHA\):
- - If both CPOL and CPHA are **0**, the clock signal level is low in the idle state and data is sampled on the first clock edge.
- - If CPOL is **0** and CPHA is **1**, the clock signal level is low in the idle state and data is sampled on the second clock edge.
- - If CPOL is **1** and CPHA is **0**, the clock signal level is high in the idle state and data is sampled on the first clock edge.
- - If both CPOL and CPHA are **1**, the clock signal level is high in the idle state and data is sampled on the second clock edge.
-
-
-- SPI defines a set of common functions for operating an SPI device, including those for:
- - Obtaining and releasing the handle of an SPI device.
- - Reading or writing data of a specified length from or into an SPI device.
- - Customizing data reading or writing via **SpiMsg**.
- - Obtaining and setting SPI device configuration parameters.
-
-
-> **NOTE**
->Currently, these functions are only applicable in the communication initiated by the SPI controller.
-
-## Available APIs
-
-**Table 1** APIs for the SPI driver
-
-
-Capability
- |
-Function
- |
-Description
- |
-
-
-SPI device handle obtaining/releasing
- |
-SpiOpen
- |
-Obtains an SPI device handle.
- |
-
-SpiClose
- |
-Releases an SPI device handle.
- |
-
-SPI reading/writing
- |
-SpiRead
- |
-Reads data of a specified length from an SPI device.
- |
-
-SpiWrite
- |
-Writes data of a specified length into an SPI device.
- |
-
-SpiTransfer
- |
-Transfers SPI data.
- |
-
-SPI device configuration
-
- |
-SpiSetCfg
- |
-Sets configuration parameters for an SPI device.
- |
-
-SpiGetCfg
- |
-Obtains configuration parameters of an SPI device.
- |
-
-
-
-
-> **NOTE:**
->All functions provided in this document can be called only in kernel space.
-
-## Usage Guidelines
-
-### How to Use
-
-The figure below illustrates how to use the APIs.
-
-**Figure 2** Using SPI driver APIs
-
-
-### Obtaining an SPI Device Handle
-
-Before performing SPI communication, obtain an SPI device handle by calling **SpiOpen**. This function returns an SPI device handle with a specified bus number and CS number.
-
-DevHandle SpiOpen\(const struct SpiDevInfo \*info\);
-
-**Table 2** Description of SpiOpen
-
-
-Parameter
- |
-Description
- |
-
-info
- |
-Pointer to the SPI device descriptor.
- |
-
-Return Value
- |
-Description
- |
-
-NULL
- |
-Failed to obtain an SPI device handle.
- |
-
-Device handle
- |
-Returns the pointer to the SPI device handle.
- |
-
-
-
-
-The following example shows how to obtain an SPI device handle based on the assumption that both the bus number and CS number of the SPI device are **0**.
+ - SCLK: clock signal output from the SPI controller
+ - MOSI: data output from the SPI controller to a device
+ - MISO: data output from an SPI device to the controller
+ - Chip select (CS): output from the SPI controller to indicate that data is being sent. It is controlled by the SPI controller.
+
+The figure below shows the connection between one controller and two devices (device A and device B). Device A and device B share three pins (SCLK, MISO, and MOSI) of the controller. CS 0 of device A and CS 1 of device B are connected to CS 0 and CS 1 of the controller, respectively.
+
+ **Figure 1** Connection between the SPI controller and devices
+
+ 
+
+- SPI communication is usually initiated by the controller and is performed as follows:
+ 1. The SPI controller selects a device to communicate on the select line. Only one device can be selected at a time.
+ 2. SCLK provides clock signals to the selected device.
+ 3. The SPI controller sends data to the device via MOSI, and receives data from the devices via MISO.
+
+- SPI can work in one of the following modes according to the combination of Clock Polarity (CPOL) and Clock Phase (CPHA) of the clock signal:
+ - If both CPOL and CPHA are **0**, the clock signal level is low in the idle state and data is sampled on the first clock edge.
+ - If CPOL is **0** and CPHA is **1**, the clock signal level is low in the idle state and data is sampled on the second clock edge.
+ - If CPOL is **1** and CPHA is **0**, the clock signal level is high in the idle state and data is sampled on the first clock edge.
+ - If both CPOL and CPHA are **1**, the clock signal level is high in the idle state and data is sampled on the second clock edge.
+
+- SPI defines a set of common functions for operating an SPI device, including those for:
+ - Obtaining and releasing an SPI device handle.
+ - Reading or writing data of the specified length from or into an SPI device.
+ - Customizing data reading or writing via **SpiMsg**.
+ - Obtaining and setting SPI device attributes.
+
+>  **NOTE**
+> Currently, these functions are only applicable in the communication initiated by the SPI controller.
+
+
+## **Available APIs**
+
+ **Table 1** SPI driver APIs
+
+| API| Description|
+| -------- | -------- |
+| SpiOpen | Opens an SPI device handle.|
+| SpiClose | Closes an SPI device handle.|
+| SpiRead | Reads data of the specified length from a device.|
+| SpiWrite | Writes data of the specified length to a device.|
+| SpiTransfer | Transfers SPI data.|
+| SpiSetCfg | Sets SPI device attributes.|
+| SpiGetCfg | Obtains SPI device attributes.|
+
+>  **NOTE**
+> All APIs described in this document can be called only in kernel mode.
+
+
+## Usage Guidelines
+
+
+### How to Use
+
+The figure below shows the general process of using SPI.
+
+ **Figure 2** Process of using SPI APIs
+
+ 
+
+
+### Opening an SPI Device Handle
+Before performing SPI communication, call **SpiOpen** to open the SPI device handle. This function returns the device handle of the SPI based on the specified bus number and CS number.
+
+
+```
+DevHandle SpiOpen(const struct SpiDevInfo *info);
```
-struct SpiDevInfo spiDevinfo; /* SPI device descriptor */
-DevHandle spiHandle = NULL; /* SPI device handle */
-spiDevinfo.busNum = 0; /* SPI device bus number */
-spiDevinfo.csNum = 0; /* SPI device CS number */
-/* Obtain an SPI device handle. */
+ **Table 2** Description of SpiOpen
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| info | Pointer to the SPI device descriptor.|
+| **Return Value**| **Description**|
+| NULL | The operation failed.|
+| Device handle| The operation is successful. The SPI device handle obtained is returned.|
+
+For example, open the handle of the SPI device, whose bus number and the CS number are both **0**.
+
+
+```
+struct SpiDevInfo spiDevinfo; /* SPI device descriptor. */
+DevHandle spiHandle = NULL; /* SPI device handle */
+spiDevinfo.busNum = 0; /* SPI device bus number. */
+spiDevinfo.csNum = 0; /* SPI device CS number. */
+
+/* Obtain the SPI device handle. */
spiHandle = SpiOpen(&spiDevinfo);
if (spiHandle == NULL) {
HDF_LOGE("SpiOpen: failed\n");
@@ -162,324 +103,201 @@ if (spiHandle == NULL) {
}
```
-### Obtaining SPI Device Configuration Parameters
-
-After obtaining the SPI device handle, obtain the SPI device configuration parameters by calling the following function:
-
-int32\_t SpiGetCfg\(DevHandle handle, struct SpiCfg \*cfg\);
-
-**Table 3** Description of SpiGetCfg
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-cfg
- |
-Pointer to SPI device configuration parameters.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in obtaining SPI device configuration parameters.
- |
-
-Negative value
- |
-Failed to obtain SPI device configuration parameters.
- |
-
-
-
-```
-int32_t ret;
-struct SpiCfg cfg = {0}; /* SPI configuration information */
-ret = SpiGetCfg(spiHandle, &cfg); /* Obtain SPI device configuration parameters. */
-if (ret != 0) {
- HDF_LOGE("SpiGetCfg: failed, ret %d\n", ret);
-}
-```
+### Obtaining SPI Device Attributes
+
+After obtaining the SPI device handle, you need to configure the device attributes. Before configuring the device attributes, you can call **SpiGetCfg** to obtain the device attributes.
-### Setting SPI Device Configuration Parameters
-
-After obtaining the SPI device handle, set SPI device configuration parameters by calling the following function:
-
-int32\_t SpiSetCfg\(DevHandle handle, struct SpiCfg \*cfg\);
-
-**Table 4** Description of SpiSetCfg
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-cfg
- |
-Pointer to SPI device configuration parameters.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in setting SPI device configuration parameters.
- |
-
-Negative value
- |
-Failed to set SPI device configuration parameters.
- |
-
-
-
```
-int32_t ret;
-struct SpiCfg cfg = {0}; /* SPI configuration information */
-cfg.mode = SPI_MODE_LOOP; /* Communication in loopback mode */
-cfg.transferMode = PAL_SPI_POLLING_TRANSFER; /* Communication in polling mode */
-cfg.maxSpeedHz = 115200; /* Maximum transmission frequency */
-cfg.bitsPerWord = 8; /* The width of per word to be read or written is 8 bits. */
-ret = SpiSetCfg(spiHandle, &cfg); /* Set SPI device configuration parameters. */
-if (ret != 0) {
- HDF_LOGE("SpiSetCfg: failed, ret %d\n", ret);
-}
+int32_t SpiGetCfg(DevHandle handle, struct SpiCfg *cfg);
```
-### Performing SPI Communication
-
-- Writing data of a specific length into an SPI device
-
-To write data into an SPI device only once, call the following function:
-
-int32\_t SpiWrite\(DevHandle handle, uint8\_t \*buf, uint32\_t len\);
-
-**Table 5** Description of SpiWrite
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-buf
- |
-Pointer to the data to write.
- |
-
-len
- |
-Length of the data to write.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in writing data into an SPI device.
- |
-
-Negative value
- |
-Failed to write data into an SPI device.
- |
-
-
-
+ **Table 3** Description of SpiGetCfg
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| cfg | Pointer to the SPI device attributes.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value | The operation failed.|
+
```
int32_t ret;
-uint8_t wbuff[4] = {0x12, 0x34, 0x56, 0x78};
-/* Write data of a specific length into an SPI device. */
-ret = SpiWrite(spiHandle, wbuff, 4);
+struct SpiCfg cfg = {0}; /* SPI configuration. */
+ret = SpiGetCfg(spiHandle, &cfg); /* Obtain SPI device attributes. */
if (ret != 0) {
- HDF_LOGE("SpiWrite: failed, ret %d\n", ret);
+ HDF_LOGE("SpiGetCfg: failed, ret %d\n", ret);
}
```
-- Reading data of a specific length from an SPI device
-
-To read data from an SPI device only once, call the following function:
-
-int32\_t SpiRead\(DevHandle handle, uint8\_t \*buf, uint32\_t len\);
-
-**Table 6** Description of SpiRead
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-buf
- |
-Pointer to the data to read.
- |
-
-len
- |
-Length of the data to read.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in reading data from an SPI device.
- |
-
-Negative value
- |
-Failed to read data from an SPI device.
- |
-
-
-
+
+### Setting SPI Device Attributes
+
+After obtaining the SPI device handle, call **SpiSetCfg** to set SPI device attributes.
+
```
-int32_t ret;
-uint8_t rbuff[4] = {0};
-/* Read data of a specific length from an SPI device. */
-ret = SpiRead(spiHandle, rbuff, 4);
-if (ret != 0) {
- HDF_LOGE("SpiRead: failed, ret %d\n", ret);
-}
+int32_t SpiSetCfg(DevHandle handle, struct SpiCfg *cfg);
```
-- Launching a custom transfer
-
-To launch a custom transfer, call the following function:
-
-int32\_t SpiTransfer\(DevHandle handle, struct SpiMsg \*msgs, uint32\_t count\);
-
-**Table 7** Description of SpiTransfer
-
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-msgs
- |
-Pointer to the message array to be transferred.
- |
-
-count
- |
-Number of messages in the message array.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-Succeeded in launching the custom transfer.
- |
-
-Negative value
- |
-Failed to launch the custom transfer.
- |
-
-
-
+ **Table 4** Description of SpiSetCfg
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| cfg | Pointer to the SPI device attributes.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value | The operation failed.|
+
```
int32_t ret;
-uint8_t wbuff[1] = {0x12};
-uint8_t rbuff[1] = {0};
-struct SpiMsg msg; /* Custom message to be transferred */
-msg.wbuf = wbuff; /* Pointer to the data to write */
-msg.rbuf = rbuff; /* Pointer to the data to read */
-msg.len = 1; /* The length of the data to read or write is 1 bit. */
-msg.csChange = 1; /* Disable the CS before the next transfer. */
-msg.delayUs = 0; /* No delay before the next transfer */
-msg.speed = 115200; /* Speed of this transfer */
-/* Launch a custom transfer. The number of messages to be transferred is 1. */
-ret = SpiTransfer(spiHandle, &msg, 1);
+struct SpiCfg cfg = {0}; /* SPI configuration. */
+cfg.mode = SPI_MODE_LOOP; /* Communicate in loop mode. */
+cfg.transferMode = PAL_SPI_POLLING_TRANSFER; /* Communicate in polling mode. */
+cfg.maxSpeedHz = 115200; /* Maximum transfer frequency. */
+cfg.bitsPerWord = 8; /* The width of per word to be read or written is 8 bits. */
+ret = SpiSetCfg(spiHandle, &cfg); /* Set SPI device attributes. */
if (ret != 0) {
- HDF_LOGE("SpiTransfer: failed, ret %d\n", ret);
+ HDF_LOGE("SpiSetCfg: failed, ret %d\n", ret);
}
```
-### Destroying the SPI Device Handle
-After the SPI communication, destroy the SPI device handle by calling the following function:
+### Performing SPI Communication
+
+- Write data to an SPI device
+
+ Call **SpiWrite()** to write data to an SPI device only once.
+
+
+ ```
+ int32_t SpiWrite(DevHandle handle, uint8_t *buf, uint32_t len);
+ ```
+
+ **Table 5** Description of SpiWrite
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| buf | Pointer to the data to write.|
+| len | Length of the data to write.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value | The operation failed.|
+
+
+ ```
+ int32_t ret;
+ uint8_t wbuff[4] = {0x12, 0x34, 0x56, 0x78};
+ /* Write data of the specified length to an SPI device. */
+ ret = SpiWrite(spiHandle, wbuff, 4);
+ if (ret != 0) {
+ HDF_LOGE("SpiWrite: failed, ret %d\n", ret);
+ }
+ ```
+
+- Read data from an SPI device
+
+ Call **SpiRead()** to read data from an SPI device only once.
+
-void SpiClose\(DevHandle handle\);
+ ```
+ int32_t SpiRead(DevHandle handle, uint8_t *buf, uint32_t len);
+ ```
-This function will release the resources previously obtained.
+ **Table 6** Description of SpiRead
-**Table 8** Description of SpiClose
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| buf | Pointer to the data to read.|
+| len | Length of the data to read.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
+
+ ```
+ int32_t ret;
+ uint8_t rbuff[4] = {0};
+ /* Read data of the specified length from an SPI device. */
+ ret = SpiRead(spiHandle, rbuff, 4);
+ if (ret != 0) {
+ HDF_LOGE("SpiRead: failed, ret %d\n", ret);
+ }
+ ```
+
+- Perform a custom transfer
+
+ Call **SpiTransfer()** to perform a custom transfer.
+
+
+ ```
+ int32_t SpiTransfer(DevHandle handle, struct SpiMsg *msgs, uint32_t count);
+ ```
+
+ **Table 7** Description of SpiTransfer
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+| msgs | Pointer to the message array to be transferred.|
+| count | Number of messages in the message array.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
+
+ ```
+ int32_t ret;
+ uint8_t wbuff[1] = {0x12};
+ uint8_t rbuff[1] = {0};
+ struct SpiMsg msg; /* Custom message to be transferred. */
+ msg.wbuf = wbuff; /* Data to write. */
+ msg.rbuf = rbuff; /* Data to read. */
+ msg.len = 1; /* The length of the data to read or write is 1 bit. */
+ msg.csChange = 1; /* Close the CS before the next transfer. */
+ msg.delayUs = 0; /* No delay before the next transfer. */
+ msg.speed = 115200; /* Transfer speed. */
+ /* Perform a custom transfer. The number of messages to be transferred is 1. */
+ ret = SpiTransfer(spiHandle, &msg, 1);
+ if (ret != 0) {
+ HDF_LOGE("SpiTransfer: failed, ret %d\n", ret);
+ }
+ ```
+
+
+### Closing an SPI Device Handle
+
+After the SPI communication, call **SpiClose()** to close the SPI device handle.
-
-Parameter
- |
-Description
- |
-
-handle
- |
-SPI device handle.
- |
-
-
-
```
-SpiClose(spiHandle); /* Destroy the SPI device handle. */
+void SpiClose(DevHandle handle);
```
-## Usage Example
+This function releases the resources requested by **MipiDsiOpen**.
+
+ **Table 8** Description of SpiClose
-The following example shows how to obtain an SPI device handle, set the configuration parameters, and then read or write data from or into the SPI device, and finally destroy the SPI device handle.
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | SPI device handle.|
+
+
+```
+SpiClose(spiHandle); /* Close the SPI device handle. */
+```
+
+
+## Example
+
+The following example shows how to obtain an SPI device handle, set device attributes, and then read or write data from or into the SPI device, and finally close the SPI device handle.
```
#include "hdf_log.h"
@@ -488,61 +306,61 @@ The following example shows how to obtain an SPI device handle, set the configur
void SpiTestSample(void)
{
int32_t ret;
- struct SpiCfg cfg; /* SPI device configuration information */
- struct SpiDevInfo spiDevinfo; /* SPI device descriptor */
- DevHandle spiHandle = NULL; /* SPI device handle */
- struct SpiMsg msg; /* Custom message to be transferred */
+ struct SpiCfg cfg; /* SPI device configuration. */
+ struct SpiDevInfo spiDevinfo; /* SPI device descriptor. */
+ DevHandle spiHandle = NULL; /* SPI device handle. */
+ struct SpiMsg msg; /* Custom message to be transferred. */
uint8_t rbuff[4] = { 0 };
uint8_t wbuff[4] = { 0x12, 0x34, 0x56, 0x78 };
uint8_t wbuff2[4] = { 0xa1, 0xb2, 0xc3, 0xd4 };
- spiDevinfo.busNum = 0; /* SPI device bus number */
- spiDevinfo.csNum = 0; /* SPI device CS number */
- spiHandle = SpiOpen(&spiDevinfo); /* Obtain an SPI device handle based on spiDevinfo. */
+ spiDevinfo.busNum = 0; /* SPI device bus number. */
+ spiDevinfo.csNum = 0; /* SPI device CS number. */
+ spiHandle = SpiOpen(&spiDevinfo); /* Open the SPI device handle based on spiDevinfo. */
if (spiHandle == NULL) {
HDF_LOGE("SpiOpen: failed\n");
return;
}
- /* Obtain configuration parameters of an SPI device. */
+ /* Obtain SPI attributes. */
ret = SpiGetCfg(spiHandle, &cfg);
if (ret != 0) {
HDF_LOGE("SpiGetCfg: failed, ret %d\n", ret);
goto err;
}
- cfg.maxSpeedHz = 115200; /* Change the maximum clock frequency to 115200. */
- cfg.bitsPerWord = 8; /* Change the word width to 8 bits. */
- /* Set configuration parameters for an SPI device. */
+ cfg.maxSpeedHz = 115200; /* Set the maximum clock frequency to 115200. */
+ cfg.bitsPerWord = 8; /* Set the word width to 8 bits. */
+ /* Set SPI attributes. */
ret = SpiSetCfg(spiHandle, &cfg);
if (ret != 0) {
HDF_LOGE("SpiSetCfg: failed, ret %d\n", ret);
goto err;
}
- /* Write specified length of data into an SPI device. */
+ /* Write data of the specified length to an SPI device. */
ret = SpiWrite(spiHandle, wbuff, 4);
if (ret != 0) {
HDF_LOGE("SpiWrite: failed, ret %d\n", ret);
goto err;
}
- /* Read data of a specific length from an SPI device. */
+ /* Read data of the specified length from an SPI device. */
ret = SpiRead(spiHandle, rbuff, 4);
if (ret != 0) {
HDF_LOGE("SpiRead: failed, ret %d\n", ret);
goto err;
}
- msg.wbuf = wbuff2; /* Pointer to the data to write */
- msg.rbuf = rbuff; /* Pointer to the data to read */
- msg.len = 4; /* The length of the data to read or write is 4 bits. */
- msg.csChange = 1; /* Disable the CS before the next transfer. */
- msg.delayUs = 0; /* No delay before the next transfer */
- msg.speed = 115200; /* Speed of this transfer */
- /* Launch a custom transfer. The number of messages to be transferred is 1. */
+ msg.wbuf = wbuff2; /* Data to write. */
+ msg.rbuf = rbuff; /* Data to read. */
+ msg.len = 4; /* Set the length of the data to read or write to 4 bits. */
+ msg.csChange = 1; /* Close the CS before the next transfer. */
+ msg.delayUs = 0; /* No delay before the next transfer. */
+ msg.speed = 115200; /* Transfer speed. */
+ /* Perform a custom transfer. The number of messages to be transferred is 1. */
ret = SpiTransfer(spiHandle, &msg, 1);
if (ret != 0) {
HDF_LOGE("SpiTransfer: failed, ret %d\n", ret);
goto err;
}
err:
- /* Destroy the SPI device handle. */
+ /* Close the SPI device handle. */
SpiClose(spiHandle);
}
-```
\ No newline at end of file
+```
diff --git a/en/device-dev/driver/driver-platform-spi-develop.md b/en/device-dev/driver/driver-platform-spi-develop.md
index 40ed76d02446262f32d8d6e55eba044eca88fd89..992424e32ed99b6cbc5dba998871a9d46f3660e6 100644
--- a/en/device-dev/driver/driver-platform-spi-develop.md
+++ b/en/device-dev/driver/driver-platform-spi-develop.md
@@ -1,16 +1,18 @@
-# SPI
+# SPI
-## Overview
+## Overview
-In the Hardware Driver Foundation \(HDF\), the Serial Peripheral Interface \(SPI\) uses the independent service mode for API adaptation. In this mode, each device independently publishes a device service to handle external access requests. After receiving an access request from an API, the device manager extracts the parameters in the request to call the internal method of the target device. In the independent service mode, the service management capabilities of the HDFDeviceManager can be directly used. However, you need to configure a device node for each device, which increases the memory usage.
+Serial Peripheral Interface (SPI) is a serial bus specification used for high-speed, full-duplex, and synchronous communication. In the Hardware Driver Foundation (HDF), the SPI module uses the independent service mode for API adaptation. In this mode, each device independently publishes a service to process external access requests. When receiving an access request, the HDF DeviceManager extracts parameters from the request to call the internal APIs of the target device. In the independent service mode, the HDF DeviceManager provides service management capabilities. However, you need to configure a node for each device, which increases memory usage.
-**Figure 1** Independent service mode
-
+ **Figure 1** Independent service mode
-## Available APIs
+ 
+
+## **Available APIs**
+
+**SpiCntlrMethod**:
-SpiCntlrMethod:
```
struct SpiCntlrMethod {
@@ -21,422 +23,348 @@ struct SpiCntlrMethod {
int32_t (*Close)(struct SpiCntlr *cntlr);
};
```
-**Table 1** Callbacks for the members in the SpiCntlrMethod structure
-
-
-Callback
- |
-Input Parameter
- |
-Return Value
- |
-Description
- |
-
-
-Transfer
- |
-cntlr: structure pointer to the SPI controller at the core layer.
-msg: structure pointer to the SPI message.
-count: number of messages. The value is of the uint32_t type.
- |
-HDF_STATUS
- |
-Transfers messages.
- |
-
-SetCfg
- |
-cntlr: structure pointer to the SPI controller at the core layer.
-cfg: structure pointer to the SPI attributes.
- |
-HDF_STATUS
- |
-Sets SPI controller attributes.
- |
-
-GetCfg
- |
-cntlr: structure pointer to the SPI controller at the core layer.
-cfg: structure pointer to the SPI attributes.
- |
-HDF_STATUS
- |
-Obtains SPI controller attributes.
- |
-
-Open
- |
-cntlr: structure pointer to the SPI controller at the core layer.
- |
-HDF_STATUS
- |
-Enables the SPI.
- |
-
-Close
- |
-cntlr: structure pointer to the SPI controller at the core layer.
- |
-HDF_STATUS
- |
-Disables the SPI.
- |
-
-
-
-
-## How to Develop
+
+ **Table 1** Description of the callback functions in SpiCntlrMethod
+
+| Function| Input Parameter| Return Value| Description|
+| -------- | -------- | -------- | -------- |
+| Transfer | **cntlr**: structure pointer to the SPI controller at the core layer.
**msg**: structure pointer to the SPI message.
**count**: number of messages. The value is of the uint32_t type.| HDF_STATUS| Transfers messages.|
+| SetCfg | **cntlr**: structure pointer to the SPI controller at the core layer.
**cfg**: structure pointer to the SPI attributes.| HDF_STATUS| Sets SPI controller attributes.|
+| GetCfg | **cntlr**: structure pointer to the SPI controller at the core layer.
**cfg**: structure pointer to the SPI attributes.| HDF_STATUS| Obtains SPI controller attributes.|
+| Open | **cntlr**: structure pointer to the SPI controller at the core layer.| HDF_STATUS| Opens an SPI device.|
+| Close | **cntlr**: structure pointer to the SPI controller at the core layer.| HDF_STATUS| Closes an SPI device.|
+
+
+## How to Develop
The SPI module adaptation involves the following steps:
-1. Instantiate the driver entry.
- - Instantiate the **HdfDriverEntry** structure.
- - Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF.
-
-2. Configure attribute files.
- - Add the **deviceNode** information to the **device\_info.hcs** file.
- - \(Optional\) Add the **spi\_config.hcs** file.
-
-3. Instantiate the SPI controller object.
- - Initialize **SpiCntlr**.
- - Instantiate **SpiCntlrMethod** in the **SpiCntlr** object.
-
- For details, see [Available APIs](#section752964871810).
-
- 4. \(Optional\) Debug the driver.
- For new drivers, verify the basic functions, such as the SPI control status and response to interrupts.
-
-
-## Development Example
-
-The following uses **spi\_hi35xx.c** as an example to present the contents that need to be provided by the vendor to implement device functions.
-
-1. Instantiate the driver entry. The driver entry must be a global variable of the **HdfDriverEntry** type \(defined in **hdf\_device\_desc.h**\), and the value of **moduleName** must be the same as that in **device\_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
-
- Generally, HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, HDF calls **Release** to release driver resources and exit.
-
- - SPI driver entry reference
-
- ```
- struct HdfDriverEntry g_hdfSpiDevice = {
- .moduleVersion = 1,
- .moduleName = "HDF_PLATFORM_SPI",// (Mandatory) The value must be the same as that of moduleName in the .hcs file.
- .Bind = HdfSpiDeviceBind, // See the Bind function.
- .Init = HdfSpiDeviceInit, // See the Init function.
- .Release = HdfSpiDeviceRelease, //See the Release function.
- };
- // Call HDF_INIT to register the driver entry with the HDF.
- HDF_INIT(g_hdfSpiDevice);
- ```
-
-2. Add the **deviceNode** information to the **device\_info.hcs** file and configure the device attributes in the **spi\_config.hcs** file. The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **SpiCntlr** members at the core layer.
-
- In this example, there is only one SPI controller. If there are multiple SPI controllers, you need to add the **deviceNode** information to the **device\_info** file and add the corresponding device attributes to the **spi\_config** file.
-
- - **device\_info.hcs** configuration reference
-
- ```
- root {
- device_info {
- match_attr = "hdf_manager";
- platform :: host {
- hostName = "platform_host";
- priority = 50;
- device_spi :: device {// Configure an HDF device node for each SPI controller.
- device0 :: deviceNode {
- policy = 1;
- priority = 60;
- permission = 0644;
- moduleName = "HDF_PLATFORM_SPI";
- serviceName = "HDF_PLATFORM_SPI_0";
- deviceMatchAttr = "hisilicon_hi35xx_spi_0";
- }
- device1 :: deviceNode {
- policy = 1;
- priority = 60;
- permission = 0644;
- moduleName = "HDF_PLATFORM_SPI"; // (Mandatory) Driver name, which must be the same as that of moduleName in the driver entry structure.
- serviceName = "HDF_PLATFORM_SPI_1"; // (Mandatory) Unique name of the service published by the driver
- deviceMatchAttr = "hisilicon_hi35xx_spi_1";// The value must be the same as that of match_attr in the .hcs file.
- }
- ...
- }
- }
- }
- }
- ```
-
- - **spi\_config.hcs** configuration reference
-
- ```
- root {
- platform {
- spi_config {// Configure private data for each SPI controller.
- template spi_controller {// Template configuration. In the template, you can configure the common parameters shared by service nodes.
- serviceName = "";
- match_attr = "";
- transferMode = 0; // Data transfer mode, which can be interrupt transfer (0), flow control transfer (1), or DMA transfer (2).
- busNum = 0; // Bus number
- clkRate = 100000000;
- bitsPerWord = 8; // Bit width of the data transferred
- mode = 19; // SPI data input/output mode
- maxSpeedHz = 0; // Maximum clock frequency
- minSpeedHz = 0; // Minimum clock frequency
- speed = 2000000; // Current message transfer speed
- fifoSize = 256; // FIFO size
- numCs = 1; // Chip select (CS) number
- regBase = 0x120c0000; // Used for address mapping.
- irqNum = 100; // Interruption number
- REG_CRG_SPI = 0x120100e4; // CRG_REG_BASE(0x12010000) + 0x0e4
- CRG_SPI_CKEN = 0;
- CRG_SPI_RST = 0;
- REG_MISC_CTRL_SPI = 0x12030024; // MISC_REG_BASE(0x12030000) + 0x24
- MISC_CTRL_SPI_CS = 0;
- MISC_CTRL_SPI_CS_SHIFT = 0;
- }
- controller_0x120c0000 :: spi_controller {
- busNum = 0; // (Mandatory) Bus number
- CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk
- CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset
- match_attr = "hisilicon_hi35xx_spi_0";// (Mandatory) The value must be the same as that of deviceMatchAttr in device_info.hcs.
- }
- controller_0x120c1000 :: spi_controller {
- busNum = 1;
- CRG_SPI_CKEN = 0x20000; // (0x1 << 17) 0:close clk, 1:open clk
- CRG_SPI_RST = 0x2; // (0x1 << 1) 0:cancel reset, 1:reset
- match_attr = "hisilicon_hi35xx_spi_1";
- regBase = 0x120c1000; // (Mandatory) Used for address mapping.
- irqNum = 101; // (Mandatory) Interrupt number
- }
- ...
- //(Optional) Add nodes to the device_info.hcs file as required.
- }
- }
- }
- ```
-
-3. Initialize the **SpiCntlr** object at the core layer, including initializing the vendor custom structure \(transferring parameters and data\), instantiating **SpiCntlrMethod** \(used to call underlying functions of the driver\) in **SpiCntlr**, and implementing the **HdfDriverEntry** member functions \(**Bind**, **Init**, and **Release**\).
- - Custom structure reference
-
- To the driver, the custom structure carries parameters and data. The values in the **spi\_config.hcs** file are read by HDF, and the structure members are initialized through **DeviceResourceIface**. Some important values, such as the device number and bus number, are also passed to the object at the core layer.
-
- ```
- struct Pl022 {// Corresponds to parameters in .hcs.
- struct SpiCntlr *cntlr;
- struct DListHead deviceList;
- struct OsalSem sem;
- volatile unsigned char *phyBase;
- volatile unsigned char *regBase;
- uint32_t irqNum;
- uint32_t busNum;
- uint32_t numCs;
- uint32_t curCs;
- uint32_t speed;
- uint32_t fifoSize;
- uint32_t clkRate;
- uint32_t maxSpeedHz;
- uint32_t minSpeedHz;
- uint32_t regCrg;
- uint32_t clkEnBit;
- uint32_t clkRstBit;
- uint32_t regMiscCtrl;
- uint32_t miscCtrlCsShift;
- uint32_t miscCtrlCs;
- uint16_t mode;
- uint8_t bitsPerWord;
- uint8_t transferMode;
- };
-
- // SpiCntlr is the core layer controller structure. Its members are assigned with values by using the Init function.
- struct SpiCntlr {
- struct IDeviceIoService service;
- struct HdfDeviceObject *device;
- uint32_t busNum;
- uint32_t numCs;
- uint32_t curCs;
- struct OsalMutex lock;
- struct SpiCntlrMethod *method;
- struct DListHead list;
- void *priv;
- };
- ```
-
- - Instantiate the callback function structure **SpiCntlrMethod** in **SpiCntlr**. Other members are initialized by using the **Init** function.
-
- ```
- // Example in spi_hi35xx.c: instantiate the hook.
- struct SpiCntlrMethod g_method = {
- .Transfer = Pl022Transfer,
- .SetCfg = Pl022SetCfg,
- .GetCfg = Pl022GetCfg,
- .Open = Pl022Open,
- .Close = Pl022Close,
- };
- ```
-
- - Bind function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
-
- Return values:
-
- HDF\_STATUS
-
- Function description:
-
- Associates the **SpiCntlr** object with **HdfDeviceObject**.
-
- ```
- static int32_t HdfSpiDeviceBind(struct HdfDeviceObject *device)
- {
- ...
- return (SpiCntlrCreate(device) == NULL) ? HDF_FAILURE : HDF_SUCCESS;
- }
-
- struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device)
- {
- struct SpiCntlr *cntlr = NULL; // Create the SpiCntlr object of the core layer.
- ...
- cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr));// Allocate memory.
- ...
- cntlr->device = device; // Enable conversion between HdfDeviceObject and SpiCntlr.
- device->service = &(cntlr->service); // Enable conversion between HdfDeviceObject and SpiCntlr.
- (void)OsalMutexInit(&cntlr->lock); // Initialize the lock.
- DListHeadInit(&cntlr->list); // Add the corresponding node.
- cntlr->priv = NULL;
- return cntlr;
- }
- ```
-
- - Init function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
-
- Return values:
-
- HDF\_STATUS \(The following table lists some status. For details about other status, see **HDF\_STATUS** in the **/drivers/framework/include/utils/hdf\_base.h** file.\)
-
- **Table 2** Input parameters and return values of the init function
-
-
- Status (Value)
- |
- Description
- |
-
-
- HDF_ERR_INVALID_OBJECT
- |
- Invalid controller object
- |
-
- HDF_ERR_MALLOC_FAIL
- |
- Failed to allocate memory
- |
-
- HDF_ERR_INVALID_PARAM
- |
- Invalid parameter
- |
-
- HDF_ERR_IO
- |
- I/O error
- |
-
- HDF_SUCCESS
- |
- Initialization successful
- |
-
- HDF_FAILURE
- |
- Initialization failed
- |
-
-
-
-
- Function description:
-
- Initializes the custom structure object and **SpiCntlr**.
-
- ```
- static int32_t HdfSpiDeviceInit(struct HdfDeviceObject *device)
- {
- int32_t ret;
- struct SpiCntlr *cntlr = NULL;
- ...
- cntlr = SpiCntlrFromDevice(device);// Forcibly convert HdfDeviceObject to SpiCntlr by using service. For details about the value assignment, see the Bind function.
- //return (device == NULL) ? NULL : (struct SpiCntlr *)device->service;
- ...
- ret = Pl022Init(cntlr, device);// (Mandatory) Instantiate the operation object customized by the vendor. The following is an example:
- ...
- ret = Pl022Probe(cntlr->priv);
- ...
- return ret;
- }
-
- static int32_t Pl022Init(struct SpiCntlr *cntlr, const struct HdfDeviceObject *device)
- {
- int32_t ret;
- struct Pl022 *pl022 = NULL;
- ...
- pl022 = (struct Pl022 *)OsalMemCalloc(sizeof(*pl022));// Apply for memory.
- ...
- ret = SpiGetBaseCfgFromHcs(pl022, device->property); // Initialize busNum, numCs, speed, fifoSize, clkRate, mode, bitsPerWord, and transferMode.
- ...
- ret = SpiGetRegCfgFromHcs(pl022, device->property); // Initialize regBase, phyBase, irqNum, regCrg, clkEnBit ,clkRstBit, regMiscCtrl, miscCtrlCs, and miscCtrlCsShift.
- ...
- // Calculate the frequencies corresponding to the maximum and minimum speeds.
- pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN);
- pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX);
- DListHeadInit(&pl022->deviceList);// Initialize the DList linked list.
- pl022->cntlr = cntlr; // Enable conversion between Pl022 and SpiCntlr.
- cntlr->priv = pl022; // Enable conversion between Pl022 and SpiCntlr.
- cntlr->busNum = pl022->busNum; // Assign a value to busNum in SpiCntlr.
- cntlr->method = &g_method; // Connect to the SpiCntlrMethod instance.
- ...
- ret = Pl022CreatAndInitDevice(pl022);
- if (ret != 0) {
- Pl022Release(pl022); // Release the Pl022 object if the initialization fails.
- return ret;
- }
- return 0;
- }
- ```
-
- - Release function
-
- Input parameters:
-
- **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs configuration file information.
-
- Return values:
-
- –
-
- Function description:
-
- Releases the memory and deletes the controller. This function assigns a value to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the corresponding value assignment operations.
-
- ```
- static void HdfSpiDeviceRelease(struct HdfDeviceObject *device)
- {
- struct SpiCntlr *cntlr = NULL;
- ...
- cntlr = SpiCntlrFromDevice(device);// Forcibly convert HdfDeviceObject to SpiCntlr by using service. For details about the value assignment, see the Bind function.
- // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service;
- ...
- if (cntlr->priv != NULL) {
- Pl022Remove((struct Pl022 *)cntlr->priv);// A forced conversion from SpiCntlr to Pl022 is involved.
- }
- SpiCntlrDestroy(cntlr); // Release the Pl022 object.
- }
- ```
\ No newline at end of file
+1. Instantiate the driver entry.
+ - Instantiate the **HdfDriverEntry** structure.
+ - Call **HDF_INIT** to register the **HdfDriverEntry** instance with the HDF.
+
+2. Configure attribute files.
+ - Add the **deviceNode** information to the **device_info.hcs** file.
+ - (Optional) Add the **spi_config.hcs** file.
+
+3. Instantiate the SPI controller object.
+ - Initialize **SpiCntlr**.
+ - Instantiate **SpiCntlrMethod** in the **SpiCntlr** object.
+ >  **NOTE**
+ > For details about the functions in **SpiCntlrMethod**, see [Available APIs](#available-apis).
+
+4. Debug the driver.
+ (Optional) For new drivers, verify the basic functions, such as the SPI status control and response to interrupts.
+
+
+## Development Example
+
+The following uses **spi_hi35xx.c** as an example to present the information required for implementing device functions.
+
+1. Instantiate the driver entry.
The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF framework, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
+ Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
+
+ SPI driver entry example:
+
+ ```
+ struct HdfDriverEntry g_hdfSpiDevice = {
+ .moduleVersion = 1,
+ .moduleName = "HDF_PLATFORM_SPI",// (Mandatory) The value must be the same as that of moduleName in the .hcs file.
+ .Bind = HdfSpiDeviceBind, // See the Bind function.
+ .Init = HdfSpiDeviceInit, // See the Init function.
+ .Release = HdfSpiDeviceRelease, //See the Release function.
+ };
+ // Call HDF_INIT to register the driver entry with the HDF.
+ HDF_INIT(g_hdfSpiDevice);
+ ```
+
+2. Add the **deviceNode** information to the **device_info.hcs** file and configure the device attributes in the **spi_config.hcs** file.
+
+ The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **SpiCntlr** members at the core layer.
+
+ In this example, there is only one SPI controller. If there are multiple SPI controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **spi_config** file for each controller.
+
+ - **device_info.hcs** configuration example
+
+
+ ```
+ root {
+ device_info {
+ match_attr = "hdf_manager";
+ platform :: host {
+ hostName = "platform_host";
+ priority = 50;
+ device_spi :: device { // Configure an HDF device node for each SPI controller.
+ device0 :: deviceNode {
+ policy = 1;
+ priority = 60;
+ permission = 0644;
+ moduleName = "HDF_PLATFORM_SPI";
+ serviceName = "HDF_PLATFORM_SPI_0";
+ deviceMatchAttr = "hisilicon_hi35xx_spi_0";
+ }
+ device1 :: deviceNode {
+ policy = 1;
+ priority = 60;
+ permission = 0644;
+ moduleName = "HDF_PLATFORM_SPI"; // (Mandatory) Driver name, which must be the same as that of moduleName in the driver entry structure.
+ serviceName = "HDF_PLATFORM_SPI_1"; // (Mandatory) Unique name of the service published by the driver.
+ deviceMatchAttr = "hisilicon_hi35xx_spi_1";// The value must be the same as that of match_attr in the .hcs file.
+ }
+ ...
+ }
+ }
+ }
+ }
+ ```
+
+ - **spi_config.hcs** configuration example
+
+
+ ```
+ root {
+ platform {
+ spi_config {// Configure private data for each SPI controller.
+ template spi_controller { // Template configuration. In the template, you can configure the common parameters shared by device nodes.
+ serviceName = "";
+ match_attr = "";
+ transferMode = 0; // Data transfer mode. The value **0** indicates interrupt transfer, **1** indicates flow control transfer, and **2** indicates DMA transfer.
+ busNum = 0; // Bus number.
+ clkRate = 100000000;
+ bitsPerWord = 8 // Number of bits per word.
+ mode = 19; // SPI data input/output mode.
+ maxSpeedHz = 0; // Maximum clock frequency.
+ minSpeedHz = 0; // Minimum clock frequency.
+ speed = 2000000; // Current message transfer speed.
+ fifoSize = 256; // FIFO size.
+ numCs = 1; // Chip select (CS) number.
+ regBase = 0x120c0000; // Used for address mapping.
+ irqNum = 100; // Interrupt request (IRQ) number.
+ REG_CRG_SPI = 0x120100e4; // CRG_REG_BASE(0x12010000) + 0x0e4
+ CRG_SPI_CKEN = 0;
+ CRG_SPI_RST = 0;
+ REG_MISC_CTRL_SPI = 0x12030024; // MISC_REG_BASE(0x12030000) + 0x24
+ MISC_CTRL_SPI_CS = 0;
+ MISC_CTRL_SPI_CS_SHIFT = 0;
+ }
+ controller_0x120c0000 :: spi_controller {
+ busNum = 0; // (Mandatory) Bus number.
+ CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk
+ CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset
+ match_attr = "hisilicon_hi35xx_spi_0";// (Mandatory) The value must be the same as that of deviceMatchAttr in device_info.hcs.
+ }
+ controller_0x120c1000 :: spi_controller {
+ busNum = 1;
+ CRG_SPI_CKEN = 0x20000; // (0x1 << 17) 0:close clk, 1:open clk
+ CRG_SPI_RST = 0x2; // (0x1 << 1) 0:cancel reset, 1:reset
+ match_attr = "hisilicon_hi35xx_spi_1";
+ regBase = 0x120c1000; // (Mandatory) Used for address mapping.
+ irqNum = 101; // (Mandatory) IRQ number.
+ }
+ ...
+ //(Optional) Add nodes to the device_info.hcs file as required.
+ }
+ }
+ }
+ ```
+
+3. Initialize the **SpiCntlr** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **SpiCntlrMethod** in **SpiCntlr** (so that the underlying driver functions can be called).
+ - Defining a custom structure
+
+ To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **spi_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the device number and bus number, to the **SpiCntlr** object at the core layer.
+
+
+ ```
+ struct Pl022 {// Corresponds to parameters in .hcs.
+ struct SpiCntlr *cntlr;
+ struct DListHead deviceList;
+ struct OsalSem sem;
+ volatile unsigned char *phyBase;
+ volatile unsigned char *regBase;
+ uint32_t irqNum;
+ uint32_t busNum;
+ uint32_t numCs;
+ uint32_t curCs;
+ uint32_t speed;
+ uint32_t fifoSize;
+ uint32_t clkRate;
+ uint32_t maxSpeedHz;
+ uint32_t minSpeedHz;
+ uint32_t regCrg;
+ uint32_t clkEnBit;
+ uint32_t clkRstBit;
+ uint32_t regMiscCtrl;
+ uint32_t miscCtrlCsShift;
+ uint32_t miscCtrlCs;
+ uint16_t mode;
+ uint8_t bitsPerWord;
+ uint8_t transferMode;
+ };
+
+ // SpiCntlr is the core layer controller structure. The Init function assigns values to the members of SpiCntlr.
+ struct SpiCntlr {
+ struct IDeviceIoService service;
+ struct HdfDeviceObject *device;
+ uint32_t busNum;
+ uint32_t numCs;
+ uint32_t curCs;
+ struct OsalMutex lock;
+ struct SpiCntlrMethod *method;
+ struct DListHead list;
+ void *priv;
+ };
+ ```
+
+ - Instantiating **SpiCntlrMethod** in **SpiCntlr** (other members are initialized by **Init**)
+
+
+ ```
+ // Example in spi_hi35xx.c: instantiate the hooks.
+ struct SpiCntlrMethod g_method = {
+ .Transfer = Pl022Transfer,
+ .SetCfg = Pl022SetCfg,
+ .GetCfg = Pl022GetCfg,
+ .Open = Pl022Open,
+ .Close = Pl022Close,
+ };
+ ```
+
+ - **Bind** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
+
+ Return value:
+
+ HDF_STATUS
+
+ Function description:
+
+ Associates the **SpiCntlr** object with **HdfDeviceObject**.
+
+
+ ```
+ static int32_t HdfSpiDeviceBind(struct HdfDeviceObject *device)
+ {
+ ...
+ return (SpiCntlrCreate(device) == NULL) ? HDF_FAILURE : HDF_SUCCESS;
+ }
+
+ struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device)
+ {
+ struct SpiCntlr *cntlr = NULL; // Create the SpiCntlr object at the core layer.
+ ...
+ cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr));// Allocate memory.
+ ...
+ cntlr->device = device; // Prerequisites for conversion between HdfDeviceObject and SpiCntlr.
+ device->service = &(cntlr->service); // Prerequisites for conversion between HdfDeviceObject and SpiCntlr.
+ (void)OsalMutexInit(&cntlr->lock); // Initialize the lock.
+ DListHeadInit(&cntlr->list); // Add the corresponding nodes.
+ cntlr->priv = NULL;
+ return cntlr;
+ }
+ ```
+
+ - **Init** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
+
+ Return value:
+
+ HDF_STATUS
+
+ The table below lists some status. For more information, see **HDF_STATUS** in the /drivers/framework/include/utils/hdf_base.h file.
+
+ **Table 2** HDF_STATUS
+
+ | Status| Description|
+ | -------- | -------- |
+ | HDF_ERR_INVALID_OBJECT | Invalid controller object.|
+ | HDF_ERR_MALLOC_FAIL | Failed to allocate memory.|
+ | HDF_ERR_INVALID_PARAM | Invalid parameter.|
+ | HDF_ERR_IO | I/O error.|
+ | HDF_SUCCESS | Initialization successful.|
+ | HDF_FAILURE | Initialization failed.|
+
+ Function description:
+
+ Initializes the custom structure object and **SpiCntlr**.
+
+
+ ```
+ static int32_t HdfSpiDeviceInit(struct HdfDeviceObject *device)
+ {
+ int32_t ret;
+ struct SpiCntlr *cntlr = NULL;
+ ...
+ cntlr = SpiCntlrFromDevice(device); // Use service to forcibly convert HdfDeviceObject to SpiCntlr. For details about the value assignment, see the Bind function.
+ // return (device == NULL) ? NULL : (struct SpiCntlr *)device->service;
+ ...
+ ret = Pl022Init(cntlr, device); // (Mandatory) Instantiate the operation object customized by the vendor. The following is an example:
+ ...
+ ret = Pl022Probe(cntlr->priv);
+ ...
+ return ret;
+ }
+
+ static int32_t Pl022Init(struct SpiCntlr *cntlr, const struct HdfDeviceObject *device)
+ {
+ int32_t ret;
+ struct Pl022 *pl022 = NULL;
+ ...
+ pl022 = (struct Pl022 *)OsalMemCalloc(sizeof(*pl022));// Request memory.
+ ...
+ ret = SpiGetBaseCfgFromHcs(pl022, device->property); // Initialize busNum, numCs, speed, fifoSize, clkRate, mode, bitsPerWord, and transferMode.
+ ...
+ ret = SpiGetRegCfgFromHcs(pl022, device->property); // Initialize regBase, phyBase, irqNum, regCrg, clkEnBit, clkRstBit, regMiscCtrl, miscCtrlCs, and miscCtrlCsShift.
+ ...
+ // Calculate the frequencies corresponding to the maximum and minimum speeds.
+ pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN);
+ pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX);
+ DListHeadInit(&pl022->deviceList);// Initialize the DList linked list.
+ pl022->cntlr = cntlr; // Prerequisite for conversion between Pl022 and SpiCntlr.
+ cntlr->priv = pl022; // Prerequisite for conversion between Pl022 and SpiCntlr.
+ cntlr->busNum = pl022->busNum; // Assign a value to busNum in SpiCntlr.
+ cntlr->method = &g_method; // Attach the SpiCntlrMethod instance.
+ ...
+ ret = Pl022CreatAndInitDevice(pl022);
+ if (ret != 0) {
+ Pl022Release(pl022); // Release the Pl022 object if the initialization fails.
+ return ret;
+ }
+ return 0;
+ }
+ ```
+
+ - **Release** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
+
+ Return value:
+
+ No value is returned.
+
+ Function description:
+
+ Releases the memory and deletes the controller. This function assigns values to the **Release** function in the driver entry structure. If the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the value assignment operations.
+
+
+ ```
+ static void HdfSpiDeviceRelease(struct HdfDeviceObject *device)
+ {
+ struct SpiCntlr *cntlr = NULL;
+ ...
+ cntlr = SpiCntlrFromDevice(device); // Use service to forcibly convert HdfDeviceObject to SpiCntlr. For details about the value assignment, see the Bind function.
+ // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service;
+ ...
+ if (cntlr->priv != NULL) {
+ Pl022Remove((struct Pl022 *)cntlr->priv);// A forced conversion from SpiCntlr to Pl022 is involved.
+ }
+ SpiCntlrDestroy(cntlr); // Release the Pl022 object.
+ }
+ ```
diff --git a/en/device-dev/driver/driver-platform-watchdog-des.md b/en/device-dev/driver/driver-platform-watchdog-des.md
index deb85133a3dde4f11cfb03762f4f4fd9d656d51b..aa00d54869576d625e05eead5cbe237a81d560e8 100644
--- a/en/device-dev/driver/driver-platform-watchdog-des.md
+++ b/en/device-dev/driver/driver-platform-watchdog-des.md
@@ -1,124 +1,60 @@
-# Watchdog
-
-## Overview
-
-A watchdog, also called a watchdog timer, is a hardware timing device. If an error occurs in the main program of the system and fails to reset the watchdog timer, the watchdog timer sends a reset signal to restore the system to a normal state.
-
-## Available APIs
-
-**Table 1** Watchdog APIs
-
-
-Capability
- |
-Function
- |
-Description
- |
-
-
-Open/Close
- |
-WatchdogOpen
- |
-Opens a watchdog.
- |
-
-WatchdogClose
- |
-Closes a watchdog.
- |
-
-Start/Stop
- |
-WatchdogStart
- |
-Starts a watchdog.
- |
-
-WatchdogStop
- |
-Stops a watchdog.
- |
-
-Timeout duration
- |
-WatchdogSetTimeout
- |
-Sets the watchdog timeout duration.
- |
-
-WatchdogGetTimeout
- |
-Obtains the watchdog timeout duration.
- |
-
-Status
- |
-WatchdogGetStatus
- |
-Obtains the watchdog status.
- |
-
-Feeding
- |
-WatchdogFeed
- |
-Feeds a watchdog, or resets a watchdog timer.
- |
-
-
-
-
-> **NOTE**
->All watchdog functions provided in this document can be called only in kernel mode.
-
-## Usage Guidelines
-
-### How to Use
-
-The figure below illustrates how to use the APIs.
-
-**Figure 1** Using watchdog driver APIs
-
-
-### Opening a Watchdog
-
-Use **WatchdogOpen** to open a watchdog. A system may have multiple watchdogs. You can open the specified watchdog by using the ID.
-
-int32\_t WatchdogOpen\(int16\_t wdtId\);
-
-**Table 2** Description of WatchdogOpen
-
-
-Parameter
- |
-Description
- |
-
-
-wdtId
- |
-Watchdog ID.
- |
-
-Return Value
- |
-Description
- |
-
-NULL
- |
-Failed to open the watchdog.
- |
-
-DevHandle pointer
- |
-Pointer to the watchdog handle.
- |
-
-
-
+# Watchdog
+
+
+## **Overview**
+
+A watchdog, also called a watchdog timer, is a hardware timing device used to facilitate automatic correction of temporary hardware faults or recover from system malfunctions. If an error occurs in the main program of the system and the watchdog timer is not cleared in time, the watchdog timer sends a reset signal to restore the system to the normal state.
+
+
+## Available APIs
+
+**Table 1** Watchdog APIs
+
+| API| Description|
+| -------- | -------- |
+| WatchdogOpen | Opens a watchdog.|
+| WatchdogClose | Closes a watchdog.|
+| WatchdogStart | Starts a watchdog.|
+| WatchdogStop | Stops a watchdog.|
+| WatchdogSetTimeout | Sets the watchdog timeout duration.|
+| WatchdogGetTimeout | Obtains the watchdog timeout duration.|
+| WatchdogGetStatus | Obtains the watchdog status.|
+| WatchdogFeed | Feeds a watchdog or resets a watchdog timer.|
+
+>  **NOTE**
+>
+> All watchdog APIs provided in this document can be called only in kernel mode.
+
+
+## Usage Guidelines
+
+
+### How to Use
+
+The figure below shows how to use the watchdog APIs.
+
+Figure 1 Using watchdog APIs
+
+
+
+
+### Opening a Watchdog
+
+Use **WatchdogOpen()** to open a watchdog. A system may have multiple watchdogs. You need to specify the ID of the watchdog to open.
+
+```
+DevHandle WatchdogOpen(int16_t wdtId);
+```
+
+**Table 2** Description of WatchdogOpen
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| wdtId | Watchdog ID.|
+| **Return Value**| **Description**|
+| NULL | The operation failed.|
+| **DevHandle** pointer| The operation is successful. The pointer to the watchdog device handle is returned.|
+
```
DevHandle handle = NULL;
@@ -129,46 +65,23 @@ if (handle == NULL) {
}
```
-### Obtaining the Watchdog Status
-
-int32\_t WatchdogGetStatus\(DevHandle handle, int32\_t \*status\);
-
-**Table 3** Description of WatchdogGetStatus
-
-
-Parameter
- |
-Description
- |
-
-
-handle
- |
-Watchdog handle.
- |
-
-status
- |
-Pointer to the watchdog status.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-The watchdog status is obtained.
- |
-
-Negative value
- |
-Failed to obtain the watchdog status.
- |
-
-
-
+
+### Obtaining the Watchdog Status
+
+```
+int32_t WatchdogGetStatus(DevHandle handle, int32_t *status);
+```
+
+**Table 3** Description of WatchdogGetStatus
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | Watchdog device handle.|
+| status | Pointer to the watchdog status obtained.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
```
int32_t ret;
@@ -181,51 +94,28 @@ if (ret != 0) {
}
```
-### Setting the Timeout Duration
-
-int32\_t WatchdogSetTimeout\(PalHandle \*handle, uint32\_t seconds\);
-
-**Table 4** Description of WatchdogSetTimeout
-
-
-Parameter
- |
-Description
- |
-
-
-handle
- |
-Watchdog handle.
- |
-
-seconds
- |
-Timeout duration, in seconds.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-The setting is successful.
- |
-
-Negative value
- |
-Setting failed.
- |
-
-
-
+
+### Setting the Timeout Duration
+
+```
+int32_t WatchdogSetTimeout(DevHandle *handle, uint32_t seconds);
+```
+
+**Table 4** Description of WatchdogSetTimeout
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | Pointer to the watchdog device handle.|
+| seconds | Timeout duration to set, in seconds.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
```
int32_t ret;
uint32_t timeOut = 60;
-/* Set the timeout duration, in seconds. */
+/* Set the timeout duration to 60 seconds. */
ret = WatchdogSetTimeout(handle, timeOut);
if (ret != 0) {
HDF_LOGE("WatchdogSetTimeout: failed, ret %d\n", ret);
@@ -233,46 +123,23 @@ if (ret != 0) {
}
```
-### Obtaining the Timeout Duration
-
-int32\_t WatchdogGetTimeout\(PalHandle \*handle, uint32\_t \*seconds\);
-
-**Table 5** Description of WatchdogGetTimeout
-
-
-Parameter
- |
-Description
- |
-
-
-handle
- |
-Watchdog handle.
- |
-
-seconds
- |
-Pointer to the timeout duration, in seconds.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-The watchdog status is obtained.
- |
-
-Negative value
- |
-Failed to obtain the watchdog status.
- |
-
-
-
+
+### Obtaining the Timeout Duration
+
+```
+int32_t WatchdogGetTimeout(DevHandle *handle, uint32_t *seconds);
+```
+
+**Table 5** Description of WatchdogGetTimeout
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | Pointer to the watchdog device handle.|
+| seconds | Pointer to the timeout duration, in seconds.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
```
int32_t ret;
@@ -285,41 +152,22 @@ if (ret != 0) {
}
```
-### Starting a Watchdog
-
-int32\_t WatchdogStart\(DevHandle handle\);
-
-**Table 6** Description of WatchdogStart
-
-
-Parameter
- |
-Description
- |
-
-
-handle
- |
-Watchdog handle.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-The watchdog is started.
- |
-
-Negative value
- |
-Failed to start the watchdog.
- |
-
-
-
+
+### Starting a Watchdog
+
+```
+int32_t WatchdogStart(DevHandle handle);
+```
+
+**Table 6** Description of WatchdogStart
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | Watchdog device handle.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
```
int32_t ret;
@@ -331,41 +179,22 @@ if (ret != 0) {
}
```
-### Feeding a Watchdog
-
-int32\_t WatchdogFeed\(DevHandle handle\);
-
-**Table 7** Description of WatchdogFeed
-
-
-Parameter
- |
-Description
- |
-
-
-handle
- |
-Watchdog handle.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-The watchdog is fed.
- |
-
-Negative value
- |
-Failed to feed the watchdog.
- |
-
-
-
+
+### Feeding a Watchdog
+
+```
+int32_t WatchdogFeed(DevHandle handle);
+```
+
+**Table 7** Description of WatchdogFeed
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | Watchdog device handle.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
```
int32_t ret;
@@ -377,41 +206,22 @@ if (ret != 0) {
}
```
-### Stopping a Watchdog
-
-int32\_t WatchdogStop\(DevHandle handle\);
-
-**Table 8** Description of WatchdogStop
-
-
-Parameter
- |
-Description
- |
-
-
-handle
- |
-Watchdog handle.
- |
-
-Return Value
- |
-Description
- |
-
-0
- |
-The watchdog is stopped.
- |
-
-Negative value
- |
-Stopping the watchdog failed.
- |
-
-
-
+
+### Stopping a Watchdog
+
+```
+int32_t WatchdogStop(DevHandle handle);
+```
+
+**Table 8** Description of WatchdogStop
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | Watchdog device handle.|
+| **Return Value**| **Description**|
+| 0 | The operation is successful.|
+| Negative value| The operation failed.|
+
```
int32_t ret;
@@ -423,44 +233,38 @@ if (ret != 0) {
}
```
-### Closing a Watchdog
-If the watchdog is no longer required, call **WatchdogClose** to close the watchdog handle.
+### Closing a Watchdog
-void WatchdogClose\(DevHandle handle\);
+If a watchdog is no longer required, call **WatchdogClose()** to close it.
-**Table 9** Description of WatchdogClose
+```
+void WatchdogClose(DevHandle handle);
+```
+
+**Table 9** Description of WatchdogClose
+
+| **Parameter**| **Description**|
+| -------- | -------- |
+| handle | Watchdog device handle.|
-
-Parameter
- |
-Description
- |
-
-
-handle
- |
-Watchdog handle.
- |
-
-
-
```
/* Close the watchdog. */
ret = WatchdogClose(handle);
```
-## Usage Example
-This example provides a complete process for using a watchdog.
+## Example
-In this example, open a watchdog, set the timeout duration, and start the watchdog.
+The following example provides the complete development process.
-- Feed the watchdog periodically to ensure that the system is not reset due to timer expiry.
-- Stop feeding the watchdog and check whether the system is reset after the timer expires.
+1. Open a watchdog, set the timeout duration, and start the watchdog.
-Example:
+2. Feed the watchdog periodically to ensure that the system is not reset due to timer expiry.
+3. Stop feeding the watchdog and check whether the system is reset after the timer expires.
+
+Sample code:
```
#include "watchdog_if.h"
@@ -481,7 +285,7 @@ static int32_t TestCaseWatchdog(void)
/* Open watchdog 0. */
handle = WatchdogOpen(0);
if (handle == NULL) {
- HDF_LOGE("Open watchdog fail!");
+ HDF_LOGE("Open watchdog failed!");
return -1;
}
@@ -493,7 +297,7 @@ static int32_t TestCaseWatchdog(void)
return ret;
}
- /* Obtain the configured timeout duration. */
+ /* Obtain the timeout duration. */
ret = WatchdogGetTimeout(handle, &timeout);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: get timeout fail! ret:%d\n", __func__, ret);
@@ -505,14 +309,14 @@ static int32_t TestCaseWatchdog(void)
/* Start the watchdog. The timer starts. */
ret = WatchdogStart(handle);
if (ret != HDF_SUCCESS) {
- HDF_LOGE("%s: satrt fail! ret:%d\n", __func__, ret);
+ HDF_LOGE("%s: start fail! ret:%d\n", __func__, ret);
WatchdogClose(handle);
return ret;
}
- /* Feed the watchdog every 1s. */
+ /* Feed the watchdog every other second. */
for (i = 0; i < WATCHDOG_TEST_FEED_TIME; i++) {
- HDF_LOGE("%s: feeding watchdog %d times... \n", __func__, i);
+ HDF_LOGI("%s: feeding watchdog %d times... \n", __func__, i);
ret = WatchdogFeed(handle);
if (ret != HDF_SUCCESS) {
HDF_LOGE("%s: feed dog fail! ret:%d\n", __func__, ret);
@@ -522,17 +326,17 @@ static int32_t TestCaseWatchdog(void)
OsalSleep(1);
}
/* Because the interval for feeding the watchdog is shorter than the timeout duration, the system does not reset, and logs can be printed normally. */
- HDF_LOGE("%s: no reset ... feeding test OK!!!\n", __func__);
+ HDF_LOGI("%s: no reset ... feeding test OK!!!\n", __func__);
- /* Enable the timer to expire by stopping feeding the watchdog. */
+ /* Stop feeding the watchdog to make the timer expire. */
for (i = 0; i < WATCHDOG_TEST_FEED_TIME; i++) {
- HDF_LOGE("%s: watiting dog buck %d times... \n", __func__, i);
+ HDF_LOGI("%s: waiting dog buck %d times... \n", __func__, i);
OsalSleep(1);
}
- /* The system resets when the timer expires. If the code is correct, the log below is not displayed. */
- HDF_LOGE("%s: dog has't buck!!! \n", __func__, i);
+ /* The system resets when the timer expires. Theoretically, this log is not displayed. */
+ HDF_LOGI("%s: dog hasn't back!!! \n", __func__, i);
WatchdogClose(handle);
return -1;
}
-```
\ No newline at end of file
+```
diff --git a/en/device-dev/driver/driver-platform-watchdog-develop.md b/en/device-dev/driver/driver-platform-watchdog-develop.md
index 13898cfeaafd8803834c5b62f819e56ecfde96e7..d153a4ae1788127dd08a0cf8c084c3cecc1b73fd 100644
--- a/en/device-dev/driver/driver-platform-watchdog-develop.md
+++ b/en/device-dev/driver/driver-platform-watchdog-develop.md
@@ -1,16 +1,21 @@
-# Watchdog
+# Watchdog
-## Overview
+## **Overview**
-In the Hardware Driver Foundation \(HDF\), the Watchdog \(also called Watchdog timer\) module uses the independent service mode for API adaptation. In this mode, each device independently publishes a device service to handle external access requests. After receiving an access request from an API, the device manager extracts the parameters in the request to call the internal method of the target device. In the independent service mode, the service management capabilities of the HDF Device Manager can be directly used. However, you need to configure a device node for each device, which increases the memory usage.
+A watchdog, also called a watchdog timer, is a hardware timing device used to facilitate automatic correction of temporary hardware faults or recover from system malfunctions.
-**Figure 1** Independent service mode
-
+In the Hardware Driver Foundation (HDF), the watchdog uses the independent service mode for API adaptation. In this mode, each device independently publishes a service to process external access requests. When receiving an access request, the HDF DeviceManager extracts parameters from the request to call the internal APIs of the target device. In the independent service mode, the HDF DeviceManager provides service management capabilities. However, you need to configure a node for each device, which increases memory usage.
-## Available APIs
+ **Figure 1** Independent service mode
+
+ 
+
+
+## **Available APIs**
+
+**WatchdogMethod**:
-WatchdogMethod
```
struct WatchdogMethod {
@@ -25,334 +30,250 @@ struct WatchdogMethod {
};
```
-**Table 1** Callbacks for the members in the WatchdogMethod structure
-
-
-Callback
- |
-Input Parameter
- |
-Output Parameter
- |
-Return Value
- |
-Description
- |
-
-
-getStatus
- |
-wdt: structure pointer to the Watchdog controller at the core layer.
- |
-status: int32_t pointer indicating the watchdog status (started or stopped).
- |
-HDF_STATUS
- |
-Obtains the watchdog status.
- |
-
-start
- |
-wdt: structure pointer to the Watchdog controller at the core layer.
- |
-–
- |
-HDF_STATUS
- |
-Starts a watchdog.
- |
-
-stop
- |
-wdt: structure pointer to the Watchdog controller at the core layer.
- |
-–
- |
-HDF_STATUS
- |
-Stops a watchdog.
- |
-
-setTimeout
- |
-wdt: structure pointer to the Watchdog controller at the core layer.
-seconds: input time value, which is of the uint32_t type.
- |
-–
- |
-HDF_STATUS
- |
-Sets the timeout period (in seconds) for a watchdog. Ensure that the actual watchdog running time complies with this setting.
- |
-
-getTimeout
- |
-wdt: structure pointer to the Watchdog controller at the core layer.
- |
-seconds: output time value, which is of the uint32_t type.
- |
-HDF_STATUS
- |
-Obtains the timeout period of a watchdog.
- |
-
-feed
- |
-wdt: structure pointer to the Watchdog controller at the core layer.
- |
-–
- |
-HDF_STATUS
- |
-Feeds a watchdog.
- |
-
-
-
-
-
-## How to Develop
-
-The Watchdog module adaptation involves the following steps:
-
-1. Instantiate the driver entry.
- - Instantiate the **HdfDriverEntry** structure.
- - Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF.
-
-2. Configure attribute files.
- - Add the **deviceNode** information to the **device\_info.hcs** file.
- - \(Optional\) Add the **watchdog\_config.hcs** file.
-
-3. Instantiate the Watchdog controller object.
- - Initialize **WatchdogCntlr**.
- - Instantiate **WatchdogMethod** in the **WatchdogCntlr** object.
-
- For details, see [Available APIs](#available-apis).
-
-4. \(Optional\) Debug the driver.
-
- For new drivers, verify basic functions, for example, verify the information returned after the connect operation and whether the watchdog timer is successfully set.
-
-
-## Development Example
-
-The following uses **watchdog\_hi35xx.c** as an example to present the contents that need to be provided by the vendor to implement device functions.
-
-1. Instantiate the driver entry. The driver entry must be a global variable of the **HdfDriverEntry** type \(defined in **hdf\_device\_desc.h**\), and the value of **moduleName** must be the same as that in **device\_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
-
- Generally, HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, HDF calls **Release** to release driver resources and exit.
-
- - Watchdog driver entry reference
-
- ```
- struct HdfDriverEntry g_watchdogDriverEntry = {
- .moduleVersion = 1,
- .Bind = Hi35xxWatchdogBind, // See the Bind function.
- .Init = Hi35xxWatchdogInit, // See the Init function.
- .Release = Hi35xxWatchdogRelease, //See the Release function.
- .moduleName = "HDF_PLATFORM_WATCHDOG",// (Mandatory) The value must be the same as that of moduleName in the .hcs file.
- };
- HDF_INIT(g_watchdogDriverEntry);// Call HDF_INIT to register the driver entry with the HDF.
- ```
-
-2. Add the **deviceNode** information to the **device\_info.hcs** file and configure the component attributes in the **watchdog\_config.hcs** file. The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **WatchdogCntlr** members at the core layer.
-
- In this example, there is only one Watchdog controller. If there are multiple Watchdog controllers, you need to add the **deviceNode** information to the **device\_info** file and add the corresponding device attributes to the **watchdog\_config** file.
-
- - **device\_info.hcs** configuration reference
-
- ```
- root {
- device_info {
- match_attr = "hdf_manager";
- device_watchdog :: device {// Device node
- device0:: deviceNode {// DeviceNode of the driver
- The policy = 1; // The value 1 indicates that the driver publishes kernel-mode services. The value 2 indicates that the driver publishes user-mode services.
- priority = 20; // Driver startup priority
- permission = 0644; // Permission to create device nodes for the driver
- moduleName = "HDF_PLATFORM_WATCHDOG";
- // (Mandatory) Driver name. The value must be the same as that of moduleName in the driver entry structure.
- serviceName = "HDF_PLATFORM_WATCHDOG_0";
- // (Mandatory) Unique name of the service published by the driver.
- deviceMatchAttr = "hisilicon_hi35xx_watchdog_0";
- // (Mandatory) Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
- }
- }
- }
- }
- ```
-
- - **watchdog\_config.hcs** configuration reference
-
- ```
- root {
- platform {
- template watchdog_controller {// Template configuration. In the template, you can configure the common parameters shared by service nodes.
- id = 0;
- match_attr = "";
- regBase = 0x12050000; // (Mandatory) Used for address mapping.
- regStep = 0x1000; // (Mandatory) Used for address mapping.
- }
- controller_0x12050000 :: watchdog_controller {// (Mandatory) Keyword for matching the private data of the device driver.
- match_attr = "hisilicon_hi35xx_watchdog_0"; // (Mandatory) The value must be the same as that of deviceMatchAttr in device_info.hcs.
- }
- // Configure this parameter when there are multiple watchdogs.
- ...
- }
- }
- ```
-
-3. Initialize the **WatchdogCntlr** object at the core layer, including initializing the vendor custom structure \(passing parameters and data\), instantiating **WatchdogMethod** \(used to call underlying functions of the driver\) in **WatchdogCntlr**, and implementing the **HdfDriverEntry** member functions \(**Bind**, **Init**, and **Release**\).
- - Custom structure reference
-
- To the driver, the custom structure carries parameters and data. The values in the **watchdog\_config.hcs** file are read by HDF, and the structure members are initialized through **DeviceResourceIface**. Some important values, such as the index and the number of pins, are also passed to the **WatchdogCntlr** object at the core layer.
-
- ```
- struct Hi35xxWatchdog {
- struct WatchdogCntlr wdt; // (Mandatory) Carrier that connects the upper and underlying layers. For details, see the following description.
- OsalSpinlock lock;
- volatile unsigned char *regBase;// [Mandatory] Used for address mapping.
- uint32_t phyBase; // (Mandatory) Used for address mapping.
- uint32_t regStep; // (Mandatory) Used for address mapping.
- };
- // WatchdogCntlr is the core layer controller structure. Its members are assigned with values by using the Init function.
- struct WatchdogCntlr {
- struct IDeviceIoService service;// Driver service
- struct HdfDeviceObject *device; // Drive device
- OsalSpinlock lock; // This variable implements the spinlock function.
- struct WatchdogMethod *ops; // Interface callback
- int16_t wdtId; // ID of the watchdog device
- void *priv; // Save the pointer.
- };
- ```
-
- - Instantiate the callback function structure **WatchdogMethod** in **WatchdogCntlr**. Other members are initialized by using the **Init** and **Bind** functions.
-
- ```
- static struct WatchdogMethod g_method = {
- .getStatus = Hi35xxWatchdogGetStatus,
- .start = Hi35xxWatchdogStart,
- .stop = Hi35xxWatchdogStop,
- .setTimeout = Hi35xxWatchdogSetTimeout,
- .getTimeout = Hi35xxWatchdogGetTimeout,
- .feed = Hi35xxWatchdogFeed,
- };
- ```
-
- - Init and Bind functions
-
- Input parameters:
-
- **HdfDeviceObject**: device object created by the HDF for each driver. It stores device-related private data and service APIs.
-
- Return values:
-
- HDF\_STATUS \(The following table lists some status. For details about other status, see **HDF\_STATUS** in the **//drivers/framework/include/utils/hdf\_base.h** file.\)
-
- **Table 2** Input parameters and return values of the Init and Bind functions
-
-
- Status (Value)
- |
- Description
- |
-
-
- HDF_ERR_INVALID_OBJECT
- |
- Failed to locate the watchdog device
- |
-
- HDF_ERR_MALLOC_FAIL
- |
- Failed to allocate memory
- |
-
- HDF_ERR_IO
- |
- I/O error
- |
-
- HDF_SUCCESS
- |
- Initialization successful
- |
-
- HDF_FAILURE
- |
- Initialization failed
- |
-
-
-
-
- Function description:
-
- Initializes the custom structure object and **WatchdogCntlr**, and calls the **WatchdogCntlrAdd** function at the core layer.
-
- ```
- // Generally, the Init function initializes the members of the Hi35xxWatchdog structure based on the attribute values of the input parameter (HdfDeviceObject).
- // In this example, the Bind function initializes the Hi35xxWatchdog structure.
- static int32_t Hi35xxWatchdogInit(struct HdfDeviceObject *device)
- {
- (void)device;
- return HDF_SUCCESS;
- }
-
- static int32_t Hi35xxWatchdogBind(struct HdfDeviceObject *device)
- {
- int32_t ret;
- struct Hi35xxWatchdog *hwdt = NULL;
- ...
- hwdt = (struct Hi35xxWatchdog *)OsalMemCalloc(sizeof(*hwdt));// Apply for memory for the Hi35xxWatchdog structure.
- ...
- hwdt->regBase = OsalIoRemap(hwdt->phyBase, hwdt->regStep); // Address mapping
- ...
- hwdt->wdt.priv = (void *)device->property;// (Optional) Assign the device attribute values to priv. However, priv is not called subsequently.
- //If priv needs to be called, instantiate the getPriv and releasePriv member functions in WatchdogMethod.
- hwdt->wdt.ops = &g_method; // (Mandatory) Assign the instantiated objects to the ops member so that the top layer can invoke the WatchdogMethod member functions.
- hwdt->wdt.device = device; // (Mandatory) Enable conversion between HdfDeviceObject and WatchdogcCntlr.
- ret = WatchdogCntlrAdd(&hwdt->wdt); // (Mandatory) Call this function to initialize the structure of the core layer. The driver accesses the platform core layer only after a success signal is returned.
- if (ret != HDF_SUCCESS) {// If the operation fails, release the resources used by the Init function.
- OsalIoUnmap((void *)hwdt->regBase);
- OsalMemFree(hwdt);
- return ret;
- }
- return HDF_SUCCESS;
- }
- ```
-
- - Release function
-
- Input parameters:
-
- **HdfDeviceObject**: device object created by the HDF for each driver. It stores device-related private data and service APIs.
-
- Return values:
-
- –
-
- Function description:
-
- Releases the memory and deletes the controller. This function assigns a value to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the corresponding value assignment operations.
-
- ```
- static void Hi35xxWatchdogRelease(struct HdfDeviceObject *device)
- {
- struct WatchdogCntlr *wdt = NULL;
- struct Hi35xxWatchdog *hwdt = NULL;
- ...
- wdt = WatchdogCntlrFromDevice(device);// Convert HdfDeviceObject to WatchdogCntlr by the service member.
- //return (device == NULL) ? NULL : (struct WatchdogCntlr *)device->service;
- if (wdt == NULL) {
- return;
- }
- WatchdogCntlrRemove(wdt); // Core layer function used to execute wdt->device->service = NULL and release cntlr->lock.
- hwdt = (struct Hi35xxWatchdog *)wdt; // Convert WatchdogCntlr to HimciHost.
- if (hwdt->regBase != NULL) {// Remove address mapping.
- OsalIoUnmap((void *)hwdt->regBase);
- hwdt->regBase = NULL;
- }
- OsalMemFree(hwdt); // Release the memory occupied by the vendor-defined objects.
- }
- ```
\ No newline at end of file
+ **Table 1** Description of the callback functions in WatchdogMethod
+
+| Function| Input Parameter| Output Parameter| Return Value| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| getStatus | **wdt**: structure pointer to the watchdog controller at the core layer.| **status**: int32_t pointer to the watchdog status (started or stopped).| HDF_STATUS| Obtains the watchdog status.|
+| start | **wdt**: structure pointer to the watchdog controller at the core layer.| –| HDF_STATUS| Starts a watchdog.|
+| stop | **wdt**: structure pointer to the watchdog controller at the core layer.| –| HDF_STATUS | Stops a watchdog.|
+| setTimeout | **wdt**: structure pointer to the watchdog controller at the core layer.
**seconds**: Timeout duration to set, in seconds. The value is of the uint32_t type. | – | HDF_STATUS | Sets the timeout duration for a watchdog. |
+| getTimeout | **wdt**: structure pointer to the watchdog controller at the core layer.| **seconds**: Pointer to the watchdog timeout duration obtained. The value is of the uint32_t type. | HDF_STATUS| Obtains the timeout duration of a watchdog.|
+| feed | **wdt**: structure pointer to the watchdog controller at the core layer.| –| HDF_STATUS| Feeds a watchdog. |
+
+
+## How to Develop
+
+The watchdog module adaptation involves the following steps:
+
+1. Instantiate the driver entry.
+ - Instantiate the **HdfDriverEntry** structure.
+ - Call **HDF_INIT** to register the **HdfDriverEntry** instance with the HDF.
+
+2. Configure attribute files.
+ - Add the **deviceNode** information to the **device_info.hcs** file.
+ - (Optional) Add the **watchdog_config.hcs** file.
+
+3. Instantiate the watchdog controller object.
+ - Initialize **WatchdogCntlr**.
+ - Instantiate **WatchdogMethod** in the **WatchdogCntlr** object.
+
+
+ >  **NOTE**
+ >
+ > For details about the functions in **WatchdogMethod**, see [Available APIs](#available-apis).
+
+4. Debug the driver.
+
+ (Optional) For new drivers, verify basic functions, for example, check the information returned after the driver is attached and whether the watchdog timer is successfully set.
+
+
+## Development Example
+
+The following uses **watchdog_hi35xx.c** as an example to present the information required for implementing device functions.
+
+1. Instantiate the driver entry.
+
+ The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
+
+ Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
+
+ Watchdog driver entry example:
+
+ ```
+ struct HdfDriverEntry g_watchdogDriverEntry = {
+ .moduleVersion = 1,
+ .Bind = Hi35xxWatchdogBind, // See the Bind function.
+ .Init = Hi35xxWatchdogInit, // See the Init function.
+ .Release = Hi35xxWatchdogRelease, // See the Release function.
+ .moduleName = "HDF_PLATFORM_WATCHDOG",// (Mandatory) The value must be the same as that of moduleName in the .hcs file.
+ };
+ HDF_INIT(g_watchdogDriverEntry);// Call HDF_INIT to register the driver entry with the HDF.
+ ```
+
+2. Add the **deviceNode** information to the **device_info.hcs** file and configure the component attributes in the **watchdog_config.hcs** file.
+
+ The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **WatchdogCntlr** members at the core layer.
+
+ In this example, there is only one watchdog controller. If there are multiple watchdog controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **watchdog_config** file for each controller.
+
+ - **device_info.hcs** configuration example:
+
+
+ ```
+ root {
+ device_info {
+ match_attr = "hdf_manager";
+ device_watchdog :: device {// Device node.
+ device0:: deviceNode { // Device node of the driver.
+ policy = 1; // Policy for the driver to provide services.
+ priority = 20; // Driver startup priority.
+ permission = 0644; // Permission to create device nodes for the driver.
+ moduleName = "HDF_PLATFORM_WATCHDOG";
+ // (Mandatory) Driver name. The value must be the same as that of moduleName in the driver entry structure.
+ serviceName = "HDF_PLATFORM_WATCHDOG_0";
+ // (Mandatory) Unique name of the service published by the driver.
+ deviceMatchAttr = "hisilicon_hi35xx_watchdog_0";
+ // (Mandatory) Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
+ }
+ }
+ }
+ }
+ ```
+
+ - **watchdog_config.hcs** configuration example:
+
+
+ ```
+ root {
+ platform {
+ template watchdog_controller {// (Mandatory) Template configuration. In the template, you can configure the common parameters shared by device nodes.
+ id = 0;
+ match_attr = "";
+ regBase = 0x12050000; // (Mandatory) Used for address mapping.
+ regStep = 0x1000; // (Mandatory) Used for address mapping.
+ }
+ controller_0x12050000 :: watchdog_controller {// (Mandatory) Keyword for matching the private data of the device driver.
+ match_attr = "hisilicon_hi35xx_watchdog_0"; // (Mandatory) The value must be the same as that of deviceMatchAttr in device_info.hcs.
+ }
+ // Configure this parameter when there are multiple watchdogs.
+ ...
+ }
+ }
+ ```
+
+3. Initialize the **WatchdogCntlr** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **WatchdogMethod** in **WatchdogCntlr** (so that the underlying driver functions can be called).
+ - Defining a custom structure
+
+ To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **watchdog_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the index and the number of pins, to the **WatchdogCntlr** object at the core layer.
+
+
+ ```
+ struct Hi35xxWatchdog {
+ struct WatchdogCntlr wdt; // (Mandatory) Carrier that connects the upper and underlying layers. For details, see the following description.
+ OsalSpinlock lock;
+ volatile unsigned char *regBase;// [Mandatory] Used for address mapping.
+ uint32_t phyBase; // (Mandatory) Used for address mapping.
+ uint32_t regStep; // (Mandatory) Used for address mapping.
+ };
+ // WatchdogCntlr is the core layer controller structure. The Init function assigns values to the members of WatchdogCntlr.
+ struct WatchdogCntlr {
+ struct IDeviceIoService service;// Driver service.
+ struct HdfDeviceObject *device; // Driver device.
+ OsalSpinlock lock; // This variable is called by the HDF core layer to implement the spinlock function.
+ struct WatchdogMethod *ops; // Callbacks.
+ int16_t wdtId // ID of the watchdog device.
+ void *priv; // Pointer to the driver's private data.
+ };
+ ```
+
+ - Instantiating **WatchdogMethod** in **WatchdogCntlr** (other members are initialized by **Init** and **Bind**)
+
+
+ ```
+ static struct WatchdogMethod g_method = {
+ .getStatus = Hi35xxWatchdogGetStatus,
+ .start = Hi35xxWatchdogStart,
+ .stop = Hi35xxWatchdogStop,
+ .setTimeout = Hi35xxWatchdogSetTimeout,
+ .getTimeout = Hi35xxWatchdogGetTimeout,
+ .feed = Hi35xxWatchdogFeed,
+ };
+ ```
+
+ - **Init** and **Bind** functions
+
+ Input parameter:
+
+ **HdfDeviceObject**, a device object created by the HDF for each driver, holds device-related private data and service APIs.
+
+ Return value:
+
+ HDF_STATUS
+
+ The table below lists some status. For more information, see **HDF_STATUS** in the /drivers/framework/include/utils/hdf_base.h file.
+
+ **Table 2** HDF_STATUS
+
+ | Status| Description|
+ | -------- | -------- |
+ | HDF_ERR_INVALID_OBJECT | Failed to locate the watchdog device.|
+ | HDF_ERR_MALLOC_FAIL | Failed to allocate memory.|
+ | HDF_ERR_IO | I/O error.|
+ | HDF_SUCCESS | Initialization successful.|
+ | HDF_FAILURE | Initialization failed.|
+
+ Function description:
+
+ Initializes the custom structure object and **WatchdogCntlr**, and calls the **WatchdogCntlrAdd** function at the core layer.
+
+
+ ```
+ // Generally, the Init function initializes the members of the Hi35xxWatchdog structure based on the attribute values in **HdfDeviceObject**.
+ // In this example, the Bind function initializes the Hi35xxWatchdog structure.
+ static int32_t Hi35xxWatchdogInit(struct HdfDeviceObject *device)
+ {
+ (void)device;
+ return HDF_SUCCESS;
+ }
+
+ static int32_t Hi35xxWatchdogBind(struct HdfDeviceObject *device)
+ {
+ int32_t ret;
+ struct Hi35xxWatchdog *hwdt = NULL;
+ ...
+ hwdt = (struct Hi35xxWatchdog *)OsalMemCalloc(sizeof(*hwdt));// Apply for memory for the Hi35xxWatchdog structure.
+ ...
+ hwdt->regBase = OsalIoRemap(hwdt->phyBase, hwdt->regStep); // Address mapping
+ ...
+ hwdt->wdt.priv = (void *)device->property;// (Optional) Assign the device attribute values to priv. However, priv is not called subsequently.
+ //If the priv member is required, instantiate getPriv() and releasePriv() of WatchdogMethod.
+ hwdt->wdt.ops = &g_method; // (Mandatory) Assign the instantiated objects to the ops members so that the top layer can invoke the WatchdogMethod functions.
+ hwdt->wdt.device = device; // (Mandatory) Enable conversion between HdfDeviceObject and WatchdogcCntlr.
+ ret = WatchdogCntlrAdd(&hwdt->wdt); // (Mandatory) Call this function to initialize the structure of the core layer. The driver accesses the platform core layer only after a success signal is returned.
+ if (ret != HDF_SUCCESS) { // If the operation fails, release the resources used by Init().
+ OsalIoUnmap((void *)hwdt->regBase);
+ OsalMemFree(hwdt);
+ return ret;
+ }
+ return HDF_SUCCESS;
+ }
+ ```
+
+ - **Release** function
+
+ Input parameter:
+
+ **HdfDeviceObject**, a device object created by the HDF for each driver, holds device-related private data and service APIs.
+
+ Return value:
+
+ No value is returned.
+
+ Function description:
+
+ Releases driver resources. This function assigns values to **Release()** in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, **Release()** can be called to release driver resources. The **Release()** function must contain the operations for releasing the memory and deleting the controller.
+
+ All forced conversion operations for obtaining the corresponding object can be successful only when **Init()** has the corresponding value assignment operations.
+
+
+ ```
+ static void Hi35xxWatchdogRelease(struct HdfDeviceObject *device)
+ {
+ struct WatchdogCntlr *wdt = NULL;
+ struct Hi35xxWatchdog *hwdt = NULL;
+ ...
+ wdt = WatchdogCntlrFromDevice(device);// Use service to convert HdfDeviceObject to WatchdogCntlr.
+ // return (device == NULL) ? NULL : (struct WatchdogCntlr *)device->service;
+ if (wdt == NULL) {
+ return;
+ }
+ WatchdogCntlrRemove(wdt); // Core layer function used to execute wdt->device->service = NULL and release cntlr->lock.
+ hwdt = (struct Hi35xxWatchdog *)wdt; // Convert WatchdogCntlr to HimciHost.
+ if (hwdt->regBase != NULL) { // Unmap addresses.
+ OsalIoUnmap((void *)hwdt->regBase);
+ hwdt->regBase = NULL;
+ }
+ OsalMemFree(hwdt); // Release the memory occupied by the vendor-defined objects.
+ }
+ ```
diff --git a/en/device-dev/driver/figures/spi-controller-device-connection.png b/en/device-dev/driver/figures/spi-controller-device-connection.png
index 96f68d24918dacf9244e0ad020f2e99d77f589c4..7a467a4d7278415cbd1174706b12cb9f598369b8 100644
Binary files a/en/device-dev/driver/figures/spi-controller-device-connection.png and b/en/device-dev/driver/figures/spi-controller-device-connection.png differ
diff --git a/en/device-dev/kernel/kernel-basic-mini-time.md b/en/device-dev/kernel/kernel-basic-mini-time.md
index 586349d0c4683c5b782b61ea2cd0b714e7b1b4b1..375e481f4c04354b83d1e043cac3d3f7f0a83c0c 100644
--- a/en/device-dev/kernel/kernel-basic-mini-time.md
+++ b/en/device-dev/kernel/kernel-basic-mini-time.md
@@ -1,8 +1,7 @@
-# Time Management
+# Time Management
-
-## Basic Concepts
+## Basic Concepts
Time management provides all time-related services for applications based on the system clock.
@@ -12,67 +11,79 @@ People use second or millisecond as the time unit, while the operating system us
The time management module of the OpenHarmony LiteOS-M kernel provides time conversion and statistics functions.
-## Time Unit
-- Cycle
+## Time Unit
+
+- Cycle
+
+ Cycle is the minimum time unit in the system. The cycle duration is determined by the system clock frequency, that is, the number of cycles per second.
+- Tick
+
+ Tick is the basic time unit of the operating system and is determined by the number of ticks per second configured by the user.
- Cycle is the minimum time unit in the system. The cycle duration is determined by the system clock frequency, that is, the number of cycles per second.
-- Tick
+## Available APIs
- Tick is the basic time unit of the operating system and is determined by the number of ticks per second configured by the user.
+The following table describes APIs available for OpenHarmony LiteOS-M time management. For more details about the APIs, see the API reference.
+**Table 1** APIs of the time management module
-## Available APIs
+| API| Description|
+| -------- | -------- |
+| LOS_MS2Tick | Converts milliseconds into ticks.|
+| LOS_Tick2MS | Converts ticks into milliseconds.|
+| OsCpuTick2MS | Converts cycles into milliseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
+| OsCpuTick2US | Converts cycles into microseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
-The following table describes APIs available for the OpenHarmony LiteOS-M time management. For more details about the APIs, see the API reference.
+**Table 2** APIs for time statistics
-**Table 1** APIs of the time management module
+| API| Description|
+| -------- | -------- |
+| LOS_SysClockGet | Obtains the system clock.|
+| LOS_TickCountGet | Obtains the number of ticks since the system starts.|
+| LOS_CyclePerTickGet | Obtains the number of cycles for each tick.|
-| Category| API| Description|
-| -------- | -------- | -------- |
-| Time conversion| LOS_MS2Tick | Converts milliseconds into ticks.|
-| | LOS_Tick2MS | Converts ticks into milliseconds.|
-| | OsCpuTick2MS | Converts cycles into milliseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
-| | OsCpuTick2US | Converts cycles into microseconds. Two UINT32 values indicate the high-order and low-order 32 bits of the result value, respectively.|
-| Time statistics| LOS_SysClockGet | Obtains the system clock.|
-| | LOS_TickCountGet | Obtains the number of ticks since the system starts.|
-| | LOS_CyclePerTickGet | Obtains the number of cycles for each tick.|
-| | LOS_CurrNanosec |Obtains the number of nanoseconds since the system starts.|
-| Delay management| LOS_UDelay |Performs busy waiting in μs, which can be preempted by a task with a higher priority.|
-| | LOS_MDelay |Performs busy waiting in ms, which can be preempted by a task with a higher priority.|
-## How to Develop
+## How to Develop
The typical development process of time management is as follows:
-1. Complete board configuration and adaptation as required, and configure the system clock frequency \(**OS\_SYS\_CLOCK** in Hz and **LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND**\). The default value of **OS\_SYS\_CLOCK** varies with the hardware platform.
-2. Call the clock conversion and statistics APIs.
+1. Complete board configuration and adaptation as required, and configure the system clock frequency (**OS_SYS_CLOCK** in Hz and **LOSCFG_BASE_CORE_TICK_PER_SECOND**). The default value of **OS_SYS_CLOCK** varies with the hardware platform.
-> **NOTE**
+2. Call the clock conversion and statistics APIs.
+
+> **NOTE**
>
->- The time management module depends on **OS\_SYS\_CLOCK** and **LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND**.
->- The number of system ticks is not counted when the interrupt feature is disabled. Therefore, the number of ticks cannot be used as the accurate time.
->- The configuration options are maintained in the **target\_config.h** file of the development board project.
+> - The time management module depends on **OS_SYS_CLOCK** and **LOSCFG_BASE_CORE_TICK_PER_SECOND**.
+>
+> - The number of system ticks is not counted when the interrupt feature is disabled. Therefore, the number of ticks cannot be used as the accurate time.
+>
+> - The configuration options are maintained in the **target_config.h** file of the development board project.
+
-## Development Example
+## Development Example
-### Example Description
+
+### Example Description
The following example describes basic time management methods, including:
- Time conversion: convert milliseconds to ticks or convert ticks to milliseconds.
+
- Time statistics: obtain the number of cycles per tick, number of ticks since system startup, and number of delayed ticks.
-### Sample Code
+
+### Sample Code
Prerequisites
-- The default value of **LOSCFG\_BASE\_CORE\_TICK\_PER\_SECOND** is **100**.
-- The system clock frequency **OS\_SYS\_CLOCK** is configured.
+- The default value of **LOSCFG_BASE_CORE_TICK_PER_SECOND** is **100**.
+
+- The system clock frequency **OS_SYS_CLOCK** is configured.
Time conversion:
+
```
VOID Example_TransformTime(VOID)
{
@@ -88,6 +99,7 @@ VOID Example_TransformTime(VOID)
Time statistics and delay:
+
```
VOID Example_GetTime(VOID)
{
@@ -112,12 +124,14 @@ VOID Example_GetTime(VOID)
}
```
-### Verification
+
+### Verification
The development is successful if the return result is as follows:
Time conversion:
+
```
tick = 1000
ms = 1000
@@ -125,6 +139,7 @@ ms = 1000
Time statistics and delay:
+
```
LOS_CyclePerTickGet = 495000
LOS_TickCountGet = 1
diff --git a/en/device-dev/kernel/kernel-mini-basic-soft.md b/en/device-dev/kernel/kernel-mini-basic-soft.md
index ec8e10ec130d2feb0d5c931b1ffbcccca56a7818..e6bb601669fcc6fd7403c25ccea520323eeea70d 100644
--- a/en/device-dev/kernel/kernel-mini-basic-soft.md
+++ b/en/device-dev/kernel/kernel-mini-basic-soft.md
@@ -1,5 +1,6 @@
# Software Timer
+
## Basic Concepts
The software timer is a software-simulated timer based on system tick interrupts. When the preset tick counter value has elapsed, the user-defined callback will be invoked. The timing precision is related to the cycle of the system tick clock.
@@ -8,144 +9,132 @@ Due to the limitation in hardware, the number of hardware timers cannot meet use
The software timer supports the following functions:
-- Disabling the software timer using a macro
-- Creating a software timer
-- Starting a software timer
-- Stopping a software timer
-- Deleting a software timer
-- Obtaining the number of remaining ticks of a software timer
+- Disabling the software timer using a macro
-## Working Principles
+- Creating a software timer
-The software timer is a system resource. When modules are initialized, a contiguous section of memory is allocated for software timers. The maximum number of timers supported by the system is configured by the **LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT** macro in **los\_config.h**.
+- Starting a software timer
-Software timers use a queue and a task resource of the system. The software timers are triggered based on the First In First Out \(FIFO\) rule. A timer with a shorter value is always closer to the queue head than a timer with a longer value, and is preferentially triggered.
+- Stopping a software timer
-The software timer counts time in ticks. When a software timer is created and started, the OpenHarmony LiteOS-M kernel determines the timer expiry time based on the current system time \(in ticks\) and the timing interval set by the user, and adds the timer control structure to the global timing list.
+- Deleting a software timer
-When a tick interrupt occurs, the tick interrupt handler scans the global timing list for expired timers. If such timers are found, the timers are recorded.
+- Obtaining the number of remaining ticks of a software timer
-When the tick interrupt handling function is complete, the software timer task \(with the highest priority\) is woken up. In this task, the timeout callback function for the recorded timer is called.
-### Timer States
+## Working Principles
-- OS\_SWTMR\_STATUS\_UNUSED
+The software timer is a system resource. When modules are initialized, a contiguous section of memory is allocated for software timers. The maximum number of timers supported by the system is configured by the **LOSCFG_BASE_CORE_SWTMR_LIMIT** macro in **los_config.h**.
- The timer is not in use. When the timer module is initialized, all timer resources in the system are set to this state.
+Software timers use a queue and a task resource of the system. The software timers are triggered based on the First In First Out (FIFO) rule. A timer with a shorter value is always closer to the queue head than a timer with a longer value, and is preferentially triggered.
+The software timer counts time in ticks. When a software timer is created and started, the OpenHarmony LiteOS-M kernel determines the timer expiry time based on the current system time (in ticks) and the timing interval set by the user, and adds the timer control structure to the global timing list.
-- OS\_SWTMR\_STATUS\_CREATED
+When a tick interrupt occurs, the tick interrupt handler scans the global timing list for expired timers. If such timers are found, the timers are recorded.
- The timer is created but not started or the timer is stopped. When **LOS\_SwtmrCreate** is called for a timer that is not in use or **LOS\_SwtmrStop** is called for a newly started timer, the timer changes to this state.
+When the tick interrupt handling function is complete, the software timer task (with the highest priority) is woken up. In this task, the timeout callback function for the recorded timer is called.
-- OS\_SWTMR\_STATUS\_TICKING
+### Timer States
- The timer is running \(counting\). When **LOS\_SwtmrStart** is called for a newly created timer, the timer enters this state.
+- OS_SWTMR_STATUS_UNUSED
+
+ The timer is not in use. When the timer module is initialized, all timer resources in the system are set to this state.
+- OS_SWTMR_STATUS_CREATED
+
+ The timer is created but not started or the timer is stopped. When **LOS_SwtmrCreate** is called for a timer that is not in use or **LOS_SwtmrStop** is called for a newly started timer, the timer changes to this state.
+
+- OS_SWTMR_STATUS_TICKING
+
+ The timer is running (counting). When **LOS_SwtmrStart** is called for a newly created timer, the timer enters this state.
-### Timer Modes
+### Timer Modes
-The OpenHarmony LiteOS-M kernel provides three types of software timers:
+The OpenHarmony LiteOS-M kernel provides the following types of software timers:
+
+- One-shot timer: Once started, the timer is automatically deleted after triggering only one timer event.
+
+- Periodic timer: This type of timer periodically triggers timer events until it is manually stopped.
+
+- One-shot timer deleted by calling an API
-- One-shot timer: Once started, the timer is automatically deleted after triggering only one timer event.
-- Periodic timer: This type of timer periodically triggers timer events until it is manually stopped.
-- One-shot timer deleted by calling an API
## Available APIs
The following table describes APIs available for the OpenHarmony LiteOS-M software timer module. For more details about the APIs, see the API reference.
-**Table 1** Software timer APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Creating or deleting timers
- |
-LOS_SwtmrCreate
- |
-Creates a software timer.
- |
-
-LOS_SwtmrDelete
- |
-Deletes a software timer.
- |
-
-Starting or stopping timers
- |
-LOS_SwtmrStart
- |
-Starts a software timer.
- |
-
-LOS_SwtmrStop
- |
-Stop a software timer.
- |
-
-Obtaining remaining ticks of a software timer
- |
-LOS_SwtmrTimeGet
- |
-Obtaining remaining ticks of a software timer
- |
-
-
-
+ **Table 1** Software timer APIs
+
+| API| Description|
+| -------- | -------- |
+| LOS_SwtmrCreate| Creates a timer.|
+| LOS_SwtmrDelete| Deletes a timer.|
+| LOS_SwtmrStart| Starts a timer.|
+| LOS_SwtmrStop| Stops a timer.|
+| LOS_SwtmrTimeGet| Obtains the remaining ticks of a software timer.|
+
## How to Develop
The typical development process of software timers is as follows:
-1. Configure the software timer.
- - Check that **LOSCFG\_BASE\_CORE\_SWTMR** and **LOSCFG\_BASE\_IPC\_QUEUE** are set to **1**.
- - Configure **LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT** \(maximum number of software timers supported by the system\).
- - Configure **OS\_SWTMR\_HANDLE\_QUEUE\_SIZE** \(maximum length of the software timer queue\).
+1. Configure the software timer.
+ - Check that **LOSCFG_BASE_CORE_SWTMR** and **LOSCFG_BASE_IPC_QUEUE** are set to **1**.
+ - Configure **LOSCFG_BASE_CORE_SWTMR_LIMIT** (maximum number of software timers supported by the system).
+ - Configure **OS_SWTMR_HANDLE_QUEUE_SIZE** (maximum length of the software timer queue).
+
+2. Call **LOS_SwtmrCreate** to create a software timer.
+ - Create a software timer with the specified timing duration, timeout handling function, and triggering mode.
+ - Return the function execution result (success or failure).
-2. Call **LOS\_SwtmrCreate** to create a software timer.
- - Create a software timer with the specified timing duration, timeout handling function, and triggering mode.
- - Return the function execution result \(success or failure\).
+3. Call **LOS_SwtmrStart** to start the software timer.
-3. Call **LOS\_SwtmrStart** to start the software timer.
-4. Call **LOS\_SwtmrTimeGet** to obtain the remaining number of ticks of the software timer.
-5. Call **LOS\_SwtmrStop** to stop the software timer.
-6. Call **LOS\_SwtmrDelete** to delete the software timer.
+4. Call **LOS_SwtmrTimeGet** to obtain the remaining number of ticks of the software timer.
+
+5. Call **LOS_SwtmrStop** to stop the software timer.
+
+6. Call **LOS_SwtmrDelete** to delete the software timer.
+
+> **NOTE**
+> - Avoid too many operations in the callback function of the software timer. Do not use APIs or perform operations that may cause task suspension or blocking.
+>
+> - The software timers use a queue and a task resource of the system. The priority of the software timer tasks is set to **0** and cannot be changed.
+>
+> - The number of software timer resources that can be configured in the system is the total number of software timer resources available to the entire system, not the number of software timer resources available to users. For example, if the system software timer occupies one more resource, the number of software timer resources available to users decreases by one.
+>
+> - If a one-shot software timer is created, the system automatically deletes the timer and reclaims resources after the timer times out and the callback function is executed.
+>
+> - For a one-shot software timer that will not be automatically deleted after expiration, you need to call **LOS_SwtmrDelete** to delete it and reclaim the timer resource to prevent resource leakage.
-> **NOTE**
->- Avoid too many operations in the callback function of the software timer. Do not use APIs or perform operations that may cause task suspension or blocking.
->- The software timers use a queue and a task resource of the system. The priority of the software timer tasks is set to **0** and cannot be changed.
->- The number of software timer resources that can be configured in the system is the total number of software timer resources available to the entire system, not the number of software timer resources available to users. For example, if the system software timer occupies one more resource, the number of software timer resources available to users decreases by one.
->- If a one-shot software timer is created, the system automatically deletes the timer and reclaims resources after the timer times out and the callback function is executed.
->- For a one-shot software timer that will not be automatically deleted after expiration, you need to call **LOS\_SwtmrDelete** to delete it and reclaim the timer resource to prevent resource leakage.
## Development Example
+
### Example Description
The following programming example demonstrates how to:
-1. Create, start, delete, pause, and restart a software timer.
-2. Use a one-shot software timer and a periodic software timer
+1. Create, start, delete, pause, and restart a software timer.
+
+2. Use a one-shot software timer and a periodic software timer
+
### Sample Code
Prerequisites
-- In **los\_config.h**, **LOSCFG\_BASE\_CORE\_SWTMR** is enabled.
-- In **los\_config.h**, **LOSCFG\_BASE\_CORE\_SWTMR\_ALIGN** is disabled. The sample code does not involve timer alignment.
-- The maximum number of software timers supported by the system \(**LOSCFG\_BASE\_CORE\_SWTMR\_LIMIT**\) is configured.
-- The maximum length of the software timer queue \(OS\_SWTMR\_HANDLE\_QUEUE\_SIZE\) is configured.
+- In **los_config.h**, **LOSCFG_BASE_CORE_SWTMR** is enabled.
+
+- In **los_config.h**, **LOSCFG_BASE_CORE_SWTMR_ALIGN** is disabled. The sample code does not involve timer alignment.
+
+- The maximum number of software timers supported by the system (**LOSCFG_BASE_CORE_SWTMR_LIMIT**) is configured.
+
+- The maximum length of the software timer queue (OS_SWTMR_HANDLE_QUEUE_SIZE) is configured.
The sample code is as follows:
+
```
#include "los_swtmr.h"
@@ -156,7 +145,7 @@ UINT32 g_timerCount2 = 0;
/* Task ID*/
UINT32 g_testTaskId01;
-void Timer1_Callback(UINT32 arg) //Callback function 1
+void Timer1_Callback(UINT32 arg) //Callback 1
{
UINT32 tick_last1;
g_timerCount1++;
@@ -164,7 +153,7 @@ void Timer1_Callback(UINT32 arg) //Callback function 1
printf("g_timerCount1=%d, tick_last1=%d\n", g_timerCount1, tick_last1);
}
-void Timer2_Callback(UINT32 arg) //Callback function 2
+void Timer2_Callback(UINT32 arg) //Callback 2
{
UINT32 tick_last2;
tick_last2 = (UINT32)LOS_TickCountGet();
@@ -237,10 +226,12 @@ UINT32 Example_TaskEntry(VOID)
}
```
+
### Verification
The output is as follows:
+
```
create Timer1 success
start Timer1 success
@@ -261,4 +252,3 @@ g_timerCount2=9 tick_last2=2113
g_timerCount2=10 tick_last2=2213
delete Timer2 success
```
-
diff --git a/en/device-dev/kernel/kernel-mini-basic-task.md b/en/device-dev/kernel/kernel-mini-basic-task.md
index b431d06f674446fe4d0ac7c990eea128d641f7af..e2b71e961f6335ce9da5485e8b025b0df88e7308 100644
--- a/en/device-dev/kernel/kernel-mini-basic-task.md
+++ b/en/device-dev/kernel/kernel-mini-basic-task.md
@@ -1,65 +1,68 @@
# Task Management
+
## Basic Concepts
From the perspective of the operating system, tasks are the minimum running units that compete for system resources. They can use or wait for CPUs, use system resources such as memory, and run independently.
The task module of the OpenHarmony LiteOS-M provides multiple tasks and supports switching between tasks, helping users manage business process procedures. The task module has the following features:
-- Multiple tasks are supported.
-- A task represents a thread.
-- The preemptive scheduling mechanism is used for tasks. High-priority tasks can interrupt low-priority tasks. Low-priority tasks can be scheduled only after high-priority tasks are blocked or complete.
-- Time slice round-robin is used to schedule tasks with the same priority.
-- A total of 32 \(**0** to **31**\) priorities are defined. **0** is the highest priority, and **31** is the lowest.
-
-### Task-related Concepts
-
-**Task States**
-
-A task has multiple states. After the system initialization is complete, the created tasks can compete for certain resources in the system according to the scheduling procedure regulated by the kernel.
-
-A task can be in any of the following states:
-
-- Ready: The task is in the ready queue, waiting for execution by a CPU.
-- Running: The task is being executed.
-- Blocked: The task is not in the ready queue. The task may be suspended, delayed, waiting for a semaphore, waiting to read from or write into a queue, or reading from or writing into an event.
-- Dead: The task execution is complete and waiting for the system to reclaim resources.
-
-**Task State Transitions**
-
-**Figure 1** Task state transitions
-
-
-The task transition process is as follows:
+- Multiple tasks are supported.
-- Ready → Running
+- A task represents a thread.
- A task enters Ready state once created. When task switching occurs, the task with the highest priority in the Ready queue will be executed. The task being executed enters the Running state and is removed from the Ready queue.
+- The preemptive scheduling mechanism is used for tasks. High-priority tasks can interrupt low-priority tasks. Low-priority tasks can be scheduled only after high-priority tasks are blocked or complete.
-- Running → Blocked
+- Time slice round-robin is used to schedule tasks with the same priority.
- When a running task is blocked \(suspended, delayed, or reading semaphores\), it will be inserted to the blocked task queue and changes from the Running state to the Blocked state. Then, task switching is triggered to run the task with the highest priority in the Ready queue.
+- A total of 32 (**0** to **31**) priorities are defined. **0** is the highest priority, and **31** is the lowest.
-- Blocked → Ready \(Blocked → Running\)
- When a blocked task is recovered \(for example, the task is resumed, the delay period or semaphore read period times out, or the task successfully reads a semaphore\), the task will be added to the Ready queue and change from the Blocked state to the Ready state. If the priority of the recovered task is higher than that of the running task, task switching will be triggered to run the recovered task. Then, the task changes from the Ready state to the Running state.
+### Task-related Concepts
-- Ready → Blocked
+**Task States**
- When a task in the Ready state is blocked \(suspended\), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered.
+A task has multiple states. After the system initialization is complete, the created tasks can compete for certain resources in the system according to the scheduling procedure regulated by the kernel.
-- Running → Ready
+A task can be in any of the following states:
- When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and remains in the Ready queue.
+- Ready: The task is in the ready queue, waiting for execution by a CPU.
-- Running → Dead
+- Running: The task is being executed.
- When a running task is complete, it changes to the Dead state. The Dead state includes normal exit state as the task is complete and the Invalid state. For example, if a task is complete but is not automatically deleted, the task is in the Invalid state.
+- Blocked: The task is not in the ready queue. The task may be suspended, delayed, waiting for a semaphore, waiting to read from or write into a queue, or reading from or writing into an event.
-- Blocked → Dead
+- Dead: The task execution is complete and waiting for the system to reclaim resources.
- If an API is called to delete a blocked task, the task state change from Blocked to Dead.
+**Task State Transitions**
+**Figure 1** Task state transition
+
+ 
+
+The task state transition process is as follows:
+
+- Ready → Running
+
+ A task enters Ready state once created. When task switching occurs, the task with the highest priority in the Ready queue will be executed. The task being executed enters the Running state and is removed from the Ready queue.
+- Running → Blocked
+
+ When a running task is blocked (suspended, delayed, or reading semaphores), it will be inserted to the blocked task queue and changes from the Running state to the Blocked state. Then, task switching is triggered to run the task with the highest priority in the Ready queue.
+- Blocked → Ready (Blocked → Running)
+
+ When a blocked task is recovered (for example, the task is resumed, the delay period or semaphore read period times out, or the task successfully reads a semaphore), the task will be added to the Ready queue and change from the Blocked state to the Ready state. If the priority of the recovered task is higher than that of the running task, task switching will be triggered to run the recovered task. Then, the task changes from the Ready state to the Running state.
+- Ready → Blocked
+
+ When a task in the Ready state is blocked (suspended), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered.
+- Running → Ready
+
+ When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and remains in the Ready queue.
+- Running → Dead
+
+ When a running task is complete, it changes to the Dead state. The Dead state includes normal exit state as the task is complete and the Invalid state. For example, if a task is complete but is not automatically deleted, the task is in the Invalid state.
+- Blocked → Dead
+
+ If an API is called to delete a blocked task, the task state change from Blocked to Dead.
**Task ID**
@@ -83,81 +86,84 @@ Resources, such as registers, used during the running of a task. When a task is
**Task Control Block**
-Each task has a task control block \(TCB\). A TCB contains task information, such as context stack pointer, state, priority, ID, name, and stack size. The TCB reflects the running status of a task.
+Each task has a task control block (TCB). A TCB contains task information, such as context stack pointer, state, priority, ID, name, and stack size. The TCB reflects the running status of a task.
**Task Switching**
Task switching involves actions, such as obtaining the task with the highest priority in the Ready queue, saving the context of the switched-out task, and restoring the context of the switched-in task.
-### Task Running Mechanism
+
+### Task Running Mechanism
When a task is created, the system initializes the task stack and presets the context. The system places the task entry function in the corresponding position so that the function is executed when the task enters the running state for the first time.
+
## Available APIs
The following table describes APIs available for the OpenHarmony LiteOS-M task module. For more details about the APIs, see the API reference.
-**Table 1** APIs of the task management module
-
-| Category| API| Description|
-| -------- | -------- | -------- |
-| Creating or deleting a task| LOS_TaskCreateOnly | Creates a task and suspends the task to disable scheduling of the task. To enable scheduling of the task, call **LOS_TaskResume** to make the task enter the Ready state.|
-| | LOS_TaskCreate | Creates a task and places the task in the Ready state. If there is no task with a higher priority in the Ready queue, the task will be executed.|
-| | LOS_TaskDelete | Deletes a task.|
-| Controlling task status| LOS_TaskResume | Resumes a suspended task to place it in the Ready state.|
-| | LOS_TaskSuspend | Suspends the specified task and performs task switching.|
-| | LOS_TaskJoin | Suspends this task till the specified task is complete and the task control block resources are reclaimed.|
-| | LOS_TaskDetach | Changes the task attribute from **joinable** to **detach**. After the task of the **detach** attribute is complete, the task control block resources will be automatically reclaimed.|
-| | LOS_TaskDelay | Makes a task wait for a period of time (in ticks) and releases CPU resources. When the delay time expires, the task enters the Ready state again. The input parameter is the number of ticks.|
-| | LOS_Msleep | Converts the input number of milliseconds into number of ticks, and use the result to call **LOS_TaskDelay**.|
-| | LOS_TaskYield | Sets the time slice of the current task to **0** to release CPU resources and schedule the task with the highest priority in the Ready queue to run.|
-| Controlling task scheduling| LOS_TaskLock | Locks task scheduling. However, tasks can still be interrupted.|
-| | LOS_TaskUnlock | Unlocks task scheduling.|
-| | LOS_Schedule | Triggers task scheduling|
-| Controlling task priority| LOS_CurTaskPriSet | Sets the priority for the current task.|
-| | LOS_TaskPriSet | Sets the priority for a specified task.|
-| | LOS_TaskPriGet | Obtains the priority of a specified task.|
-| Obtaining Job information| LOS_CurTaskIDGet | Obtains the ID of the current task.|
-| | LOS_NextTaskIDGet | Obtains the ID of the task with the highest priority in the Ready queue.|
-| | LOS_NewTaskIDGet | Same as **LOS_NextTaskIDGet**.|
-| | LOS_CurTaskNameGet | Obtains the name of the current task.|
-| | LOS_TaskNameGet | Obtains the name of a specified task.|
-| | LOS_TaskStatusGet | Obtains the state of a specified task.|
-| | LOS_TaskInfoGet | Obtains information about a specified task, including the task state, priority, stack size, stack pointer (SP), task entry function, and used stack space.|
-| | LOS_TaskIsRunning | Checks whether the task module has started scheduling.|
-| Updating task information| LOS_TaskSwitchInfoGet | Obtains task switching information. The macro **LOSCFG_BASE_CORE_EXC_TSK_SWITCH** must be enabled.|
-| Reclaiming task stack resources| LOS_TaskResRecycle | Reclaims all task stack resources.|
+ **Table 1** APIs of the task management module
+
+| Category| Description|
+| -------- | -------- |
+| Creating or deleting a task| **LOS_TaskCreateOnly**: creates a task and places the task in the Ready state. If there is no task with a higher priority in the Ready queue, the task will be executed.
**LOS_TaskCreate**: creates a task and places the task in the Ready state. If there is no task with a higher priority in the Ready queue, the task will be executed.
**LOS_TaskDelete**: deletes a task.|
+| Controlling task status| **LOS_TaskResume**: resumes a suspended task to place the task in the Ready state.
**LOS_TaskSuspend**: suspends the specified task and performs task switching.
**LOS_TaskJoin**: suspends this task till the specified task is complete and the task control block resources are reclaimed.
**LOS_TaskDelay**: makes a task wait for a period of time (in ticks) and releases CPU resources. When the delay timer expires, the task enters the Ready state again. The input parameter is the number of ticks.
**LOS_Msleep**: converts the input parameter number of milliseconds into number of ticks, and use the result to call **LOS_TaskDelay**.
**LOS_TaskYield**: sets the time slice of the current task to **0** to release CPU resources and schedule the task with the highest priority in the Ready queue to run.|
+| Controlling task scheduling| **LOS_TaskLock**: locks task scheduling. However, tasks can still be interrupted.
**LOS_TaskUnlock**: unlocks task scheduling.
**LOS_Schedule**: triggers task scheduling.|
+| Controlling task priority| **LOS_CurTaskPriSet**: sets the priority for the current task.
**LOS_TaskPriSet**: sets the priority for a specified task.
**LOS_TaskPriGet**: obtains the priority of a specified task.|
+| Obtaining Job information| **LOS_CurTaskIDGet**: obtains the ID of the current task.
**LOS_NextTaskIDGet**: obtains the ID of the task with the highest priority in the Ready queue.
**LOS_NewTaskIDGet**: equivalent to **LOS_NextTaskIDGet**.
**LOS_CurTaskNameGet**: obtains the name of the current task.
**LOS_TaskNameGet**: obtains the name of a task.
**LOS_TaskStatusGet**: obtains the state of a task.
**LOS_TaskInfoGet**: obtains information about a specified task, including the task state, priority, stack size, stack pointer (SP), task entry function, and used stack space.
**LOS_TaskIsRunning**: checks whether the task module has started scheduling.|
+| Updating task information| **LOS_TaskSwitchInfoGet**: obtains task switching information. The macro **LOSCFG_BASE_CORE_EXC_TSK_SWITCH** must be enabled.|
## How to Develop
The typical development process of the task module is as follows:
-1. Use **LOS\_TaskLock** to lock task scheduling and prevent high-priority tasks from being scheduled.
-2. Use **LOS\_TaskCreate** to create a task.
-3. Use **LOS\_TaskUnlock** to unlock task scheduling so that tasks can be scheduled by priority.
-4. Use **LOS\_TaskDelay** to delay a task.
-5. Use **LOS\_TaskSuspend** to suspend a task.
-6. Use **LOS\_TaskResume** to resume the suspended task.
-
-> **NOTE**
->- Running idle tasks reclaims the TCBs and stacks in the to-be-recycled linked list.
->- The task name is a pointer without memory space allocated. When setting the task name, do not assign the local variable address to the task name pointer.
->- The task stack size is 8-byte aligned. Follow the "nothing more and nothing less" principle while determining the task stack size.
->- A running task cannot be suspended if task scheduling is locked.
->- Idle tasks and software timer tasks cannot be suspended or deleted.
->- In an interrupt handler or when a task is locked, the operation of calling **LOS\_TaskDelay** fails.
->- Locking task scheduling does not disable interrupts. Tasks can still be interrupted while task scheduling is locked.
->- Locking task scheduling must be used together with unlocking task scheduling.
->- Task scheduling may occur while a task priority is being set.
->- The maximum number of tasks that can be set for the operating system is the total number of tasks of the operating system, not the number of tasks available to users. For example, if the system software timer occupies one more task resource, the number of task resources available to users decreases by one.
->- **LOS\_CurTaskPriSet** and **LOS\_TaskPriSet** cannot be used in interrupts or used to modify the priorities of software timer tasks.
->- If the task corresponding to the task ID sent to **LOS\_TaskPriGet** has not been created or the task ID exceeds the maximum number of tasks, **-1** will be returned.
->- Resources such as a mutex or a semaphore allocated to a task must have been released before the task is deleted.
+1. Use **LOS_TaskLock** to lock task scheduling and prevent high-priority tasks from being scheduled.
+
+2. Use **LOS_TaskCreate** to create a task.
+
+3. Use **LOS_TaskUnlock** to unlock task scheduling so that tasks can be scheduled by priority.
+
+4. Use **LOS_TaskDelay** to delay a task.
+
+5. Use **LOS_TaskSuspend** to suspend a task.
+
+6. Use **LOS_TaskResume** to resume the suspended task.
+
+> **NOTE**
+> - Running idle tasks reclaims the TCBs and stacks in the to-be-recycled linked list.
+>
+> - The task name is a pointer without memory space allocated. When setting the task name, do not assign the local variable address to the task name pointer.
+>
+> - The task stack size is 8-byte aligned. Follow the "nothing more and nothing less" principle while determining the task stack size.
+>
+> - A running task cannot be suspended if task scheduling is locked.
+>
+> - Idle tasks and software timer tasks cannot be suspended or deleted.
+>
+> - In an interrupt handler or when a task is locked, the operation of calling **LOS_TaskDelay** fails.
+>
+> - Locking task scheduling does not disable interrupts. Tasks can still be interrupted while task scheduling is locked.
+>
+> - Locking task scheduling must be used together with unlocking task scheduling.
+>
+> - Task scheduling may occur while a task priority is being set.
+>
+> - The maximum number of tasks that can be set for the operating system is the total number of tasks of the operating system, not the number of tasks available to users. For example, if the system software timer occupies one more task resource, the number of task resources available to users decreases by one.
+>
+> - **LOS_CurTaskPriSet** and **LOS_TaskPriSet** cannot be used in interrupts or used to modify the priorities of software timer tasks.
+>
+> - If the task corresponding to the task ID sent to **LOS_TaskPriGet** has not been created or the task ID exceeds the maximum number of tasks, **-1** will be returned.
+>
+> - Resources such as a mutex or a semaphore allocated to a task must have been released before the task is deleted.
+
## Development Example
-This example describes the priority-based task scheduling and use of task-related APIs, including creating, delaying, suspending, and resuming two tasks with different priorities, and locking/unlocking task scheduling. The sample code is as follows:
+This example describes the priority-based task scheduling and use of task-related APIs, including creating, delaying, suspending, and resuming two tasks with different priorities, and locking/unlocking task scheduling.
+
+The sample code is as follows:
+
```
UINT32 g_taskHiId;
@@ -249,7 +255,7 @@ UINT32 Example_TskCaseEntry(VOID)
initParam.pcName = "TaskLo";
initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
- /*Create a low-priority task. The task will not be executed immediately after being created, because task scheduling is locked. */
+ /* Create a low-priority task. The task will not be executed immediately after being created, because task scheduling is locked. */
ret = LOS_TaskCreate(&g_taskLoId, &initParam);
if (ret != LOS_OK) {
LOS_TaskUnlock();
@@ -271,10 +277,12 @@ UINT32 Example_TskCaseEntry(VOID)
}
```
+
### Verification
The development is successful if the return result is as follows:
+
```
LOS_TaskLock() Success!
Example_TaskHi create Success!
diff --git a/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md b/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md
index 1bf198e1fa337518d06a4062c74a2cf290630b4c..3e6ab8c31e41128a1f15f10a2d396cb74dd7bc7f 100644
--- a/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md
+++ b/en/device-dev/kernel/kernel-mini-extend-dynamic-loading.md
@@ -1,17 +1,26 @@
# Dynamic Loading
+
## Basic Concepts
-In small devices with limited hardware resources, dynamic algorithm deployment capability is required to solve the problem that multiple algorithms cannot be deployed at the same time. The LiteOS-M kernel uses the Executable and Linkable Format \(ELF\) loading because it is easy to use and compatible with a wide variety of platforms. The LiteOS-M provides APIs similar to **dlopen** and **dlsym**. Apps can load and unload required algorithm libraries by using the APIs provided by the dynamic loading module. As shown in the following figure, the app obtains the corresponding information output through the API required by the third-party algorithm library. The third-party algorithm library depends on the basic APIs provided by the kernel, such as **malloc**. After the app loads the API and relocates undefined symbols, it can call the API to complete the function. The dynamic loading component supports only the Arm architecture. In addition, the signature and source of the shared library to be loaded must be verified to ensure system security.
+In small devices with limited hardware resources, dynamic algorithm deployment capability is required to allow multiple algorithms to be deployed at the same time. The LiteOS-M kernel uses the Executable and Linkable Format (ELF) loading because it is easy to use and compatible with a wide variety of platforms.
+
+The LiteOS-M provides APIs similar to **dlopen** and **dlsym**. Apps can load and unload required algorithm libraries by using the APIs provided by the dynamic loading module. As shown in the following figure, the app obtains the corresponding information output through the API required by the third-party algorithm library. The third-party algorithm library depends on the basic APIs provided by the kernel, such as **malloc**. After the app loads the API and relocates undefined symbols, it can call the API to complete the function.
+
+The dynamic loading component supports only the Arm architecture. In addition, the signature and source of the shared library to be loaded must be verified to ensure system security.
+
+ **Figure 1** LiteOS-M kernel dynamic loading architecture
+
+ 
-**Figure 1** LiteOS-M kernel dynamic loading architecture
-
## Working Principles
+
### Exporting the Symbol Table
-The kernel needs to proactively expose the API required by the dynamic library when the shared library calls a kernel API, as shown in the following figure. This mechanism compiles the symbol information to the specified section and calls the **SYM\_EXPORT** macro to export information of the specified symbol. The symbol information is described in the structure **SymInfo**. Its members include the symbol name and symbol address information. The macro **SYM\_EXPORT** imports the symbol information to the **.sym.\*** section by using the **\_\_attribute\_\_** compilation attribute.
+The kernel needs to proactively expose the API required by the dynamic library when the shared library calls a kernel API, as shown in the following figure. This mechanism compiles the symbol information to the specified section and calls the **SYM_EXPORT** macro to export information of the specified symbol. The symbol information is described in the structure **SymInfo**, which includes the symbol name and address information. The macro **SYM_EXPORT** imports the symbol information to the **.sym.*** section by using **__attribute__**.
+
```
typedef struct {
@@ -26,12 +35,15 @@ const SymInfo sym_##func __attribute__((section(".sym."#func))) = { \
};
```
-**Figure 2** Exported symbol table information
-
+ **Figure 2** Exported symbol table
+
+ 
+
### Loading an ELF File
-During the loading process, the LOAD section to be loaded to the memory is obtained based on the ELF file handle and the section offset of the program header table. Generally, there are two sections: read-only section and read-write section. You can run the **readelf -l** command to view the LOAD section information of the ELF file. The physical memory is requested according to the related alignment attributes. Then, a code section or a data segment is written into the memory based on the loading base address and an offset of each section.
+The **LOAD** section to be loaded to the memory can be obtained based on the ELF file handle and the section offset of the program header table. Generally, there are two sections: read-only and read-write. You can run the **readelf -l** command to view the LOAD section information of the ELF file. The physical memory is requested according to the related alignment attributes. Then, a code section or a data segment is written into the memory based on the loading base address and an offset of each section.
+
```
$ readelf -l lib.so
@@ -43,8 +55,7 @@ There are 4 program headers, starting at offset 52
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
EXIDX 0x000760 0x00000760 0x00000760 0x00008 0x00008 R 0x4
- LOAD 0x000000 0x00000000 0x00000000 0x0076c 0x0076c R E 0x10000
- LOAD 0x00076c 0x0001076c 0x0001076c 0x0010c 0x00128 RW 0x10000
+ LOAD 0x000000 0x00000000 0x00000000 0x0076c 0x0076c R E 0x10000LOAD 0x00076c 0x0001076c 0x0001076c 0x0010c 0x00128 RW 0x10000
DYNAMIC 0x000774 0x00010774 0x00010774 0x000c8 0x000c8 RW 0x4
Section to Segment mapping:
@@ -55,29 +66,45 @@ Program Headers:
03 .dynamic
```
-**Figure 3** Process of loading an ELF file
-
+ **Figure 3** Process of loading an ELF file
+ 
+
-### ELF File Link
+### ELF File Linking
A relocation table is obtained by using a **.dynamic** section of the ELF file. Each entry that needs to be relocated in the table is traversed. Then, the symbol is searched, based on the symbol name that needs to be relocated, in the shared library and the exported symbol table provided by the kernel. The relocation information is updated based on the symbol found.
-**Figure 4** ELF file linking process
-
+ **Figure 4** ELF file linking process
+
+ 
+
## ELF Specifications
+
### ELF Type
-When compiling a shared library, you can add **-fPIC** \(a compilation option\) to compile location-independent code. The shared library file type is **ET\_DYN**, which can be loaded to any valid address range.
+When compiling a shared library, you can add **-fPIC** (a compilation option) to compile location-independent code. The shared library file type is **ET_DYN**, which can be loaded to any valid address range.
Example: **arm-none-eabi-gcc -fPIC –shared –o lib.so lib.c**
+
### Options for Linking
-1. **-nostdlib**: Do not use the lib library in the compiler when linking.
-2. **-nostartfiles**: Do not use the startup files in the compiler when linking.
-3. **-fPIC**: compiles location-independent shared libraries.
-4. **-z max-page-size=4**: sets the number of alignment bytes of the loadable sections in the binary file to **4**. This setting saves memory and can be used for a dynamic library.
-5. **-mcpu=** specifies the CPU architecture.
+- **-nostdlib**: Do not use the lib library in the compiler when linking.
+
+- **-nostartfiles**: Do not use the startup files in the compiler when linking.
+
+- **-fPIC**: compiles location-independent shared libraries.
+
+- **-z max-page-size=4**: sets the number of alignment bytes of the loadable sections in the binary file to **4**. This setting saves memory and can be used for a dynamic library.
+
+- **-mcpu=** specifies the CPU architecture.
+
+
+## Constraints
+
+- Applications cannot be loaded. Only shared libraries can be loaded.
+- The shared library to be loaded cannot depend on the libc library or other shared libraries in the compiler. It can depend only on the external APIs provided by the kernel (provided by the exported symbol table).
+- This feature depends on the cross compiler and file system.
diff --git a/en/device-dev/kernel/kernel-mini-extend-file-fat.md b/en/device-dev/kernel/kernel-mini-extend-file-fat.md
index 5f191076a6e75743b254e0b8611698de701bb8e0..b7a9bffdd5e106d1afedff3f960b4f29d9b8dca2 100644
--- a/en/device-dev/kernel/kernel-mini-extend-file-fat.md
+++ b/en/device-dev/kernel/kernel-mini-extend-file-fat.md
@@ -1,20 +1,27 @@
# FAT
+
## Basic Concepts
-File Allocation Table \(FAT\) is a file system developed for personal computers. It consists of the DOS Boot Record \(DBR\) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system supports multiple media, especially removable media \(such as USB flash drives, SD cards, and removable hard drives\). The FAT file system ensures good compatibility between embedded devices and desktop systems \(such as Windows and Linux\) and facilitates file management.
+File Allocation Table (FAT) is a file system developed for personal computers. It consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster.
+
+The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, respectively. The FAT file system supports multiple media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). The FAT file system ensures good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management.
The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary partition and logical partition.
+
## Development Guidelines
-### Adaptation of Drivers
-The use of the FAT file system requires support from the underlying MultiMediaCard \(MMC\) drivers. To run FatFS on a board with an MMC storage device, you must:
+### Driver Adaptation
+
+The use of the FAT file system requires support from the underlying MultiMedia Card (MMC) drivers. To run FatFS on a board with an MMC storage device, you must:
-1. Implement the **disk\_status**, **disk\_initialize**, **disk\_read**, **disk\_write**, and **disk\_ioctl** APIs to adapt to the embedded MMC \(eMMC\) drivers on the board.
+1. Implement the **disk_status**, **disk_initialize**, **disk_read**, **disk_write**, and **disk_ioctl** APIs to adapt to the embedded MMC (eMMC) drivers on the board.
+2. Add the **fs_config.h** file with information such as **FS_MAX_SS** (maximum sector size of the storage device) and **FF_VOLUME_STRS** (partition names) configured.
+
+The following is an example:
-2. Add the **fs\_config.h** file with information such as **FS\_MAX\_SS** \(maximum sector size of the storage device\) and **FF\_VOLUME\_STRS** \(partition names\) configured. The following is an example:
```
#define FF_VOLUME_STRS "system", "inner", "update", "user"
@@ -22,63 +29,70 @@ The use of the FAT file system requires support from the underlying MultiMediaCa
#define FAT_MAX_OPEN_FILES 50
```
+
### How to Develop
-> **NOTE**
->- Note the following when managing FatFS files and directories:
-> - A file cannot exceed 4 GB.
-> - **FAT\_MAX\_OPEN\_FILES** specifies the maximum number files you can open at a time, and **FAT\_MAX\_OPEN\_DIRS** specifies the maximum number of folders you can open at a time.
-> - Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the file or directory **testfile** in the **user** partition.
-> - To open a file multiple times, use **O\_RDONLY** \(read-only mode\). **O\_RDWR** or **O\_WRONLY** \(writable mode\) can open a file only once.
-> - The read and write pointers are not separated. If a file is open in **O\_APPEND** mode, the read pointer is also at the end of the file. If you want to read the file from the beginning, you must manually set the position of the read pointer.
-> - File and directory permission management is not supported.
-> - The **stat** and **fstat** APIs do not support query of the modification time, creation time, and last access time. The Microsoft FAT protocol does not support time before A.D. 1980.
->- Note the following when mounting and unmounting FatFS partitions:
-> - Partitions can be mounted with the read-only attribute. When the input parameter of the **mount** function is **MS\_RDONLY**, all APIs with the write attribute, such as **write**, **mkdir**, **unlink**, and **open** with **non-O\_RDONLY** attributes, will be rejected.
-> - You can use the **MS\_REMOUNT** flag with **mount** to modify the permission for a mounted partition.
-> - Before unmounting a partition, ensure that all directories and files in the partition are closed.
-> - You can use **umount2** with the **MNT\_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when running **umount2**.
->- The FAT file system supports re-partitioning and formatting of storage devices using **fatfs\_fdisk** and **fatfs\_format**.
-> - If a partition is mounted before being formatted using **fatfs\_format**, you must close all directories and files in the partition and unmount the partition first.
-> - Before calling **fatfs\_fdisk**, ensure that all partitions in the device are unmounted.
-> - Using **fatfs\_fdisk** and **fatfs\_format** may cause data loss. Exercise caution when using them.
+>  **NOTE**
+>
+> Note the following when managing FatFS files and directories:
+> - A file cannot exceed 4 GB.
+> - **FAT\_MAX\_OPEN\_FILES** specifies the maximum number files you can open at a time, and **FAT\_MAX\_OPEN\_DIRS** specifies the maximum number of folders you can open at a time.
+> - Root directory management is not supported. File and directory names start with the partition name. For example, **user/testfile** indicates the file or directory **testfile** in the **user** partition.
+> - To open a file multiple times, use **O_RDONLY** (read-only mode). **O_RDWR** or **O_WRONLY** (writable mode) can open a file only once.
+> - The read and write pointers are not separated. If a file is open in **O_APPEND** mode, the read pointer is also at the end of the file. If you want to read the file from the beginning, you must manually set the position of the read pointer.
+> - File and directory permission management is not supported.
+> - The **stat** and **fstat** APIs do not support query of the modification time, creation time, and last access time. The Microsoft FAT protocol does not support time before A.D. 1980.
+>
+> Note the following when mounting and unmounting FatFS partitions:
+> - Partitions can be mounted with the read-only attribute. When the input parameter of the **mount** function is **MS_RDONLY**, all APIs with the write attribute, such as **write**, **mkdir**, **unlink**, and **open** with **non-O_RDONLY** attributes, will be rejected.
+> - You can use the **MS_REMOUNT** flag with **mount** to modify the permission for a mounted partition.
+> - Before unmounting a partition, ensure that all directories and files in the partition are closed.
+> - You can use **umount2** with the **MNT_FORCE** parameter to forcibly close all files and folders and unmount the partition. However, this may cause data loss. Therefore, exercise caution when running **umount2**.
+>
+> The FAT file system supports re-partitioning and formatting of storage devices using **fatfs_fdisk** and **fatfs_format**.
+> - If a partition is mounted before being formatted using **fatfs_format**, you must close all directories and files in the partition and unmount the partition first.
+> - Before calling **fatfs_fdisk**, ensure that all partitions in the device are unmounted.
+> - Using **fatfs_fdisk** and **fatfs_format** may cause data loss. Exercise caution when using them.
+
## Development Example
+
### Example Description
This example implements the following:
-1. Create the **user/test** directory.
-2. Create the **file.txt** file in the **user/test** directory.
-3. Write "Hello OpenHarmony!" at the beginning of the file.
-4. Save the update of the file to the device.
-5. Set the offset to the beginning of the file.
-6. Read the file.
-7. Close the file.
-8. Delete the file.
-9. Delete the directory.
+1. Create the **user/test** directory.
+2. Create the **file.txt** file in the **user/test** directory.
+3. Write **Hello OpenHarmony!** at the beginning of the file.
+4. Save the file to a device.
+5. Set the offset to the start position of the file.
+6. Read the file.
+7. Close the file.
+8. Delete the file.
+9. Delete the directory.
+
### Sample Code
-Prerequisites
+**Prerequisites**
-- The MMC device partition is mounted to the **user** directory.
+The MMC device partition is mounted to the **user** directory.
-The sample code is as follows:
+ The sample code is as follows:
-```
-#include
-#include
-#include "sys/stat.h"
-#include "fcntl.h"
-#include "unistd.h"
+ ```
+ #include
+ #include
+ #include "sys/stat.h"
+ #include "fcntl.h"
+ #include "unistd.h"
-#define LOS_OK 0
-#define LOS_NOK -1
+ #define LOS_OK 0
+ #define LOS_NOK -1
-int FatfsTest(void)
-{
+ int FatfsTest(void)
+ {
int ret;
int fd = -1;
ssize_t len;
@@ -88,14 +102,14 @@ int FatfsTest(void)
char writeBuf[20] = "Hello OpenHarmony!";
char readBuf[20] = {0};
- /* Create the user/test directory.*/
+ /* Create the user/test directory. */
ret = mkdir(dirName, 0777);
if (ret != LOS_OK) {
printf("mkdir failed.\n");
return LOS_NOK;
}
- /* Create the file user/test/file.txt and make it readable and writable.*/
+ /* Create a readable and writable file named file.txt in the user/test/ directory. */
fd = open(fileName, O_RDWR | O_CREAT, 0777);
if (fd < 0) {
printf("open file failed.\n");
@@ -109,21 +123,21 @@ int FatfsTest(void)
return LOS_NOK;
}
- /* Save the update of the file to the device.*/
+ /* Save the file to a storage device. */
ret = fsync(fd);
if (ret != LOS_OK) {
printf("fsync failed.\n");
return LOS_NOK;
}
- /* Move the read/write pointer to the file header. */
+ /* Move the read/write pointer to the beginning of the file. */
off = lseek(fd, 0, SEEK_SET);
if (off != 0) {
printf("lseek failed.\n");
return LOS_NOK;
}
- /* Read the file content, with the same size as readBuf, to readBuf.*/
+ /* Read the file content with the length of readBuf to readBuf. */
len = read(fd, readBuf, sizeof(readBuf));
if (len != strlen(writeBuf)) {
printf("read file failed.\n");
@@ -138,14 +152,14 @@ int FatfsTest(void)
return LOS_NOK;
}
- /*Delete the file user/test/file.txt.*/
+ /* Delete the file file.txt from the user/test directory. */
ret = unlink(fileName);
if (ret != LOS_OK) {
printf("unlink failed.\n");
return LOS_NOK;
}
- /*Delete the user/test directory.*/
+ /* Delete the user/test directory. */
ret = rmdir(dirName);
if (ret != LOS_OK) {
printf("rmdir failed.\n");
@@ -153,14 +167,15 @@ int FatfsTest(void)
}
return LOS_OK;
-}
-```
+ }
+ ```
+
### Verification
The development is successful if the return result is as follows:
+
```
Hello OpenHarmony!
```
-
diff --git a/en/device-dev/kernel/kernel-mini-extend-file-lit.md b/en/device-dev/kernel/kernel-mini-extend-file-lit.md
index 7d51b76ab3167951eeaa72d839481a4630ec2390..599c94b5a12ea632374a03fcf0ca3e03afea7d8b 100644
--- a/en/device-dev/kernel/kernel-mini-extend-file-lit.md
+++ b/en/device-dev/kernel/kernel-mini-extend-file-lit.md
@@ -1,15 +1,17 @@
# LittleFS
+
## Basic Concepts
-LittleFS is a small file system designed for flash. By combining the log-structured file system and the copy-on-write \(COW\) file system, LittleFS stores metadata in log structure and data in the COW structure. This special storage empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size \(configurable\). That is, the RAM usage does not grow with the file system.
+LittleFS is a small file system designed for flash. By combining the log-structured file system and the copy-on-write (COW) file system, LittleFS stores metadata in log structure and data in the COW structure. This special storage empowers LittleFS high power-loss resilience. LittleFS uses the statistical wear leveling algorithm when allocating COW data blocks, effectively prolonging the service life of flash devices. LittleFS is designed for small-sized devices with limited resources, such as ROM and RAM. All RAM resources are allocated through a buffer with the fixed size (configurable). That is, the RAM usage does not grow with the file system.
LittleFS is a good choice when you look for a flash file system that is power-cut resilient and has wear leveling support on a small device with limited resources.
## Development Guidelines
-When porting LittleFS to a new hardware device, you need to declare **lfs\_config**:
+When porting LittleFS to a new hardware device, you need to declare **lfs_config**:
+
```
const struct lfs_config cfg = {
// block device operations
@@ -29,20 +31,21 @@ const struct lfs_config cfg = {
};
```
-**.read**, **.prog**, **.erase**, and **.sync** correspond to the read, write, erase, and synchronization APIs at the bottom layer of the hardware platform, respectively.
+**.read**, **.prog**, **.erase**, and **.sync** correspond to the read, write, erase, and synchronization APIs at the bottom layer of the hardware platform, respectively.
-**read\_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed.
+**read_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed.
-**prog\_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read\_size**. However, if the value is too large, more memory is consumed.
+**prog_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read_size**. However, if the value is too large, more memory is consumed.
-**block\_size**: indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog\_size**.
+**block_size**: indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog_size**.
-**block\_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased \(**block\_size**\).
+**block_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased (**block_size**).
-## Sample Code
-The sample code is as follows:
+## Sample Code
+ The sample code is as follows:
+
```
#include "lfs.h"
#include "stdio.h"
@@ -89,11 +92,12 @@ int main(void) {
}
```
-### Verification
+
+ **Verification**
The development is successful if the return result is as follows:
+
```
Say hello 1 times.
```
-
diff --git a/en/device-dev/kernel/kernel-mini-memory-perf.md b/en/device-dev/kernel/kernel-mini-memory-perf.md
index 3da1dd5dc276a844ed393af9b7d73bed23a4b767..95d097792307376342a55eefcfde96f7f921952b 100644
--- a/en/device-dev/kernel/kernel-mini-memory-perf.md
+++ b/en/device-dev/kernel/kernel-mini-memory-perf.md
@@ -3,7 +3,8 @@
## Basic Concepts
-perf is a performance analysis tool. It uses the performance monitoring unit \(PMU\) to count sampling events and collect context information and provides hot spot distribution and hot paths.
+perf is a performance analysis tool. It uses the performance monitoring unit (PMU) to count sampling events and collect context information and provides hot spot distribution and hot paths.
+
## Working Principles
@@ -13,227 +14,142 @@ perf provides two working modes: counting mode and sampling mode.
In counting mode, perf collects only the number of event occurrences and duration. In sampling mode, perf also collects context data and stores the data in a circular buffer. The IDE then analyzes the data and provides information about hotspot functions and paths.
+
## Available APIs
+
### Kernel Mode
-The perf module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h) reference.
-
-**Table 1** perf module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Starting or stopping perf sampling
- |
-LOS_PerfStart
- |
-Starts sampling.
- |
-
-LOS_PerfStop
- |
-Stops sampling.
- |
-
-Configuring perf sampling events
- |
-LOS_PerfConfig
- |
-Sets the type and period of a sampling event.
- |
-
-Reading sampling data
- |
-LOS_PerfDataRead
- |
-Reads the sampling data to a specified address.
- |
-
-Registering a hook for the sampling data buffer
- |
-LOS_PerfNotifyHookReg
- |
-Registers the hook to be called when the buffer waterline is reached.
- |
-
-LOS_PerfFlushHookReg
- |
-Registers the hook for flushing the cache in the buffer.
- |
-
-
-
-
-1. The structure of the perf sampling event is **PerfConfigAttr**. For details, see **kernel\\include\\los\_perf.h**.
-2. The sampling data buffer is a circular buffer, and only the region that has been read in the buffer can be overwritten.
-3. The buffer has limited space. You can register a hook to provide a buffer overflow notification or perform buffer read operation when the buffer waterline is reached. The default buffer waterline is 1/2 of the buffer size. The sample code is as follows:
-
- ```
- VOID Example_PerfNotifyHook(VOID)
- {
- CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0};
- UINT32 len;
- PRINT_DEBUG("perf buffer reach the waterline!\n");
- len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE);
- OsPrintBuff(buf, len); /* print data */
- }
- LOS_PerfNotifyHookReg(Example_PerfNotifyHook);
- ```
+The Perf module of the OpenHarmony LiteOS-A kernel provides the following functions. For details about the interfaces, see the [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_perf.h).
-4. If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency. The sample code is as follows:
+ **Table 1** APIs of the perf module
- ```
- VOID Example_PerfFlushHook(VOID *addr, UINT32 size)
- {
- OsCacheFlush(addr, size); /* platform interface */
- }
- LOS_PerfNotifyHookReg(Example_PerfFlushHook);
- ```
+| API| Description|
+| -------- | -------- |
+| LOS_PerfStart| Starts sampling.|
+| LOS_PerfStop| Stops sampling.|
+| LOS_PerfConfig| Sets the event type and sampling interval.|
+| LOS_PerfDataRead| Reads the sampling data.|
+| LOS_PerfNotifyHookReg| Registers the hook to be called when the buffer waterline is reached.|
+| LOS_PerfFlushHookReg| Registers the hook for flushing the cache in the buffer.|
+
+- The structure of the perf sampling event is **PerfConfigAttr**. For details, see **kernel\include\los_perf.h**.
+
+- The sampling data buffer is a circular buffer, and only the region that has been read in the buffer can be overwritten.
- The API for flushing the cache is configured based on the platform.
+- The buffer has limited space. You can register a hook to provide a buffer overflow notification or perform buffer read operation when the buffer waterline is reached. The default buffer waterline is 1/2 of the buffer size.
+
+ Example:
+
+ ```
+ VOID Example_PerfNotifyHook(VOID)
+ {
+ CHAR buf[LOSCFG_PERF_BUFFER_SIZE] = {0};
+ UINT32 len;
+ PRINT_DEBUG("perf buffer reach the waterline!\n");
+ len = LOS_PerfDataRead(buf, LOSCFG_PERF_BUFFER_SIZE);
+ OsPrintBuff(buf, len); /* print data */
+ }
+ LOS_PerfNotifyHookReg(Example_PerfNotifyHook);
+ ```
+
+- If the buffer sampled by perf involves caches across CPUs, you can register a hook for flushing the cache to ensure cache consistency.
+
+ Example:
+
+ ```
+ VOID Example_PerfFlushHook(VOID *addr, UINT32 size)
+ {
+ OsCacheFlush(addr, size); /* platform interface */
+ }
+ LOS_PerfNotifyHookReg(Example_PerfFlushHook);
+ ```
+
+ The API for flushing the cache is configured based on the platform.
### User Mode
-The perf character device is located in **/dev/perf**. You can read, write, and control the user-mode perf by running the following commands on the device node:
-- **read**: reads perf data in user mode.
-- **write**: writes user-mode sampling events.
-- **ioctl**: controls the user-mode perf, which includes the following:
+The perf character device is located in **/dev/perf**. You can read, write, and control the user-mode perf by running the following commands on the device node:
+
- ```
- #define PERF_IOC_MAGIC 'T'
- #define PERF_START _IO(PERF_IOC_MAGIC, 1)
- #define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
- ```
+- **read**: reads perf data in user mode.
- The operations correspond to **LOS\_PerfStart** and **LOS\_PerfStop**.
+- **write**: writes user-mode sampling events.
+- **ioctl**: controls the user-mode perf, which includes the following:
+
+ ```
+ #define PERF_IOC_MAGIC 'T'
+ #define PERF_START _IO(PERF_IOC_MAGIC, 1)
+ #define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
+ ```
-For more details, see [User-mode Development Example](#user-mode-development-example).
+ The operations correspond to **LOS_PerfStart** and **LOS_PerfStop**.
-## Development Guidelines
-### Kernel-mode Development Process
+For details, see [User-Mode Development Example](#user-mode-development-example).
+
+
+## How to Develop
+
+
+### Kernel-Mode Development Process
The typical process of enabling perf is as follows:
-1. Configure the macros related to the perf module.
-
- Configure the perf control macro **LOSCFG\_KERNEL\_PERF**, which is disabled by default. In the **kernel/liteos\_a** directory, run the **make update\_config** command, choose **Kernel**, and select **Enable Perf Feature**.
-
-
- Macro
- |
- menuconfig Option
- |
- Description
- |
- Value
- |
-
-
- LOSCFG_KERNEL_PERF
- |
- Enable Perf Feature
- |
- Whether to enable perf.
- |
- YES/NO
- |
-
- LOSCFG_PERF_CALC_TIME_BY_TICK
- |
- Time-consuming Calc Methods->By Tick
- |
- Whether to use tick as the perf timing unit.
- |
- YES/NO
- |
-
- LOSCFG_PERF_CALC_TIME_BY_CYCLE
- |
- Time-consuming Calc Methods->By Cpu Cycle
- |
- Whether to use cycle as the perf timing unit.
- |
- YES/NO
- |
-
- LOSCFG_PERF_BUFFER_SIZE
- |
- Perf Sampling Buffer Size
- |
- Size of the buffer used for perf sampling.
- |
- INT
- |
-
- LOSCFG_PERF_HW_PMU
- |
- Enable Hardware Pmu Events for Sampling
- |
- Whether to enable hardware PMU events. The target platform must support the hardware PMU.
- |
- YES/NO
- |
-
- LOSCFG_PERF_TIMED_PMU
- |
- Enable Hrtimer Period Events for Sampling
- |
- Whether to enable high-precision periodical events. The target platform must support the high precision event timer (HPET).
- |
- YES/NO
- |
-
- LOSCFG_PERF_SW_PMU
- |
- Enable Software Events for Sampling
- |
- Whether to enable software events. LOSCFG_KERNEL_HOOK must also be enabled.
- |
- YES/NO
- |
-
-
-
-
-2. Call **LOS\_PerfConfig** to configure the events to be sampled.
-
- perf provides two working modes and three types of events.
-
- Two modes: counting mode \(counts only the number of event occurrences\) and sampling mode \(collects context information such as task IDs, PC, and backtrace\)
-
- Three types of events: CPU hardware events \(such as cycle, branch, icache, and dcache\), high-precision periodical events \(such as CPU clock\), and OS software events \(such as task switch, mux pend, and IRQ\)
-
-3. Call **LOS\_PerfStart\(UINT32 sectionId\)** at the start of the code to be sampled. The input parameter **sectionId** specifies different sampling session IDs.
-4. Call **LOS\_PerfStop** at the end of the code to be sampled.
-5. Call **LOS\_PerfDataRead** to read the sampling data and use IDE to analyze the collected data.
-
-## Kernel-mode Development Example
+1. Configure the macros related to the perf module.
+
+ Configure the perf control macro **LOSCFG_KERNEL_PERF**, which is disabled by default. In the **kernel/liteos_a** directory, run the **make update_config** command, choose **Kernel**, and select **Enable Perf Feature**.
+
+ | Item| menuconfig Option| Description| Value|
+ | -------- | -------- | -------- | -------- |
+ | LOSCFG_KERNEL_PERF | Enable Perf Feature | Whether to enable perf.| YES/NO |
+ | LOSCFG_PERF_CALC_TIME_BY_TICK | Time-consuming Calc Methods->By Tick | Whether to use tick as the perf timing unit.| YES/NO |
+ | LOSCFG_PERF_CALC_TIME_BY_CYCLE | Time-consuming Calc Methods->By Cpu Cycle | Whether to use cycle as the perf timing unit.| YES/NO |
+ | LOSCFG_PERF_BUFFER_SIZE | Perf Sampling Buffer Size | Size of the buffer used for perf sampling.| INT |
+ | LOSCFG_PERF_HW_PMU | Enable Hardware Pmu Events for Sampling | Whether to enable hardware PMU events. The target platform must support the hardware PMU.| YES/NO |
+ | LOSCFG_PERF_TIMED_PMU | Enable Hrtimer Period Events for Sampling | Whether to enable high-precision periodical events. The target platform must support the high precision event timer (HPET).| YES/NO |
+ | LOSCFG_PERF_SW_PMU | Enable Software Events for Sampling | Whether to enable software events. **LOSCFG_KERNEL_HOOK** must also be enabled.| YES/NO |
+
+2. Call **LOS_PerfConfig** to configure the events to be sampled.
+
+ perf provides two working modes and three types of events.
+
+ Working modes: counting mode (counts only the number of event occurrences) and sampling mode (collects context information such as task IDs, PC, and backtrace)
+
+ Events: CPU hardware events (such as cycle, branch, icache, and dcache), high-precision periodical events (such as CPU clock), and OS software events (such as task switch, mux pend, and IRQ)
+
+3. Call **LOS_PerfStart(UINT32 sectionId)** at the start of the code to be sampled. The input parameter **sectionId** specifies different sampling session IDs.
+
+4. Call **LOS_PerfStop** at the end of the code to be sampled.
+
+5. Call **LOS_PerfDataRead** to read the sampling data and use IDE to analyze the collected data.
+
+
+#### Kernel-Mode Development Example
This example implements the following:
-1. Create a perf task.
-2. Configure sampling events.
-3. Start perf.
-4. Execute algorithms for statistics.
-5. Stop perf.
-6. Export the result.
+1. Create a perf task.
-## Kernel-mode Sample Code
+2. Configure sampling events.
-Prerequisites: The perf module configuration is complete in **menuconfig**.
+3. Start perf.
-The code is as follows:
+4. Execute algorithms for statistics.
+
+5. Stop perf.
+
+6. Export the result.
+
+
+#### Kernel-Mode Sample Code
+
+Prerequisites: The perf module configuration is complete in **menuconfig**.
+
+The sample code is as follows:
```
#include "los_perf.h"
@@ -299,10 +215,10 @@ STATIC VOID perfTestHwEvent(VOID)
UINT32 Example_Perf_test(VOID){
UINT32 ret;
TSK_INIT_PARAM_S perfTestTask;
- /* Create a perf task.*/
+ /* Create a perf task. */
memset(&perfTestTask, 0, sizeof(TSK_INIT_PARAM_S));
perfTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)perfTestHwEvent;
- perfTestTask.pcName = "TestPerfTsk"; /* Task name.*/
+ perfTestTask.pcName = "TestPerfTsk"; /* Test task name. */
perfTestTask.uwStackSize = 0x800;
perfTestTask.usTaskPrio = 5;
perfTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
@@ -316,9 +232,10 @@ UINT32 Example_Perf_test(VOID){
LOS_MODULE_INIT(perfTestHwEvent, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
-### Kernel-mode Verification
-The output is as follows:
+#### Kernel-Mode Verification
+
+ The output is as follows:
```
--------count mode----------
@@ -330,48 +247,50 @@ num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00
```
-- For the counting mode, the following information is displayed after perf is stopped:
-
- Event name \(cycles\), event type \(0xff\), and number of event occurrences \(5466989440\)
+- For the counting mode, the following information is displayed after perf is stopped:
+ Event name (cycles), event type (0xff), and number of event occurrences (5466989440)
- For hardware PMU events, the displayed event type is the hardware event ID, not the abstract type defined in **enum PmuHWId**.
+ For hardware PMU events, the displayed event type is the hardware event ID, not the abstract type defined in **enum PmuHWId**.
-- For the sampling mode, the address and length of the sampled data will be displayed after perf is stopped:
+- For the sampling mode, the address and length of the sampled data will be displayed after perf is stopped:
+ dump section data, addr: (0x8000000) length: (0x5000)
- dump section data, addr: \(0x8000000\) length: \(0x5000\)
+ You can export the data using the JTAG interface and then use the IDE offline tool to analyze the data.
- You can export the data using the JTAG interface and then use the IDE offline tool to analyze the data.
+ You can also call **LOS_PerfDataRead** to read data to a specified address for further analysis. In the example, **OsPrintBuff** is a test API, which prints the sampled data by byte. **num** indicates the sequence number of the byte, and **hex** indicates the value in the byte.
- You can also call **LOS\_PerfDataRead** to read data to a specified address for further analysis. In the example, **OsPrintBuff** is a test API, which prints the sampled data by byte. **num** indicates the sequence number of the byte, and **hex** indicates the value in the byte.
+### User-Mode Development Process
-### User-mode Development Process
+Choose **Driver** > **Enable PERF DRIVER** in **menuconfig** to enable the perf driver. This option is available in **Driver** only after **Enable Perf Feature** is selected in the kernel.
-Choose **Driver** \> **Enable PERF DRIVER** in **menuconfig** to enable the perf driver. This option is available in **Driver** only after **Enable Perf Feature** is selected in the kernel.
+1. Open the **/dev/perf** file and perform read, write, and ioctl operations.
-1. Open the **/dev/perf** file and perform read, write, and ioctl operations.
-2. Run the **perf** commands in user mode in the **/bin** directory. After running **cd bin**, you can use the following commands:
- - **./perf start \[_id_\]**: starts perf sampling. _id_ is optional and is **0** by default.
- - **./perf stop**: stops perf sampling.
- - **./perf read <_nBytes_\>**: reads n-byte data from the sampling buffer and displays the data.
- - **./perf list**: lists the events supported by **-e**.
- - **./perf stat/record \[_option_\] <_command_\>**: sets counting or sampling parameters.
- - The \[_option_\] can be any of the following:
- - **-e**: sets sampling events. Events of the same type listed in **./perf list** can be used.
- - **-p**: sets the event sampling interval.
- - **-o**: specifies the path of the file for saving the perf sampling data.
- - **-t**: specifies the task IDs for data collection. Only the contexts of the specified tasks are collected. If this parameter is not specified, all tasks are collected by default.
- - **-s**: specifies the context type for sampling. For details, see **PerfSampleType** defined in **los\_perf.h**.
- - **-P**: specifies the process IDs for data collection. Only the contexts of the specified processes are collected. If this parameter is not specified, all processes are collected by default.
- - **-d**: specifies whether to divide the frequency \(the value is incremented by 1 each time an event occurs 64 times\). This option is valid only for hardware cycle events.
-
- - _command_ specifies the program to be checked by perf.
+2. Run the **perf** commands in user mode in the **/bin** directory.
+
+ After running **cd bin**, you can use the following commands:
+
+ - **./perf start [*id*]**: starts perf sampling. *id* is optional and is **0** by default.
+ - **./perf stop**: stops perf sampling.
+ - **./perf read <*nBytes*>**: reads n-byte data from the sampling buffer and displays the data.
+ - **./perf list**: lists the events supported by **-e**.
+ - **./perf stat/record [*option*] <*command*>**: sets counting or sampling parameters.
+ - The [*option*] can be any of the following:
+ - -**-e**: sets sampling events. Events of the same type listed in **./perf list** can be used.
+ - -**-p**: sets the event sampling interval.
+ - -**-o**: specifies the path of the file for saving the perf sampling data.
+ - -**-t**: specifies the task IDs for data collection. Only the contexts of the specified tasks are collected. If this parameter is not specified, all tasks are collected by default.
+ - -**-s**: specifies the context type for sampling. For details, see **PerfSampleType** defined in **los_perf.h**.
+ - -**-P**: specifies the process IDs for data collection. Only the contexts of the specified processes are collected. If this parameter is not specified, all processes are collected by default.
+ - -**-d**: specifies whether to divide the frequency (the value is incremented by 1 each time an event occurs 64 times). This option is valid only for hardware cycle events.
+ - *command* specifies the program to be checked by perf.
+Examples:
+Run the **./perf list** command to display available events.
-Examples:
+The output is as follows:
-Run the **./perf list** command to display available events. The output is as follows:
```
cycles [Hardware event]
@@ -389,7 +308,10 @@ mem-alloc [Software event]
mux-pend [Software event]
```
-Run **./perf stat -e cycles os\_dump**. The output is as follows:
+Run **./perf stat -e cycles os_dump**.
+
+The output is as follows:
+
```
type: 0
@@ -406,7 +328,10 @@ time used: 0.058000(s)
[cycles] eventType: 0xff [core 1]: 13583830
```
-Run **./perf record -e cycles os\_dump**. The output is as follows:
+Run **./perf record -e cycles os_dump**.
+
+The output is as follows:
+
```
type: 0
@@ -423,22 +348,28 @@ time used: 0.059000(s)
save perf data success at /storage/data/perf.data
```
-> **NOTE**
->After running the **./perf stat/record** command, you can run the **./perf start** and **./perf stop** commands multiple times. The sampling event configuration is as per the parameters set in the latest **./perfstat/record** command.
+>  **NOTE**
+> After running the **./perf stat/record** command, you can run the **./perf start** and **./perf stop** commands multiple times. The sampling event configuration is as per the parameters set in the latest **./perfstat/record** command.
+
-### User-mode Development Example
+#### User-Mode Development Example
This example implements the following:
-1. Open the perf character device.
-2. Write the perf events.
-3. Start perf.
-4. Stop perf.
-5. Read the perf sampling data.
+1. Open the perf character device.
+
+2. Write the perf events.
-### User-Mode Sample Code
+3. Start perf.
-The code is as follows:
+4. Stop perf.
+
+5. Read the perf sampling data.
+
+
+#### User-Mode Sample Code
+
+ The code is as follows:
```
#include "fcntl.h"
@@ -506,13 +437,13 @@ int main(int argc, char **argv)
}
```
-### User-mode Verification
-The output is as follows:
+#### User-Mode Verification
+
+ The output is as follows:
```
[EMG] dump section data, addr: 0x8000000 length: 0x800000
num: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ...
hex: 00 ef ef ef 00 00 00 00 14 00 00 00 60 00 00 00 00 00 00 00 70 88 36 40 08 00 00 00 6b 65 72 6e 65 6c 00 00 01 00 00 00 cc 55 30 40 08 00 00 00 6b 65 72 6e 65 6c 00 00
```
-
diff --git a/en/device-dev/kernel/kernel-mini-overview.md b/en/device-dev/kernel/kernel-mini-overview.md
index 7b86f1a82028e03366eb3441d6257eb7791764c3..a1b7902c802ad44bac6477e73757955d4611aecf 100644
--- a/en/device-dev/kernel/kernel-mini-overview.md
+++ b/en/device-dev/kernel/kernel-mini-overview.md
@@ -1,59 +1,35 @@
# Kernel Overview
+
## Overview
-The OpenHarmony LiteOS-M kernel is a lightweight operating system \(OS\) kernel designed for the IoT field. It features small size, low power consumption, and high performance. The LiteOS-M kernel has simple code structure, including the minimum function set, kernel abstraction layer \(KAL\), optional components, and project directory. It supports the Hardware Driver Foundation \(HDF\), which provides unified driver standards and access mode for device vendors to simplify porting of drivers and allow one-time development for multi-device deployment.
+The OpenHarmony LiteOS-M kernel is a lightweight operating system (OS) kernel designed for the IoT field. It features small size, low power consumption, and high performance. The LiteOS-M kernel has simple code structure, including the minimum function set, kernel abstraction layer (KAL), optional components, and project directory. It supports the Hardware Driver Foundation (HDF), which provides unified driver standards and access mode for device vendors to simplify porting of drivers and allow one-time development for multi-device deployment.
+
+The OpenHarmony LiteOS-M kernel architecture consists of the hardware layer and hardware-irrelevant layers, as shown in the figure below. The hardware layer is classified based on the compiler toolchain and chip architecture, and provides a unified Hardware Abstraction Layer (HAL) interface to improve hardware adaptation and facilitate the expansion of various types of AIoT hardware and compilation toolchains. The other modules are irrelevant to the hardware. The basic kernel module provides basic kernel capabilities. The extended modules provide capabilities of components, such as the network and file systems, as well as exception handling and debug tools. The KAL provides unified standard APIs.
-The OpenHarmony LiteOS-M kernel architecture consists of the hardware layer and hardware-irrelevant layers, as shown in the figure below. The hardware layer is classified based on the compiler toolchain and chip architecture, and provides a unified Hardware Abstraction Layer \(HAL\) interface to improve hardware adaptation and facilitate the expansion of various types of AIoT hardware and compilation toolchains. The other modules are irrelevant to the hardware. The basic kernel module provides basic kernel capabilities. The extended modules provide capabilities of components, such as the network and file systems, as well as exception handling and debug tools. The KAL provides unified standard APIs.
+ **Figure 1** Kernel architecture
-**Figure 1** Kernel architecture
-
+ 
-### CPU Architecture Support
+
+## CPU Architecture Support
The CPU architecture includes two layers: general architecture definition layer and specific architecture definition layer. The former provides interfaces supported and implemented by all architectures. The latter is specific to an architecture. For a new architecture to be added, the general architecture definition layer must be implemented first and the architecture-specific functions can be implemented at the specific architecture definition layer.
-**Table 1** CPU architecture rules
-
-
-Rule
- |
-General Architecture Definition Layer
- |
-Specific Architecture Definition Layer
- |
-
-
-Header file location
- |
-arch/include
- |
-arch/<arch>/<arch>/<toolchain>/
- |
-
-Header file name
- |
-los_<function>.h
- |
-los_arch_<function>.h
- |
-
-Function name
- |
-Halxxxx
- |
-Halxxxx
- |
-
-
-
-
-LiteOS-M supports mainstream architectures, such as ARM Cortex-M3, ARM Cortex-M4, ARM Cortex-M7, ARM Cortex-M33, and RISC-V. If you need to expand the CPU architecture, see [Chip Architecture Adaptation](../porting/porting-chip-kernel-overview.md#section137431650339).
-
-### Working Principles
-
-Configure the system clock and number of ticks per second in the **target\_config.h** file of the development board. Configure the task, memory, inter-process communication \(IPC\), and exception handling modules based on service requirements. When the system boots, the modules are initialized based on the configuration. The kernel startup process includes peripheral initialization, system clock configuration, kernel initialization, and OS boot, as shown in the figure below.
-
-**Figure 2** Kernel startup process
-
+ **Table 1** CPU architecture rules
+
+| Rule| General Architecture Layer| Specific Architecture Layer|
+| -------- | -------- | -------- |
+| Header file location| arch/include | arch/<arch>/<arch>/<toolchain>/ |
+| Header file name| los_<function>.h | los_arch_<function>.h |
+| Function name| Halxxxx | Halxxxx |
+
+LiteOS-M supports mainstream architectures, such as ARM Cortex-M3, ARM Cortex-M4, ARM Cortex-M7, ARM Cortex-M33, and RISC-V. If you need to expand the CPU architecture, see [Chip Architecture Adaptation](../porting/porting-chip-kernel-overview.md).
+
+
+## Working Principles
+
+In the **target\_config.h** file of the development board, configure the system clock and number of ticks per second, and configure the task, memory, inter-process communication (IPC), and exception handling modules based on service requirements. When the system boots, the modules are initialized based on the configuration. The kernel startup process includes peripheral initialization, system clock configuration, kernel initialization, and OS boot, as shown in the figure below.
+ **Figure 2** Kernel startup process
+ 
diff --git a/en/device-dev/kernel/kernel-small-apx-dll.md b/en/device-dev/kernel/kernel-small-apx-dll.md
index 2e7bb0d0fadcf92e14ea957b89728e240542c18a..e33e8e55d65e6a5e39fbb33e154557e2751148e9 100644
--- a/en/device-dev/kernel/kernel-small-apx-dll.md
+++ b/en/device-dev/kernel/kernel-small-apx-dll.md
@@ -1,178 +1,69 @@
# Doubly Linked List
-
## Basic Concepts
-A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains a pointer to the previous node and a pointer to the next node in the sequence of nodes. The pointer head is unique. A doubly linked list allows access from a list node to its next node and also the previous node on the list. This data structure facilitates data search, especially traversal of a large amount of data. The symmetry of the doubly linked list also makes operations, such as insertion and deletion, easy. However, pay attention to the pointer direction when performing operations.
+A doubly linked list (DLL) is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains a pointer to the previous node and a pointer to the next node in the sequence of nodes. The pointer head is unique. A DLL allows access from a list node to its next node and also the previous node on the list. This data structure facilitates data search, especially traversal of a large amount of data. The symmetry of the DLL also makes operations, such as insertion and deletion, easy. However, pay attention to the pointer direction when performing operations.
+
## Available APIs
-The following table describes APIs available for the doubly linked list. For more details about the APIs, see the API reference.
-
-
-Function
- |
-API
- |
-Description
- |
-
-Initializing a linked list
- |
-LOS_ListInit
- |
-Initializes a specified node as a doubly linked list node.
- |
-
-LOS_DL_LIST_HEAD
- |
-Defines a node and initializes it as a doubly linked list node.
- |
-
-Adding a node
- |
-LOS_ListAdd
- |
-Inserts the specified node to the head of a doubly linked list.
- |
-
-LOS_ListHeadInsert
- |
-Inserts the specified node to the head of a doubly linked list. It is the same as LOS_ListAdd.
- |
-
-LOS_ListTailInsert
- |
-Inserts the specified node to the end of a doubly linked list.
- |
-
-Adding a linked list
- |
-LOS_ListAddList
- |
-Inserts the head of a specified linked list into the head of a doubly linked list.
- |
-
-LOS_ListHeadInsertList
- |
-Inserts the head of a specified linked list into the head of a doubly linked list. It is the same as LOS_ListAddList.
- |
-
-LOS_ListTailInsertList
- |
-Inserts the end of a specified linked list into the head of a doubly linked list.
- |
-
-Deleting a node
- |
-LOS_ListDelete
- |
-Deletes the specified node from a doubly linked list.
- |
-
-LOS_ListDelInit
- |
-Deletes the specified node from the linked list and uses the node to initialize the linked list.
- |
-
-Determining a doubly linked list
- |
-LOS_ListEmpty
- |
-Checks whether a linked list is empty.
- |
-
-LOS_DL_LIST_IS_END
- |
-Checks whether the specified linked list node is at the end of the linked list.
- |
-
-LOS_DL_LIST_IS_ON_QUEUE
- |
-Checks whether the linked list node is in a doubly linked list.
- |
-
-Obtaining structure information
- |
-LOS_OFF_SET_OF
- |
-Obtains the offset of a member in a specified structure relative to the start address of the structure.
- |
-
-LOS_DL_LIST_ENTRY
- |
-Obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.
- |
-
-LOS_ListPeekHeadType
- |
-Obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Return Null if the linked list is empty.
- |
-
-LOS_ListRemoveHeadType
- |
-Obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Return Null if the linked list is empty.
- |
-
-LOS_ListNextType
- |
-Obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL is returned.
- |
-
-Traversing a doubly linked list
- |
-LOS_DL_LIST_FOR_EACH
- |
-Traverses a doubly linked list.
- |
-
-LOS_DL_LIST_FOR_EACH_SAFE
- |
-Traverses a doubly linked list, and stores the next node of the current node for security verification.
- |
-
-Traversing the structure that contains the doubly linked list
- |
-LOS_DL_LIST_FOR_EACH_ENTRY
- |
-Traverses the specified doubly linked list and obtains the address of the structure that contains the linked list node.
- |
-
-LOS_DL_LIST_FOR_EACH_ENTRY_SAFE
- |
-Traverses the specified doubly linked list, obtains the structure address of the node that contains the linked list, and stores the structure address that contains the next node of the current node.
- |
-
-
-
-
-## How to Develop
-
-The typical development process of the doubly linked list is as follows:
-
-1. Call **LOS\_ListInit/LOS\_DL\_LIST\_HEAD** to initialize a doubly linked list.
-2. Call **LOS\_ListAdd** to insert a node to the list.
-3. Call **LOS\_ListTailInsert** to insert a node to the end of the list.
-4. Call **LOS\_ListDelete** to delete the specified node.
-5. Call **LOS\_ListEmpty** to check whether a linked list is empty.
-6. Call **LOS\_ListDelInit** to delete a specified node, and initialize the linked list based on this node.
-
-> **NOTE:**
->- Pay attention to the operations of the front and back pointer of the node.
->- The linked list operation APIs are underlying APIs and do not check whether the input parameters are empty. You must ensure that the input parameters are valid.
->- If the memory of a linked list node is dynamically requested, release the memory after deleting the node.
-
-### Development Example
+The table below describes the DLL APIs. For more details about the APIs, see the API reference.
+
+| **Category**| **API**|
+| -------- | -------- |
+| Initializing a DLL| - **LOS_ListInit**: initializes a node as a DLL node.
- **LOS_DL_LIST_HEAD**: defines a node and initializes it as a DLL node.|
+| Adding a node| - **LOS_ListAdd**: adds a node to the head of a DLL.
- **LOS_ListHeadInsert**: same as **LOS_ListAdd**.
- **LOS_ListTailInsert**: inserts a node to the tail of a DLL.|
+| Adding a DLL| - **LOS_ListAddList**: adds the head of a DLL to the head of this DLL.
- **LOS_ListHeadInsertList**: inserts the head of a DLL to the head of this DLL.
- **LOS_ListTailInsertList**: Inserts the end of a DLL to the head of this DLL.|
+| Deleting a node| - **LOS_ListDelete**: deletes a node from this DLL.
- **LOS_ListDelInit**: deletes a node from this DLL and uses this node to initialize the DLL.|
+| Checking a DLL| - **LOS_ListEmpty**: checks whether a DLL is empty.
- **LOS_DL_LIST_IS_END**: checks whether a node is the tail of the DLL.
- **LOS_DL_LIST_IS_ON_QUEUE**: checks whether a node is in the DLL.|
+| Obtains structure information.| - **LOS_OFF_SET_OF**: obtains the offset of a member in the specified structure relative to the start address of the structure.
- **LOS_DL_LIST_ENTRY**: obtains the address of the structure that contains the first node in the DLL. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure.
- **LOS_ListPeekHeadType**: obtains the address of the structure that contains the first node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListRemoveHeadType**: obtains the address of the structure that contains the first node in the linked list, and deletes the first node from the list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the name of the structure to be obtained, and the third input parameter indicates the name of the linked list in the structure. Null will be returned if the DLL is empty.
- **LOS_ListNextType**: obtains the address of the structure that contains the next node of the specified node in the linked list. The first input parameter of the API indicates the head node in the list, the second input parameter indicates the specified node, the third parameter indicates the name of the structure to be obtained, and the fourth input parameter indicates the name of the linked list in the structure. If the next node of the linked list node is the head node and is empty, NULL will be returned.|
+| Traversing a DLL| - **LOS_DL_LIST_FOR_EACH**: traverses a DLL.
- **LOS_DL_LIST_FOR_EACH_SAFE**: traverses the DLL and stores the subsequent nodes of the current node for security verification.|
+| Traversing the structure that contains the DLL| - **LOS_DL_LIST_FOR_EACH_ENTRY**: traverses a DLL and obtains the address of the structure that contains the linked list node.
- **LOS_DL_LIST_FOR_EACH_ENTRY_SAFE**: traverses a DLL, obtains the address of the structure that contains the linked list node, and stores the address of the structure that contains the subsequent node of the current node.|
+
+
+## How to Develop
+
+The typical development process of the DLL is as follows:
+
+1. Call **LOS_ListInit** or **LOS_DL_LIST_HEAD** to initialize a DLL.
+
+2. Call **LOS_ListAdd** to add a node into the DLL.
+
+3. Call **LOS_ListTailInsert** to insert a node to the tail of the DLL.
+
+4. Call **LOS_ListDelete** to delete the specified node.
+
+5. Call **LOS_ListEmpty** to check whether the DLL is empty.
+
+6. Call **LOS_ListDelInit** to delete the specified node and initialize the DLL based on the node.
+
+
+>  **NOTE**
+> - Pay attention to the operations operations of the front and back pointer of the node.
+>
+> - The DLL APIs are underlying interfaces and do not check whether the input parameters are empty. You must ensure that the input parameters are valid.
+>
+> - If the memory of a linked list node is dynamically allocated, release the memory when deleting the node.
+
+
+ **Development Example**
**Example Description**
+
This example implements the following:
-1. Initialize a doubly linked list.
-2. Add nodes.
-3. Delete nodes.
-4. Check the operation result.
+
+1. Initialize a DLL.
+
+2. Add nodes.
+
+3. Delete nodes.
+
+4. Check the operation result.
+
+
```
#include "stdio.h"
@@ -184,7 +75,7 @@ static UINT32 ListSample(VOID)
LOS_DL_LIST listNode1 = {NULL,NULL};
LOS_DL_LIST listNode2 = {NULL,NULL};
- // Initialize the linked list.
+ // Initialize the DLL.
PRINTK("Initial head\n");
LOS_ListInit(&listHead);
@@ -203,7 +94,7 @@ static UINT32 ListSample(VOID)
LOS_ListDelete(&listNode1);
LOS_ListDelete(&listNode2);
- // Check that the linked list is empty.
+ // Check whether the DLL is empty.
if (LOS_ListEmpty(&listHead)) {
PRINTK("Delete success\n");
}
@@ -212,8 +103,10 @@ static UINT32 ListSample(VOID)
}
```
+
**Verification**
+
The development is successful if the return result is as follows:
```
@@ -222,4 +115,3 @@ Add listNode1 success
Tail insert listNode2 success
Delete success
```
-
diff --git a/en/device-dev/kernel/kernel-small-basic-memory-virtual.md b/en/device-dev/kernel/kernel-small-basic-memory-virtual.md
index 1c3b440fd5ecc5741b2cad1a49ef59b90d9082aa..bcef2eb5c93bf3ba1b15552d055a5cfa7dc9405b 100644
--- a/en/device-dev/kernel/kernel-small-basic-memory-virtual.md
+++ b/en/device-dev/kernel/kernel-small-basic-memory-virtual.md
@@ -1,322 +1,129 @@
# Virtual Memory Management
-## Basic Concepts
+## Basic Concepts
Virtual memory management is a technology used by computer systems to manage memory. Each process has a continuous virtual address space. The size of the virtual address space is determined by the number of CPU bits. The maximum addressing space for a 32-bit hardware platform ranges from 0 GiB to 4 GiB. The 4 GiB space is divided into two parts: 3 GiB higher-address space for the LiteOS-A kernel and 1 GiB lower-address space for user-mode processes. The virtual address space of each process space is independent, and the code and data do not affect each other.
-The system divides the virtual memory into memory blocks called virtual pages. The size of a virtual page is generally 4 KiB or 64 KiB. The virtual page of the LiteOS-A kernel is 4 KiB by default. You can configure memory management units \(MMUs\) as required. The minimum unit of the virtual memory management is a page. A virtual address region in the LiteOS-A kernel can contain one virtual page or multiple virtual pages with contiguous addresses. Similarly, the physical memory is also divided by page, and each memory block is called page frame. The virtual address space is divided as follows: 3 GiB \(**0x40000000** to **0xFFFFFFFF**\) for the kernel space and 1 GiB \(**0x01000000** to **0x3F000000**\) for the user space. The following tables describe the virtual address plan. You can view or configure virtual addresses in **los\_vm\_zone.h**.
-
-**Table 1** Kernel-mode addresses
-
-
-Zone
- |
-Description
- |
-Property
- |
-
-
-DMA zone
- |
-Addresses for direct memory access (DMA) of I/O devices.
- |
-Uncache
- |
-
-Normal zone
- |
-Addresses for loading the kernel code segment, data segment, heap, and stack.
- |
-Cache
- |
-
-high mem zone
- |
-Addresses for allocating contiguous virtual memory. The mapped physical memory blocks may not be contiguous.
- |
-Cache
- |
-
-
-
-
-**Table 2** User-mode virtual addresses
-
-
-Zone
- |
-Description
- |
-Property
- |
-
-
-Code segment
- |
-User-mode code segment address range
- |
-Cache
- |
-
-Heap
- |
-User-mode heap address range
- |
-Cache
- |
-
-Stack
- |
-User-mode stack address range
- |
-Cache
- |
-
-Shared library
- |
-Address range for loading the user-mode shared library, including the address range mapped by mmap.
- |
-Cache
- |
-
-
-
-
-## Working Principles
+The system divides the virtual memory into memory blocks called virtual pages. The size of a virtual page is generally 4 KiB or 64 KiB. The virtual page of the LiteOS-A kernel is 4 KiB by default. You can configure memory management units (MMUs) as required. The minimum unit of the virtual memory management is a page. A virtual address region in the LiteOS-A kernel can contain one virtual page or multiple virtual pages with contiguous addresses. Similarly, the physical memory is also divided by page, and each memory block is called page frame. The virtual address space is divided as follows: 3 GiB (**0x40000000** to **0xFFFFFFFF**) for the kernel space and 1 GiB (**0x01000000** to **0x3F000000**) for the user space. The following tables describe the virtual address plan. You can view or configure virtual addresses in **los_vm_zone.h**.
+
+**Table 1** Kernel-mode addresses
+
+| Zone| Description| Property|
+| -------- | -------- | -------- |
+| DMA zone | Addresses for direct memory access (DMA) of I/O devices.| Uncache |
+| Normal zone | Addresses for loading the kernel code segment, data segment, heap, and stack.| Cache |
+| high mem zone | Addresses for allocating contiguous virtual memory. The mapped physical memory blocks may not be contiguous.| Cache |
+
+**Table 2** User-mode virtual addresses
+
+| Zone| Description| Property|
+| -------- | -------- | -------- |
+| Code snippet| User-mode code segment address range.| Cache |
+| Heap| User-mode heap address range.| Cache |
+| Stack| User-mode stack address range.| Cache |
+| Shared databases| Address range for loading the user-mode shared library, including the address range mapped by mmap.| Cache |
+
+
+## Working Principles
In virtual memory management, the virtual address space is contiguous, but the mapped physical memory is not necessarily contiguous, as depicted in the following figure. When an executable program is loaded and runs, the CPU accesses the code or data in the virtual address space in the following two cases:
-- If the page \(for example, V0\) containing the virtual address accessed by the CPU is mapped to a physical page \(for example, P0\), the CPU locates the page table entry corresponding to the process \(for details, see [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md)"\), accesses the physical memory based on the physical address information in the page table entry, and returns the content.
-- If the page \(for example, V2\) containing the virtual address accessed by the CPU is not mapped to a physical page, the system triggers a page missing fault, requests a physical page, copies the corresponding information to the physical page, and updates the start address of the physical page to the page table entry. Then, the CPU can access specific code or data by executing the instruction for accessing the virtual memory again.
-
-**Figure 1** Mapping between the virtual and physical memory addresses
-
-
-## Development Guidelines
-
-### Available APIs
-
-**Table 3** APIs of the virtual memory management module
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Obtaining process memory space
- |
-LOS_CurrSpaceGet
- |
-Obtains the pointer to the current process space structure.
- |
-
-LOS_SpaceGet
- |
-Obtains the pointer to the process space structure corresponding to the virtual address.
- |
-
-LOS_GetKVmSpace
- |
-Obtains the pointer to the kernel process space structure.
- |
-
-LOS_GetVmallocSpace
- |
-Obtains the pointer to the vmalloc space structure.
- |
-
-LOS_GetVmSpaceList
- |
-Obtains the pointer to the process space linked list.
- |
-
-Operations related to the virtual address region
- |
-LOS_RegionFind
- |
-Searches for and returns the virtual address region corresponding to the specified address in the process space.
- |
-
-LOS_RegionRangeFind
- |
-Searches for and returns the virtual address region corresponding to the specified address range in the process space.
- |
-
-LOS_IsRegionFileValid
- |
-Checks whether the virtual address region is mapped to a file.
- |
-
-LOS_RegionAlloc
- |
-Requests a free virtual address region.
- |
-
-LOS_RegionFree
- |
-Releases a specific region in the process space.
- |
-
-LOS_RegionEndAddr
- |
-Obtains the end address of the specified address region.
- |
-
-LOS_RegionSize
- |
-Obtains the size of a region.
- |
-
-LOS_IsRegionTypeFile
- |
-Checks whether the address region is a file memory mapping.
- |
-
-LOS_IsRegionPermUserReadOnly
- |
-Checks whether the address region is read-only in the user space.
- |
-
-LOS_IsRegionFlagPrivateOnly
- |
-Checks whether the address region has private attributes.
- |
-
-LOS_SetRegionTypeFile
- |
-Sets the file memory mapping attribute.
- |
-
-LOS_IsRegionTypeDev
- |
-Checks whether the address region is device memory mapping.
- |
-
-LOS_SetRegionTypeDev
- |
-Sets the device memory mapping attribute.
- |
-
-LOS_IsRegionTypeAnon
- |
-Checks whether the address region is an anonymous mapping.
- |
-
-LOS_SetRegionTypeAnon
- |
-Sets the anonymous mapping attribute.
- |
-
-Verifying address
- |
-LOS_IsUserAddress
- |
-Checks whether the address is in the user space.
- |
-
-LOS_IsUserAddressRange
- |
-Checks whether the address region is in the user space.
- |
-
-LOS_IsKernelAddress
- |
-Checks whether the address is in the kernel space.
- |
-
-LOS_IsKernelAddressRange
- |
-Checks whether the address region is in the kernel space.
- |
-
-LOS_IsRangeInSpace
- |
-Checks whether the address region is in the process space.
- |
-
-vmalloc operations
- |
-LOS_VMalloc
- |
-Requests memory using vmalloc.
- |
-
-LOS_VFree
- |
-Releases memory using vmalloc.
- |
-
-LOS_IsVmallocAddress
- |
-Checks whether the address is requested by using vmalloc.
- |
-
-Requesting memory
- |
-LOS_KernelMalloc
- |
-Allocates memory from the heap memory pool if the requested memory is less than 16 KiB; allocates multiple contiguous physical pages for memory allocation if the requested memory is greater than 16 KiB.
- |
-
-LOS_KernelMallocAlign
- |
-Allocates memory with alignment attributes. The allocation rule is the same as that of the LOS_KernelMalloc API.
- |
-
-LOS_KernelFree
- |
-Releases the memory requested by LOS_KernelMalloc and LOS_KernelMallocAlign.
- |
-
-LOS_KernelRealloc
- |
-Reallocates the memory requested by LOS_KernelMalloc and LOS_KernelMallocAlign.
- |
-
-Others
- |
-LOS_PaddrQuery
- |
-Obtains the physical address based on the virtual address.
- |
-
-LOS_VmSpaceFree
- |
-Releases the process space, including the virtual memory region and page table.
- |
-
-LOS_VmSpaceReserve
- |
-Reserves a memory space in the process space.
- |
-
-LOS_VaddrToPaddrMmap
- |
-Maps the physical address region with the specified length to a virtual address region. You need to request the physical address region before the operation.
- |
-
-
-
-
-### How to Develop
+- If the page (for example, V0) containing the virtual address accessed by the CPU is mapped to a physical page (for example, P0), the CPU locates the page table entry corresponding to the process (for details, see [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md)"), accesses the physical memory based on the physical address information in the page table entry, and returns the content.
-To use APIs related to virtual memory:
+- If the page (for example, V2) containing the virtual address accessed by the CPU is not mapped to a physical page, the system triggers a page missing fault, requests a physical page, copies the corresponding information to the physical page, and updates the start address of the physical page to the page table entry. Then, the CPU can access specific code or data by executing the instruction for accessing the virtual memory again.
+
+ **Figure 1** Mapping between the virtual and physical memory addresses
+
+ 
+
+
+## Development Guidelines
+
+
+### Available APIs
+
+**Table 3** APIs of the virtual memory management module
-1. Obtain the process space structure using the APIs for obtaining the process space, and access the structure information.
-2. Perform the following operations on the virtual address region:
- - Call **LOS\_RegionAlloc** to request a virtual address region.
+| API| Description|
+| -------- | -------- |
+| LOS_CurrSpaceGet | Obtains the pointer to the current process space structure.|
+| LOS_SpaceGet | Obtains the pointer to the process space structure corresponding to the virtual address.|
+| LOS_GetKVmSpace | Obtains the pointer to the kernel process space structure.|
+| LOS_GetVmallocSpace | Obtains the pointer to the vmalloc space structure.|
+| LOS_GetVmSpaceList | Obtains the pointer to the process space linked list.|
- - Call **LOS\_RegionFind** and **LOS\_RegionRangeFind** to check whether the corresponding address region exists.
- - Call **LOS\_RegionFree** to release a virtual address region.
+**Table 4** Operations related to the virtual address region
+
+| API| Description|
+| -------- | -------- |
+| LOS_RegionFind | Searches for and returns the virtual address region corresponding to the specified address in the process space.|
+| LOS_RegionRangeFind | Searches for and returns the virtual address region corresponding to the specified address range in the process space.|
+| LOS_IsRegionFileValid | Checks whether the virtual address region is mapped to a file.|
+| LOS_RegionAlloc | Requests a free virtual address region.|
+| LOS_RegionFree | Releases a specific region in the process space.|
+| LOS_RegionEndAddr | Obtains the end address of the specified address region.|
+| LOS_RegionSize | Obtains the size of a region.|
+| LOS_IsRegionTypeFile | Checks whether the address region is a file memory mapping.|
+| LOS_IsRegionPermUserReadOnly | Checks whether the address region is read-only in the user space.|
+| LOS_IsRegionFlagPrivateOnly | Checks whether the address region has private attributes.|
+| LOS_SetRegionTypeFile | Sets the file memory mapping attributes. |
+| LOS_IsRegionTypeDev | Checks whether the address region is device memory mapping.|
+| LOS_SetRegionTypeDev | Sets the device memory mapping attributes. |
+| LOS_IsRegionTypeAnon | Checks whether the address region is an anonymous mapping.|
+| LOS_SetRegionTypeAnon | Sets the anonymous mapping attributes. |
+
+**Table 5** APIs for address verification
+
+| API| Description|
+| -------- | -------- |
+| LOS_IsUserAddress | Checks whether the address is in the user space.|
+| LOS_IsUserAddressRange | Checks whether the address region is in the user space.|
+| LOS_IsKernelAddress | Checks whether the address is in the kernel space.|
+| LOS_IsKernelAddressRange | Checks whether the address region is in the kernel space.|
+| LOS_IsRangeInSpace | Checks whether the address region is in the process space.|
+
+**Table 6** APIs for vmalloc operations
+
+| API| Description|
+| -------- | -------- |
+| LOS_VMalloc | Requests memory using **vmalloc**.|
+| LOS_VFree | Releases memory using **vmalloc**.|
+| LOS_IsVmallocAddress | Checks whether the address is requested using **vmalloc**. |
+
+**Table 7** APIs for memory allocation
+
+| API| Description|
+| -------- | -------- |
+| LOS_KernelMalloc | Allocates memory from the heap memory pool if the requested memory is less than 16 KiB; allocates multiple contiguous physical pages if the requested memory is greater than 16 KiB. |
+| LOS_KernelMallocAlign | Allocates memory with alignment attributes. The allocation rule is the same as that of the **LOS_KernelMalloc** API.|
+| LOS_KernelFree | Releases the memory requested by **LOS_KernelMalloc** and **LOS_KernelMallocAlign**.|
+| LOS_KernelRealloc | Reallocates the memory requested by **LOS_KernelMalloc** and **LOS_KernelMallocAlign**.|
+
+**Table 8** Other APIs
+
+| API | Description |
+| -------- | -------- |
+| LOS_PaddrQuery | Obtains the physical address based on the virtual address. |
+| LOS_VmSpaceFree | Releases the process space, including the virtual memory region and page table. |
+| LOS_VmSpaceReserve | Reserves a memory space in the process space. |
+| LOS_VaddrToPaddrMmap | Maps the physical address region with the specified length to a virtual address region. You need to request the physical address region before the operation. |
+
+
+### How to Develop
+
+To use APIs related to virtual memory:
-3. Call **vmalloc** and memory requesting APIs to apply for memory in the kernel as demanded.
+1. Obtain the process space structure using the APIs for obtaining the process space, and access the structure information.
+2. Perform the following operations on the virtual address region:
+ - Call **LOS_RegionAlloc** to request a virtual address region.
+ - Call **LOS_RegionFind** and **LOS_RegionRangeFind** to check whether the corresponding address region exists.
+ - Call **LOS_RegionFree** to release a virtual address region.
-> **NOTE:**
->The physical memory requested by using the memory requesting APIs must be contiguous. If the system cannot provide a large number of contiguous memory blocks, the request fails. Therefore, the memory requesting APIs are recommended for requesting small memory blocks. **vmalloc** is recommended for requesting non-contiguous physical memory. However, the memory is allocated in the unit of pages \(4096 bytes/page in the current system\). If you want memory that is an integer multiple of a page, you can use **vmalloc**. For example, you can use **vmalloc** to request memory for file reading in a file system, which demands a large cache.
+3. Call **vmalloc** APIs (see table 6) and memory allocation APIs (see table 7) to apply for memory in the kernel as required.
+>  **NOTE**
+>
+> The physical memory requested by using the memory allocation APIs must be contiguous. If the system cannot provide a large number of contiguous memory blocks, the request fails. Therefore, the memory allocation APIs are recommended for requesting small memory blocks.
+>
+> **vmalloc** APIs are recommended for requesting non-contiguous physical memory. However, the memory is allocated in the unit of pages (4096 bytes/page in the current system). If you want memory that is an integer multiple of a page, you can use **vmalloc** APIs. For example, you can use **vmalloc** to request memory for file reading in a file system, which demands a large cache.
diff --git a/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md b/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md
index 97f8b77622ee03c6701df1e0b426778c8a956ddd..18558986daf9a5cf45e72a771aa8dc6e98454876 100644
--- a/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md
+++ b/en/device-dev/kernel/kernel-small-basic-trans-rwlock.md
@@ -1,128 +1,85 @@
# RW Lock
-## Basic Concepts
+## Basic Concepts
-Similar to a mutex, a read-write lock \(RW lock\) can be used to synchronize tasks in the same process. Different from a mutex, an RW lock allows concurrent access for read operations and exclusive access for write operations.
+Similar to a mutex, a read-write lock (RW lock) can be used to synchronize tasks in the same process. Different from a mutex, an RW lock allows concurrent access for read operations and exclusive access for write operations.
An RW lock has three states: locked in read mode, locked in write mode, and unlocked.
Observe the following rules when using RW locks:
-- If there is no lock in write mode in the protected area, any task can add a lock in read mode.
-- A lock in write mode can be added only when the protected area is in the unlocked state.
+- If there is no lock in write mode in the protected area, any task can add a lock in read mode.
+
+- A lock in write mode can be added only when the protected area is in the unlocked state.
In a multi-task environment, multiple tasks may access the same shared resource. A lock in read mode allows access to a protected area in shared mode, and a lock in a write mode allows exclusive access to the shared resource.
This sharing-exclusive manner is suitable for a multi-task environment where the data read operations are far more than data write operations. It can improve multi-task concurrency of the application.
-## Working Principles
+
+## Working Principles
How does an RW lock implement lock in read mode and lock in write mode to control read/write access of multiple tasks?
-- If task A acquires the lock in write mode for the first time, other tasks cannot acquire or attempt to acquire the lock in read mode.
-
-- If task A acquires the lock in read mode, the RW lock count increments by 1 when a task acquires or attempts to acquire the lock in read mode.
-
-## Development Guidelines
-
-### Available APIs
-
-**Table 1** Read/write lock module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Creating and deleting an RW lock
- |
-LOS_RwlockInit
- |
-Creates an RW lock.
- |
-
-LOS_RwlockDestroy
- |
-Deletes the specified RW lock.
- |
-
-Requesting a lock in read mode
- |
-LOS_RwlockRdLock
- |
-Requests the specified lock in read mode.
- |
-
-LOS_RwlockTryRdLock
- |
-Attempts to request the specified lock in read mode.
- |
-
-Requesting a lock in write mode
- |
-LOS_RwlockWrLock
- |
-Requests the specified lock in write mode.
- |
-
-LOS_RwlockTryWrLock
- |
-Attempts to request the specified lock in write mode.
- |
-
-Releasing an RW lock
- |
-LOS_RwlockUnLock
- |
-Releases the specified RW lock.
- |
-
-Verifying RW lock validity
- |
-LOS_RwlockIsValid
- |
-Checks the validity of an RW lock.
- |
-
-
-
-
-### How to Develop
+- If task A acquires the lock in write mode for the first time, other tasks cannot acquire or attempt to acquire the lock in read mode.
+
+- If task A acquires the lock in read mode, the RW lock count increments by 1 when a task acquires or attempts to acquire the lock in read mode.
+
+
+## Development Guidelines
+
+
+### Available APIs
+
+**Table 1** APIs of the RW lock module
+
+| API| Description|
+| -------- | -------- |
+| LOS_RwlockInit| Creates an RW lock.|
+| LOS_RwlockDestroy| Deletes an RW lock.|
+| LOS_RwlockRdLock| Requests the specified lock in read mode.|
+| LOS_RwlockTryRdLock| Attempts to request a lock in read mode.|
+| LOS_RwlockWrLock| Requests the specified lock in write mode.|
+| LOS_RwlockTryWrLock| Attempts to request a lock in write mode.|
+| LOS_RwlockUnLock| Releases the specified RW lock.|
+| LOS_RwlockIsValid| Checks the validity of an RW lock.|
+
+
+### How to Develop
The typical development process is as follows:
-1. Call **LOS\_RwlockInit** to create an RW lock.
+1. Call **LOS_RwlockInit** to create an RW lock.
-2. Call **LOS\_RwlockRdLock** to request a lock in read mode or call **LOS\_RwlockWrLock** to request a lock in write mode.
+2. Call **LOS_RwlockRdLock** to request a lock in read mode or call **LOS_RwlockWrLock** to request a lock in write mode.
-If a lock in read mode is requested:
+ If a lock in read mode is requested:
-- If the lock is not held, the read task can acquire the lock.
-- If the lock is held, the read task acquires the lock and is executed based on the task priority.
-- If the lock in write mode is held by another task, the task cannot acquire the lock until the lock in write mode is released.
+ - If the lock is not held, the read task can acquire the lock.
-If a lock in write mode is requested:
+ - If the lock is held, the read task acquires the lock and is executed based on the task priority.
-- If the lock is not held or if the task that holds the lock in read mode is the one that requests the lock in write mode, the task acquires the lock in write mode immediately.
-- If the lock already has a lock in read mode and the read task has a higher priority, the current task is suspended until the lock in read mode is released.
+ - If the lock in write mode is held by another task, the task cannot acquire the lock until the lock in write mode is released.
-3. There are three types of locks in read mode and write mode: non-block mode, permanent block mode, and scheduled block mode. The difference lies in the task suspension time.
+ If a lock in write mode is requested:
+
+ - If the lock is not held or if the task that holds the lock in read mode is the one that requests the lock in write mode, the task acquires the lock in write mode immediately.
-4. Call **LOS\_RwlockUnLock** to release an RW lock.
+ - If the lock already has a lock in read mode and the read task has a higher priority, the current task is suspended until the lock in read mode is released.
-- If tasks are blocked by the specified RW lock, the task with the highest priority is woken up, enters the Ready state, and is scheduled.
+3. There are three types of locks in read mode and write mode: non-block mode, permanent block mode, and scheduled block mode. The difference lies in the task suspension time.
-- If no task is blocked by the specified RW lock, the RW lock is released.
+4. Call **LOS_RwlockUnLock** to release an RW lock.
-5. Call **LOS\_RwlockDestroy** to delete an RW lock.
+ - If tasks are blocked by the specified RW lock, the task with the highest priority is woken up, enters the Ready state, and is scheduled.
+ - If no task is blocked by the specified RW lock, the RW lock is released.
-> **NOTE:**
->- The RW lock cannot be used in the interrupt service program.
->- When using the LiteOS-A kernel, the OpenHarmony must ensure real-time task scheduling and avoid long-time task blocking. Therefore, an RW lock must be released as soon as possible after use.
->- When an RW lock is held by a task, the task priority cannot be changed by using APIs such as **LOS\_TaskPriSet**.
+5. Call **LOS_RwlockDestroy** to delete an RW lock.
+ >  **NOTE**
+ > - The RW lock cannot be used in the interrupt service program.
+ >
+ > - The LiteOS-A kernel used in the RTOS must ensure real-time task scheduling and avoid long-time task blocking. Therefore, RW locks must be released as soon as possible after use.
+ >
+ > - When an RW lock is held by a task, the task priority cannot be changed by using APIs, such as **LOS_TaskPriSet**.
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md
index d82858014b528de1c82b4313cfc3a0e0312a9540..e2bf8109175e2498239134fd959f71326d263bf9 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-fat.md
@@ -1,40 +1,49 @@
# FAT
-## Basic Concepts
+## Basic Concepts
-File Allocation Table \(FAT\) is a file system developed for personal computers. It consists of the DOS Boot Record \(DBR\) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, the number of the next cluster of the file, and whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, and also restrict the maximum file size in the system. The FAT file system supports multiple media, especially removable media \(such as USB flash drives, SD cards, and removable hard drives\). The FAT file system ensures good compatibility between embedded devices and desktop systems \(such as Windows and Linux\) and facilitates file management.
+File Allocation Table (FAT) is a file system developed for personal computers. It consists of the DOS Boot Record (DBR) region, FAT region, and Data region. Each entry in the FAT region records information about the corresponding cluster in the storage device. The cluster information includes whether the cluster is used, number of the next cluster of the file, whether the file ends with the cluster. The FAT file system supports multiple formats, such as FAT12, FAT16, and FAT32. The numbers 12, 16, and 32 indicate the number of bits per cluster within the FAT, and also restrict the maximum file size in the system. The FAT file system supports multiple media, especially removable media (such as USB flash drives, SD cards, and removable hard drives). The FAT file system ensures good compatibility between embedded devices and desktop systems (such as Windows and Linux) and facilitates file management.
The OpenHarmony kernel supports FAT12, FAT16, and FAT32 file systems. These file systems require a tiny amount of code to implement, use less resources, support a variety of physical media, and are tailorable and compatible with Windows and Linux systems. They also support identification of multiple devices and partitions. The kernel supports multiple partitions on hard drives and allows creation of the FAT file system on the primary partition and logical partition.
-## Working Principles
+
+## Working Principles
This document does not include the FAT design and physical layout. You can find a lot of reference on the Internet.
-The OpenHarmony LiteOS-A kernel uses block cache \(Bcache\) to improve FAT performance. When read and write operations are performed, Bcache caches the sectors close to the read and write sectors to reduce the number of I/Os and improve performance. The basic cache unit of Bcache is block. The size of each block is the same. By default, there are 28 blocks, and each block caches data of 64 sectors. When the Bcache dirty block rate \(number of dirty sectors/total number of sectors\) reaches the threshold, writeback is triggered and cached data is written back to disks. You can manually call **sync** and **fsync** to write data to disks if you want. Some FAT APIs \(such as **close** and **umount**\) may also trigger writeback operations. However, you are advised not to use them to trigger writeback.
+The OpenHarmony LiteOS-A kernel uses block cache (Bcache) to improve FAT performance. When read and write operations are performed, Bcache caches the sectors close to the read and write sectors to reduce the number of I/Os and improve performance. The basic cache unit of Bcache is block. The size of each block is the same. By default, there are 28 blocks, and each block caches data of 64 sectors. When the Bcache dirty block rate (number of dirty sectors/total number of sectors) reaches the threshold, writeback is triggered and cached data is written back to disks. You can manually call **sync** and **fsync** to write data to disks if you want. Some FAT APIs (such as **close** and **umount**) may also trigger writeback operations. However, you are advised not to use them to trigger writeback.
+
-## Development Guidelines
+## Development Guidelines
-### How to Develop
+
+ **How to Develop**
The development process involves mounting partitions, managing files and directories, and unmounting partitions.
-The device name of the SD card or MMC is **mmcblk\[x\]p\[y\]**, and the file system type is **vfat**.
+The device name of the SD card or MMC is **mmcblk[x]p[y]**, and the file system type is **vfat**.
Example:
+
```
mount("/dev/mmcblk0p0", "/mnt", "vfat", 0, NULL);
```
-> **NOTE**
->- The size of a single FAT file cannot be greater than 4 GiB.
->- When there are two SD card slots, the first card inserted is card 0, and that inserted later is card 1.
->- When multi-partition is enabled and there are multiple partitions, the device node **/dev/mmcblk0** \(primary device\) registered by card 0 and **/dev/mmcblk0p0** \(secondary device\) are the same device. In this case, you cannot perform operations on the primary device.
->- Before removing an SD card, close the open files and directories and unmount the related nodes. Otherwise, SD card exceptions or memory leaks may occur.
->- Before performing the **format** operation, unmount the mount point.
->- After the Bcache feature takes effect, note the following:
-> - When **MS\_NOSYNC** is carried in the **mount** function, FAT does not proactively write the content in the cache back to the storage device. The FAT-related APIs **open**, **close**, **unlink**, **rename**, **mkdir**, **rmdir**, and **truncate** do not automatically perform the **sync** operation, which improves the operation speed. However, the upper layer must actively invoke the **sync** operation to synchronize data. Otherwise, data loss may occur.
-> - Bcache provides scheduled writeback. After **LOSCFG\_FS\_FAT\_CACHE\_SYNC\_THREAD** is enabled in **menuconfig**, the OpenHarmony kernel creates a scheduled task to write the Bcache data back to disks. By default, the kernel checks the dirty block rate in the Bcache every 5 seconds. If the dirty block rate exceeds 80%, the **sync** operation will be performed to write all dirty data in the Bcache to disks. You can call **LOS\_SetSyncThreadPrio**, **LOS\_SetSyncThreadInterval**, and **LOS\_SetDirtyRatioThreshold** to set the task priority, flush interval, and dirty block rate threshold, respectively.
-> - The cache has 28 blocks by default, and each block has 64 sectors.
-
+>  **NOTE**
+> - The size of a single FAT file cannot be greater than 4 GiB.
+>
+> - When there are two SD card slots, the first card inserted is card 0, and that inserted later is card 1.
+>
+> - When multi-partition is enabled and there are multiple partitions, the device node **/dev/mmcblk0** (primary device) registered by card 0 and **/dev/mmcblk0p0** (secondary device) are the same device. In this case, you cannot perform operations on the primary device.
+>
+> - Before removing an SD card, close the open files and directories and unmount the related nodes. Otherwise, SD card exceptions or memory leaks may occur.
+>
+> - Before performing the **format** operation, unmount the mount point.
+>
+> - After the Bcache feature takes effect, note the following:
+> - When **MS_NOSYNC** is carried in the **mount** function, FAT does not proactively write the content in the cache back to the storage device. The FAT-related APIs **open**, **close**, **unlink**, **rename**, **mkdir**, **rmdir**, and **truncate** do not automatically perform the **sync** operation, which improves the operation speed. However, the upper layer must actively invoke the **sync** operation to synchronize data. Otherwise, data loss may occur.
+>
+> - Bcache provides scheduled writeback. After **LOSCFG_FS_FAT_CACHE_SYNC_THREAD** is enabled in **menuconfig**, the OpenHarmony kernel creates a scheduled task to write the Bcache data back to disks. By default, the kernel checks the dirty block rate in the Bcache every 5 seconds. If the dirty block rate exceeds 80%, the **sync** operation will be performed to write all dirty data in the Bcache to disks. You can call **LOS_SetSyncThreadPrio**, **LOS_SetSyncThreadInterval**, and **LOS_SetDirtyRatioThreshold** to set the task priority, flush interval, and dirty block rate threshold, respectively.
+> - The cache has 28 blocks by default, and each block has 64 sectors.
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
index d205531eb3d7ac83645ce872669a645d0d4d5aa5..57e01b4a58d9430f167b89c0cd03f6b4ded73dbf 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md
@@ -1,135 +1,140 @@
# NFS
-## Basic Concepts
+## Basic Concepts
-NFS allows you to share files across hosts and OSs over a network. You can treat NFS as a file system service, which is equivalent to folder sharing in the Windows OS to some extent.
+Network File System (NFS) allows you to share files across hosts and OSs over a network. You can treat NFS as a file system service, which is equivalent to folder sharing in the Windows OS to some extent.
-## Working Principles
-The NFS of the OpenHarmony LiteOS-A kernel acts as an NFS client. The NFS client can mount the directory shared by a remote NFS server to the local machine and run the programs and shared files without occupying the storage space of the current system. To the local machine, the directory on the remote server is like its disk.
-
-## Development Guidelines
-
-1. Create an NFS server.
-
-The following uses the Ubuntu OS as an example to describe how to configure an NFS server.
-
-- Install the NFS server software.
-
-Set the download source of the Ubuntu OS when the network connection is normal.
-
-```
-sudo apt-get install nfs-kernel-server
-```
+## Working Principles
-- Create a directory for mounting and assign full permissions for the directory.
-
-```
-mkdir -p /home/sqbin/nfs
-sudo chmod 777 /home/sqbin/nfs
-```
-
-- Configure and start the NFS server.
-
-Append the following line in the **/etc/exports** file:
-
-```
-/home/sqbin/nfs *(rw,no_root_squash,async)
-```
-
-**/home/sqbin/nfs** is the root directory shared by the NFS server.
-
-Start the NFS server.
+The NFS of the OpenHarmony LiteOS-A kernel acts as an NFS client. The NFS client can mount the directory shared by a remote NFS server to the local machine and run the programs and shared files without occupying the storage space of the current system. To the local machine, the directory on the remote server is like its disk.
-```
-sudo /etc/init.d/nfs-kernel-server start
-```
-Restart the NFS server.
+## Development Guidelines
-```
-sudo /etc/init.d/nfs-kernel-server restart
-```
+1. Create an NFS server.
-1. Configure the board as an NFS client.
+ The following uses the Ubuntu OS as an example to describe how to configure an NFS server.
-In this section, the NFS client is a device running the OpenHarmony kernel.
+ - Install the NFS server software.
-- Set the hardware connection.
+ Set the download source of the Ubuntu OS when the network connection is normal.
-Connect the OpenHarmony kernel device to the NFS server. Set their IP addresses in the same network segment. For example, set the IP address of the NFS server to **10.67.212.178/24** and set the IP address of the OpenHarmony kernel device to **10.67.212.3/24**. Note that the preceding IP addresses are private IP addresses used as examples. You need to use your actual IP addresses.
+ ```
+ sudo apt-get install nfs-kernel-server
+ ```
-You can run the **ifconfig** command to check the OpenHarmony kernel device's IP address.
+ - Create a directory for mounting and assign full permissions for the directory.
-- Start the network and ensure that the network between the board and NFS server is normal.
+ ```
+ mkdir -p /home/sqbin/nfs
+ sudo chmod 777 /home/sqbin/nfs
+ ```
-Start the Ethernet or another type of network, and then run **ping** to check whether the network connection to the server is normal.
+ - Configure and start the NFS server.
-```
-OHOS # ping 10.67.212.178
-[0]Reply from 10.67.212.178: time=1ms TTL=63
-[1]Reply from 10.67.212.178: time=0ms TTL=63
-[2]Reply from 10.67.212.178: time=1ms TTL=63
-[3]Reply from 10.67.212.178: time=1ms TTL=63
---- 10.67.212.178 ping statistics ---
-4 packets transmitted, 4 received, 0 loss
-```
+ Append the following line in the **/etc/exports** file:
-Initialize the NFS client.
+ ```
+ /home/sqbin/nfs *(rw,no_root_squash,async)
+ ```
+
+ **/home/sqbin/nfs** is the root directory shared by the NFS server.
+
+ Start the NFS server.
-```
-OHOS # mkdir /nfs
-OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
-```
+ ```
+ sudo /etc/init.d/nfs-kernel-server start
+ ```
+
+ Restart the NFS server.
-If the following information is displayed, the NFS client is initialized.
+ ```
+ sudo /etc/init.d/nfs-kernel-server restart
+ ```
-```
-OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
-Mount nfs on 10.67.212.178:/home/sqbin/nfs, uid:1011, gid:1000
-Mount nfs finished.
-```
+2. Configure the board as an NFS client.
-This command mounts the **/home/sqbin/nfs** directory on the NFS server whose IP address is 10.67.212.178 to the **/nfs** directory on the OpenHarmony kernel device.
+ In this section, the NFS client is a device running the OpenHarmony kernel.
-> **NOTE:**
->This section assumes that the NFS server is available, that is, the **/home/sqbin/nfs** directory on the NFS server 10.67.212.178 is accessible.
->The **mount** command format is as follows:
->```
->mount nfs
->```
->- **SERVER\_IP** indicates the IP address of the server.
->- **SERVER\_PATH** indicates the path of the shared directory on the NFS server.
->- **CLIENT\_PATH** indicates the NFS path on the local device.
->- **nfs** indicates the path to which the remote shared directory is mounted on the local device.
->Replace the parameters as required.
->If you do not want to restrict the NFS access permission, set the permission of the NFS root directory to **777** on the Linux CLI.
->```
->chmod -R 777 /home/sqbin/nfs
->```
->The NFS client setting is complete, and the NFS file system has been mounted.
+ - Set the hardware connection.
-1. Share files using NFS.
+ Connect the OpenHarmony kernel device to the NFS server. Set their IP addresses in the same network segment. For example, set the IP address of the NFS server to **10.67.212.178/24** and the IP address of the OpenHarmony kernel device to
+ **10.67.212.3/24**. Note that this IP address is an intranet private IP address. Use the actual IP address.
-Create the **dir** directory on the NFS server and save the directory. Run the **ls** command in the OpenHarmony kernel.
+ You can run the **ifconfig** command to check the OpenHarmony kernel device's IP address.
-```
-OHOS # ls /nfs
-```
+ - Start the network and ensure that the network between the board and NFS server is normal.
-The following information is returned from the serial port:
+ Start the Ethernet or another type of network, and then run **ping** to check whether the network connection to the server is normal.
-```
-OHOS # ls /nfs
-Directory /nfs:
-drwxr-xr-x 0 u:0 g:0 dir
-```
-The **dir** directory created on the NFS server has been synchronized to the **/nfs** directory on the client \(OpenHarmony kernel system\).
+ ```
+ OHOS # ping 10.67.212.178
+ [0]Reply from 10.67.212.178: time=1ms TTL=63
+ [1]Reply from 10.67.212.178: time=0ms TTL=63
+ [2]Reply from 10.67.212.178: time=1ms TTL=63
+ [3]Reply from 10.67.212.178: time=1ms TTL=63
+ --- 10.67.212.178 ping statistics ---
+ 4 packets transmitted, 4 received, 0 loss
+ ```
+
+ Initialize the NFS client.
-Similarly, you can create files and directories on the client \(OpenHarmony kernel system\) and access them from the NFS server.
+ ```
+ OHOS # mkdir /nfs
+ OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
+ ```
+
+ If the following information is displayed, the NFS client is initialized.
-> **NOTE:**
->Currently, the NFS client supports some NFS v3 specifications. Therefore, the NFS client is not fully compatible with all types of NFS servers. You are advised to use the Linux NFS server to perform the development.
+ ```
+ OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000
+ Mount nfs on 10.67.212.178:/home/sqbin/nfs, uid:1011, gid:1000
+ Mount nfs finished.
+ ```
+
+ This command mounts the **/home/sqbin/nfs** directory on the NFS server (IP address: 10.67.212.178) to the **/nfs** directory on the OpenHarmony kernel device.
+ >  **NOTE**
+ >
+ > This example assumes that the NFS server is available, that is, the **/home/sqbin/nfs** directory on the NFS server 10.67.212.178 is accessible.
+ >
+ > The **mount** command format is as follows:
+ >
+ > ```
+ > mount nfs
+ > ```
+ >
+ > **SERVER_IP** indicates the IP address of the server; **SERVER_PATH** indicates the path of the shared directory on the NFS server; **CLIENT_PATH** indicates the NFS path on the local device; **nfs** indicates the path to which the remote shared directory is mounted on the local device. Replace the parameters as required.
+ >
+ > If you do not want to restrict the NFS access permission, set the permission of the NFS root directory to **777** on the Linux CLI.
+ >
+ > ```
+ > chmod -R 777 /home/sqbin/nfs
+ > ```
+ >
+ > The NFS client setting is complete, and the NFS file system is mounted.
+
+3. Share files using NFS.
+
+ Create the **dir** directory on the NFS server. Run the **ls** command in the OpenHarmony kernel.
+
+ ```
+ OHOS # ls /nfs
+ ```
+
+ The following information is returned from the serial port:
+
+ ```
+ OHOS # ls /nfs
+ Directory /nfs:
+ drwxr-xr-x 0 u:0 g:0 dir
+ ```
+
+ The **dir** directory created on the NFS server has been synchronized to the **/nfs** directory on the client (OpenHarmony kernel system). Similarly, you can create files and directories on the client (OpenHarmony kernel system) and access them from the NFS server.
+
+ >  **NOTE**
+ >
+ > Currently, the NFS client supports some NFS v3 specifications. Therefore, the NFS client is not fully compatible with all types of NFS servers. You are advised to use the Linux NFS server to perform the development.
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md
index a9b031e9f72b535f22f3083491c5b76c08459e3f..261eae927bd78029daead0a19c56aca175a8623e 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-procfs.md
@@ -1,28 +1,32 @@
# procfs
-## Basic Concepts
+## Basic Concepts
-The proc filesystem \(procfs\) is a virtual file system that displays process or other system information in a file-like structure. It is more convenient to obtain system information in file operation mode than API calling mode.
+The proc filesystem (procfs) is a virtual file system that displays process or other system information in a file-like structure. It is more convenient to obtain system information in file operation mode than API calling mode.
-## Working Principles
-In the OpenHarmony kernel, procfs is automatically mounted to the **/proc** directory during startup. Only the kernel module can create file nodes to provide the query service.
+## Working Principles
-## Development Guidelines
+In the OpenHarmony kernel, procfs is automatically mounted to the **/proc** directory during startup. Only the kernel module can create file nodes to provide the query service.
-To create a procfs file, you need to use **ProcMkdir** to create a directory and use **CreateProcEntry** to create a file. The development of the file node function is to hook the read and write functions to the file created by **CreateProcEntry**. When the procfs file is read or written, the hooked functions will be called to implement custom functions.
-### Development Example
+## Development Guidelines
-The following describes how to create the **/proc/hello/world** file to implement the following functions:
+To create a procfs file, you need to use **ProcMkdir** to create a directory and use **CreateProcEntry** to create a file. The development of the file node function is to hook the read and write functions to the file created by **CreateProcEntry**. When the procfs file is read or written, the hooked functions will be called to implement custom functions.
-1. Create a file in **/proc/hello/world**.
+
+### Development Example
+
+The following describes how to create the **/proc/hello/world** file to implement the following functions:
+
+1. Create a file in **/proc/hello/world**.
2. Read the file. When the file is read, "HelloWorld!" is returned.
3. Write the file and print the data written in the file.
+
```
#include "proc_fs.h"
@@ -48,7 +52,7 @@ static const struct ProcFileOperations HELLO_WORLD_OPS = {
void HelloWorldInit(void)
{
- /* Create the hello directory.*/
+ /* Create the hello directory. */
struct ProcDirEntry *dir = ProcMkdir("hello", NULL);
if (dir == NULL) {
PRINT_ERR("create dir failed!\n");
@@ -69,7 +73,8 @@ void HelloWorldInit(void)
**Verification**
-After the OS startup, run the following command in the shell:
+After the OS startup, run the following commands in the shell:
+
```
OHOS # cat /proc/hello/world
@@ -77,4 +82,3 @@ OHOS # Hello World!
OHOS # echo "yo" > /proc/hello/world
OHOS # your input is: yo
```
-
diff --git a/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md b/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md
index 975baff8c25166e4e9afa703c4208aa03af5d066..ee785aeffd5fa016fe4a605183d68324aaff73dc 100644
--- a/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md
+++ b/en/device-dev/kernel/kernel-small-bundles-fs-support-ramfs.md
@@ -1,60 +1,43 @@
# Ramfs
-## Basic Concepts
-Ramfs is a RAM-based file system whose size can be dynamically adjusted. Ramfs does not have a backing store. Directory entries and page caches are allocated when files are written into ramfs. However, data is not written back to any other storage medium. This means that data will be lost after a power outage.
-
-## Working Principles
-
-Ramfs stores all files in RAM, and read/write operations are performed in RAM. Ramfs is generally used to store temporary data or data that needs to be frequently modified, such as the **/tmp** and **/var** directories. Using ramfs reduces the read/write loss of the memory and improves the data read/write speed.
-
-## Development Guidelines
+## Basic Concepts
+Ramfs is a RAM-based file system whose size can be dynamically adjusted. Ramfs does not have a backing store. Directory entries and page caches are allocated when files are written into ramfs. However, data is not written back to any other storage medium. This means that data will be lost after a power outage.
+## Working Principles
+Ramfs stores all files in RAM, and read/write operations are performed in RAM. Ramfs is generally used to store temporary data or data that needs to be frequently modified, such as the **/tmp** and **/var** directories. Using ramfs reduces the read/write loss of the memory and improves the data read/write speed.
+## Development Guidelines
Mount:
-
```
mount(NULL, "/dev/shm", "ramfs", 0, NULL)
```
-
-Create a directory:
-
+Create a directory:
```
mkdir(pathname, mode)
```
-
Create a file:
-
```
open(pathname, O_NONBLOCK | O_CREAT | O_RDWR, mode)
```
-
-Read a directory:
-
+Read a directory:
```
dir = opendir(pathname)
ptr = readdir(dir)
closedir(dir)
```
-
-Delete a file:
-
+Delete a file:
```
unlink(pathname)
```
-
Delete a directory:
-
```
rmdir(pathname)
```
-
-Unmount:
-
+Unmount:
```
umount("/dev/shm")
```
-
-> **CAUTION:**
->- A ramfs file system can be mounted only once. Once mounted to a directory, it cannot be mounted to other directories.
->- Ramfs is under debugging and disabled by default. Do not use it in formal products.
-
+>  **CAUTION**
+> - A ramfs file system can be mounted only once. Once mounted to a directory, it cannot be mounted to other directories.
+>
+> - Ramfs is under debugging and disabled by default. Do not use it in formal products.
diff --git a/en/device-dev/kernel/kernel-small-debug-shell-guide.md b/en/device-dev/kernel/kernel-small-debug-shell-guide.md
index d20dd2abf4420eb5f115171aafaa697108f38ed7..3bb07ddf59843ff76a2b7f4472ecc9a089f99421 100644
--- a/en/device-dev/kernel/kernel-small-debug-shell-guide.md
+++ b/en/device-dev/kernel/kernel-small-debug-shell-guide.md
@@ -1,164 +1,87 @@
-# Shell Command Development Guidelines
-
-
-## Development Guidelines
+# Shell Command Development
You can perform the following operations to add shell commands:
-1. Include the following header files:
-
- ```
- #include "shell.h"
- #include "shcmd.h"
- ```
-
-2. Register commands. You can register commands either statically or dynamically when the system is running. In most cases, static registration is widely used by common system commands, and dynamic registration is widely used by user commands.
-
- 1. Static registration:
-
- 1. Register a command using a macro.
-
- The prototype of the macro is as follows:
-
- ```
- SHELLCMD_ENTRY(l, cmdType, cmdKey, paraNum, cmdHook)
- ```
-
- **Table 1** Parameters of the SHELLCMD\_ENTRY macro
-
-
- Parameter
- |
- Description
- |
-
-
- l
- |
- Specifies the global variable name passed in static registration. Note that the name cannot be the same as other symbol names in the system.
- |
-
- cmdType
- |
- Specifies the command type, which can be any of the following:
- CMD_TYPE_EX: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter ls /ramfs, only /ramfs will be passed to the registration function, and ls will be masked.
- CMD_TYPE_STD: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed.
-
- |
-
- cmdKey
- |
- Specifies the command keyword, which is the name used to access a shell function.
- |
-
- paraNum
- |
- Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently.
- |
-
- cmdHook
- |
- Specifies the address of the execution function, that is, the function executed by the command.
- |
-
-
-
-
- Example:
-
- ```
- SHELLCMD_ENTRY(ls_shellcmd, CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
- ```
-
- 2. Add options to the **build/mk/liteos\_tables\_ldflags.mk** file.
-
- For example, when registering the **ls** command, add **-uls\_shellcmd** to the **build/mk/liteos\_tables\_ldflags.mk** file. **-u** is followed by the first parameter of **SHELLCMD\_ENTRY**.
-
- 2. Dynamic registration:
-
- The prototype of the function to register is as follows:
-
- ```
- UINT32 osCmdReg(CmdT ype cmdType, CHAR *cmdKey, UINT32 paraNum, CmdCallBackFunc cmdProc)
- ```
-
- **Table 2** Parameters of UINT32 osCmdReg
-
-
- Parameter
- |
- Description
- |
-
-
- cmdType
- |
- Specifies the command type, which can be any of the following:
- CMD_TYPE_EX: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter ls /ramfs, only /ramfs will be passed to the registration function, and ls will be masked.
- CMD_TYPE_STD: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed.
-
- |
-
- cmdKey
- |
- Specifies the command keyword, which is the name used to access a shell function.
- |
-
- paraNum
- |
- Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently. The default value is XARGS(0xFFFFFFFF).
- |
-
- cmdHook
- |
- Specifies the address of the execution function, that is, the function executed by the command.
- |
-
-
-
-
- Example:
-
- ```
- osCmdReg(CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
- ```
+1. Include header files.
- > **NOTE:**
- >The command keyword must be unique. That is, two different commands cannot share the same command keyword. Otherwise, only one command is executed.
- >When executing user commands sharing the same keyword, the shell executes only the first command in the **help** commands.
+
+ ```
+ #include "shell.h"
+ #include "shcmd.h"
+ ```
-3. Use the following function prototype to add built-in commands:
+2. Register commands.
- ```
- UINT32 osShellCmdLs(UINT32 argc, CHAR **argv)
- ```
+ You can register commands either statically or dynamically (with the system running). Generally, common system commands are registered statically, and user commands are registered dynamically.
- **Table 3** Parameters of osShellCmdLs
+ - Static registration
-
- Parameter
- |
- Description
- |
-
-
- argc
- |
- Specifies the number of parameters in the shell command.
- |
-
- argv
- |
- Specifies a pointer array, where each element points to a string. You can determine whether to pass the command keyword to the registration function by specifying the command type.
- |
-
-
-
+ 1. Register a command using a macro.
-4. Enter the shell command in either of the following methods:
- - Enter the shell command in a serial port tool.
+ The prototype of the macro is as follows:
- - Enter the shell command in the Telnet tool. For details, see [telnet](kernel-small-debug-shell-net-telnet.md).
+ ```
+ SHELLCMD_ENTRY(l, cmdType, cmdKey, paraNum, cmdHook)
+ ```
+ **Table 1** SHELLCMD_ENTRY parameters
+ | Parameter| Description|
+ | -------- | -------- |
+ | l | Specifies the global variable name passed in static registration. Note that the name cannot be the same as other symbol names in the system.|
+ | cmdType | Specifies the command type, which can be any of the following:
**CMD_TYPE_EX**: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter **ls /ramfs**, only **/ramfs** will be passed to the registration function and **ls** will be masked.
**CMD_TYPE_STD**: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed. |
+ | cmdKey | Specifies the command keyword, which is the name used to access a shell function.|
+ | paraNum | Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently.|
+ | cmdHook | Specifies the address of the execution function, that is, the function executed by the command.|
+ Example:
+
+ ```
+ SHELLCMD_ENTRY(ls_shellcmd, CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
+ ```
+
+
+ 2. Add options to the **build/mk/liteos_tables_ldflags.mk** file.
+
+ For example, when registering the **ls** command, add **-uls_shellcmd** to the **build/mk/liteos_tables_ldflags.mk** file. **-u** is followed by the first parameter of **SHELLCMD_ENTRY**.
+
+ - Dynamic registration
+
+ The prototype of the function to register is as follows:
+
+ ```
+ UINT32 osCmdReg(CmdT ype cmdType, CHAR *cmdKey, UINT32 paraNum, CmdCallBackFunc cmdProc)
+ ```
+ **Table 2** UINT32 osCmdReg parameters
+ | Parameter| Description|
+ | -------- | -------- |
+ | cmdType | Specifies the command type, which can be any of the following:
**CMD_TYPE_EX**: does not support standard command parameters and will mask the command keywords you entered. For example, if you enter **ls /ramfs**, only **/ramfs** will be passed to the registration function, and **ls** will be masked.
**CMD_TYPE_STD**: supports standard command parameters. All the characters you entered will be passed to the registration function after being parsed.|
+ | cmdKey | Specifies the command keyword, which is the name used to access a shell function.|
+ | paraNum | Specifies the maximum number of input parameters in the execution function to be called. This parameter is not supported currently. The default value is **XARGS(0xFFFFFFFF)**.|
+ | cmdHook | Specifies the address of the execution function, that is, the function executed by the command.|
+
+ Example:
+ ```
+ osCmdReg(CMD_TYPE_EX, "ls", XARGS, (CMD_CBK_FUNC)osShellCmdLs)
+ ```
+  NOTE
+ > The command keyword must be unique. That is, two different commands cannot share the same command keyword. Otherwise, only one command is executed. When executing user commands sharing the same keyword, the shell executes only the first command in the **help** commands.
+
+
+3. Use the following function prototype to add built-in commands:
+
+ ```
+ UINT32 osShellCmdLs(UINT32 argc, CHAR **argv)
+ ```
+
+ **Table 3** osShellCmdLs parameters
+
+ | Parameter| Description|
+ | -------- | -------- |
+ | argc | Specifies the number of parameters in the shell command.|
+ | argv | Specifies a pointer array, where each element points to a string. You can determine whether to pass the command keyword to the registration function by specifying the command type.|
+
+4. Enter the shell command in either of the following methods:
+
+ - Enter the shell command using a serial port tool.
+ - Enter the shell command using the Telnet tool. For details about how to use Telnet, see [telnet](../kernel/kernel-small-debug-shell-net-telnet.md).
diff --git a/en/device-dev/kernel/kernel-small-debug-shell-magickey.md b/en/device-dev/kernel/kernel-small-debug-shell-magickey.md
index 95dd7f69f0160ae301c51a210ddb51c3c357728b..80248ba4e5fbc59fbef823ca8b34e8584709c243 100644
--- a/en/device-dev/kernel/kernel-small-debug-shell-magickey.md
+++ b/en/device-dev/kernel/kernel-small-debug-shell-magickey.md
@@ -1,42 +1,36 @@
# Magic Key
-## When to Use
+## When to Use
-When the system does not respond, you can use the magic key to check whether the system is locked and interrupted \(the magic key also does not respond\) or view the system task running status.
+When the system does not respond, you can use the magic key function to check whether the system is suspended by an interrupt lock (the magic key also does not respond) or view the system task running status.
-If an interrupt is responded, you can use the magic key to check the task CPU usage \(**cpup**\) and find out the task with the highest CPU usage. Generally, the task with a higher priority preempts the CPU resources.
+If interrupts are responded, you can use the magic key to check the task CPU usage (**cpup**) and find out the task with the highest CPU usage. Generally, the task with a higher priority preempts the CPU resources.
-## How to Use
-1. Configure the macro **LOSCFG\_ENABLE\_MAGICKEY**.
+## How to Use
-The magic key depends on the **LOSCFG\_ENABLE\_MAGICKEY** macro. Before using the magic key, select **Enable MAGIC KEY** on **menuconfig**.
+1. Configure the macro **LOSCFG_ENABLE_MAGICKEY**.
-**Enable MAGIC KEY**: **Debug** ---\> **Enable MAGIC KEY**
+ The magic key depends on the **LOSCFG_ENABLE_MAGICKEY** macro. Before using the magic key, select **Enable MAGIC KEY** (**Debug** ---> **Enable MAGIC KEY**) on **menuconfig**. The magic key cannot be used if this option is disabled.
-The magic key cannot be used if this macro is disabled.
+ >  **NOTE**
+ >
+ > On **menuconfig**, you can move the cursor to **LOSCFG_ENABLE_MAGICKEY** and enter a question mark (?) to view help Information.
+
+2. Press **Ctrl+R** to enable the magic key.
-> **NOTE:**
->On **menuconfig**, you can move the cursor to **LOSCFG\_ENABLE\_MAGICKEY** and type a question mark \(?\) to view help information.
+ When the UART or USB-to-virtual serial port is connected, press **Ctrl+R**. If "Magic key on" is displayed, the magic key is enabled. To disable it, press **Ctrl+R** again. If "Magic key off" is displayed, the magic key is disabled.
-2. Press **Ctrl+R** to enable the magic key.
+ The functions of the magic key are as follows:
-When the UART or USB-to-virtual serial port is connected, press **Ctrl+R**. If "Magic key on" is displayed, the magic key is enabled.
+ - **Ctrl+Z**: displays help information about the related magic keys.
-To disable the magic key, press **Ctrl+R** again. If "Magic key off" is displayed, the magic key is disabled.
+ - **Ctrl+T**: displays task information.
-You can use the magic key combinations as follows:
-
-- **Ctrl+Z**: displays help information about the related magic keys.
-
-- **Ctrl+T**: displays task information.
-
-- **Ctrl+P**: allows the system to proactively enter the panic state. After the panic-related information is printed, the system is suspended.
-
-- **Ctrl+E**: Checks the integrity of the memory pool. If an error is detected, the system displays an error message. If no error is detected, the system displays "system memcheck over, all passed!".
-
-
-> **NOTICE:**
->If magic key is enabled, when special characters need to be entered through the UART or USB-to-virtual serial port, avoid using characters the same as the magic keys. Otherwise, the magic key may be triggered by mistake, causing errors in the original design.
+ - **Ctrl+P**: allows the system to proactively enter the panic state. After the panic-related information is printed, the system is suspended.
+ - **Ctrl+E**: Checks the integrity of the memory pool. If an error is detected, the system displays an error message. If no error is detected, the system displays "system memcheck over, all passed!".
+
+ >  **NOTICE**
+ > If magic key is enabled, when special characters need to be entered through the UART or USB-to-virtual serial port, avoid using characters the same as the magic keys. Otherwise, the magic key may be triggered by mistake, causing errors in the original design.
diff --git a/en/device-dev/kernel/kernel-small-debug-shell-overview.md b/en/device-dev/kernel/kernel-small-debug-shell-overview.md
index 5ac89f7eb900197534dca3a3d73846a9bdde0b6f..7c1ce9d0e6e8d0caf21fc5bd38d7c4f976de65eb 100644
--- a/en/device-dev/kernel/kernel-small-debug-shell-overview.md
+++ b/en/device-dev/kernel/kernel-small-debug-shell-overview.md
@@ -1,35 +1,34 @@
-# Introduction to the Shell
+# Shell
The shell provided by the OpenHarmony kernel supports commonly used debugging commands. You can also add and customize commands to the shell of the OpenHarmony kernel to address your service needs. The common debugging commands include the following:
-- System commands: commands used to query information, such as system tasks, semaphores, system software timers, CPU usage, and interrupts.
-- File commands: commands used to manage files and directories, such as **ls** and **cd**.
+- System commands: commands used to query information, such as system tasks, semaphores, system software timers, CPU usage, and interrupts.
-- Network commands: commands used to query the IP addresses of other devices connected to the development board, querying the IP address of the local device, testing network connectivity, and setting the access point \(AP\) and station \(STA\) modes of the development board.
+- File commands: commands used to manage files and directories, such as **ls** and **cd**.
- For details about how to add a command, see [Shell Command Development Guidelines](kernel-small-debug-shell-guide.md) and [Shell Command Programming Example](kernel-small-debug-shell-build.md).
+- Network commands: commands used to query the IP addresses of other devices connected to the development board, querying the IP address of the local device, testing network connectivity, and setting the access point (AP) and station (STA) modes of the development board.
+ For details about the process of adding commands, see [Shell Command Development](../kernel/kernel-small-debug-shell-guide.md) and [Shell Command Programming Example](../kernel/kernel-small-debug-shell-build.md).
-## Important Notes
-Note the following when using the shell:
+ **Precautions**
-- You can use the **exec** command to run executable files.
-- The shell supports English input by default. To delete the Chinese characters entered in UTF-8 format, press the backspace key for three times.
+Note the following when using shell:
-- When entering shell commands, file names, and directory names, you can press **Tab** to enable automatic completion. If there are multiple completions, multiple items are printed based on the same characters they have. If more than 24 lines of completions are available, the system displays the message "Display all num possibilities?\(y/n\)", asking you to determine whether to print all items. You can enter **y** to print all items or enter **n** to exit the printing. If more than 24 lines are printed after your selection, the system displays "--More--". In this case, you can press **Enter** to continue the printing or press **q** \(or **Ctrl+c**\) to exit.
+- You can use the **exec** command to run executable files.
-- The shell working directory is separated from the system working directory. You can run commands such as **cd** and **pwd** on the shell to perform operations on the shell working directory, and run commands such as **chdir** and **getcwd** to perform operations on the system working directory. Pay special attention when an input parameter in a file system operation command is a relative path.
+- The shell supports English input by default. To delete the Chinese characters entered in UTF-8 format, press the backspace key for three times.
-- Before using network shell commands, you need to call the **tcpip\_init** function to initialize the network and set up the Telnet connection. By default, the kernel does not call **tcpip\_init**.
+- When entering shell commands, file names, and directory names, you can press **Tab** to enable automatic completion. If there are multiple completions, multiple items are printed based on the same characters they have. If more than 24 lines of completions are available, the system displays the message "Display all num possibilities?(y/n)", asking you to determine whether to print all items. You can enter **y** to print all items or enter **n** to exit the printing. If more than 24 lines are printed after your selection, the system displays "--More--". In this case, you can press **Enter** to continue the printing or press **q** (or **Ctrl+c**) to exit.
-- You are not advised to run shell commands to perform operations on device files in the **/dev** directory, which may cause unexpected results.
+- The shell working directory is separated from the system working directory. You can run commands such as **cd** and **pwd** on the shell to perform operations on the shell working directory, and run commands such as **chdir** and **getcwd** to perform operations on the system working directory. Pay special attention when an input parameter in a file system operation command is a relative path.
-- The shell functions do not comply with the POSIX standards and are used only for debugging.
-
- > **NOTICE**
- >The shell functions are used for debugging only and can be enabled only in the Debug version \(by enabling the **LOSCFG\_DEBUG\_VERSION** configuration item using **menuconfig**\).
+- Before using network shell commands, you need to call the **tcpip_init** function to initialize the network and set up the Telnet connection. By default, the kernel does not call **tcpip_init**.
+- You are not advised to run shell commands to perform operations on device files in the **/dev** directory, which may cause unexpected results.
+- The shell functions do not comply with the POSIX standards and are used only for debugging.
+ >  **NOTICE**
+ > The shell functions are used for debugging only and can be enabled only in the Debug version (by enabling **LOSCFG_DEBUG_VERSION** using **menuconfig**).
diff --git a/en/device-dev/kernel/kernel-small-debug-trace.md b/en/device-dev/kernel/kernel-small-debug-trace.md
index b808e35d2515e9ede4def18ec35fd7a06a638d59..df41fd67f3d7d2ddc196e1ea4ddc3c10e701aa95 100644
--- a/en/device-dev/kernel/kernel-small-debug-trace.md
+++ b/en/device-dev/kernel/kernel-small-debug-trace.md
@@ -1,10 +1,12 @@
# Trace
-## Basic Concepts
+
+## Basic Concepts
Trace helps you learn about the kernel running process and the execution sequence of modules and tasks. With the information, you can better understand the code running process of the kernel and locate time sequence problems.
-## Working Principles
+
+## Working Principles
The kernel provides a hook framework to embed hooks in the main process of each module. In the initial startup phase of the kernel, the trace function is initialized and the trace handlers are registered with the hooks.
@@ -16,170 +18,117 @@ In offline mode, trace frames are stored in a circular buffer. If too many frame

-The online mode must be used with the integrated development environment \(IDE\). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner.
-
-## **Available APIs**
-
-### Kernel Mode
-
-The trace module of the OpenHarmony LiteOS-A kernel provides the following functions. For details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h) reference.
-
-**Table 1** Trace module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Starting and stopping trace
- |
-LOS_TraceStart
- |
-Starts trace.
- |
-
-LOS_TraceStop
- |
-Stops trace.
- |
-
-Managing trace records
- |
-LOS_TraceRecordDump
- |
-Exports data in the trace buffer.
- |
-
-LOS_TraceRecordGet
- |
-Obtains the start address of the trace buffer.
- |
-
-LOS_TraceReset
- |
-Clears events in the trace buffer.
- |
-
-Filtering trace records
- |
-LOS_TraceEventMaskSet
- |
-Sets the event mask to trace only events of the specified modules.
- |
-
-Masking events of specified interrupt IDs
- |
-LOS_TraceHwiFilterHookReg
- |
-Registers a hook to filter out events of specified interrupt IDs.
- |
-
-Performing function instrumentation
- |
-LOS_TRACE_EASY
- |
-Performs simple instrumentation.
- |
-
-LOS_TRACE
- |
-Performs standard instrumentation.
- |
-
-
-
-
-- You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
- - **LOS\_TRACE\_EASY\(TYPE, IDENTITY, params...\)** for simple instrumentation
- - You only need to insert this API into the source code.
- - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
- - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
- - **Params** specifies the event parameters. The value is of the **UIntPtr** type.
-
- Example:
-
- ```
- Perform simple instrumentation for reading and writing files fd1 and fd2.
- Set TYPE to 1 for read operations and 2 for write operations.
- Insert the following to the position where the fd1 file is read:
- LOS_TRACE_EASY(1, fd1, flag, size);
- Insert the following to the position where the fd2 file is read:
- LOS_TRACE_EASY(1, fd2, flag, size);
- Insert the following to the position where the fd1 file is written:
- LOS_TRACE_EASY(2, fd1, flag, size);
- Insert the following in the position where the fd2 file is written:
- LOS_TRACE_EASY(2, fd2, flag, size);
- ```
-
- - **LOS\_TRACE\(TYPE, IDENTITY, params...\)** for standard instrumentation.
- - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
- - **TYPE** specifies the event type. You can define the event type in **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**. For details about methods and rules for defining events, see other event types.
- - The **IDENTITY** and **Params** are the same as those of simple instrumentation.
-
- Example:
-
- ```
- 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK.
- Format: TRACE_#MOD#_FLAG (MOD indicates the module name)
- Example:
- TRACE_FS_FLAG = 0x4000
- 2. Define the event type in enum LOS_TRACE_TYPE.
- Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER
- Example:
- FS_READ = TRACE_FS_FLAG | 0; // Read files
- FS_WRITE = TRACE_FS_FLAG | 1; // Write files
- 3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format.
- #TYPE# is the #TYPE# defined in step 2.
- Example:
- #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size
- The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can modify the parameters as required.
- If no parameter is specified, events of this type are not traced.
- #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced.
- 4. Insert a code stub in a proper position.
- Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...))
- LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files
- The parameters following #TYPE# are the input parameter of the FS_READ_PARAMS function in step 3.
- ```
-
- > **NOTE:**
- >The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\\include\\los\_trace.h**.
-
-
-
-- For **LOS\_TraceEventMaskSet\(UINT32 mask\)**, only the most significant 28 bits \(corresponding to the enable bit of the module in **LOS\_TRACE\_MASK**\) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS\_TraceEventMaskSet\(0x202\)**, the effective mask is **0x200 \(TRACE\_QUE\_FLAG\)** and all events of the QUE module are collected. The recommended method is **LOS\_TraceEventMaskSet\(TRACE\_EVENT\_FLAG | TRACE\_MUX\_FLAG | TRACE\_SEM\_FLAG | TRACE\_QUE\_FLAG\);**.
-- To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE\_MAX\_FLAG**.
-- The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS\_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
-- The typical trace operation process includes **LOS\_TraceStart**, **LOS\_TraceStop**, and **LOS\_TraceRecordDump**.
-- You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
-
- The sample code is as follows:
-
- ```
- BOOL Example_HwiNumFilter(UINT32 hwiNum)
- {
- if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) {
- return TRUE;
- }
- return FALSE;
+The online mode must be used with the integrated development environment (IDE). Trace frames are sent to the IDE in real time. The IDE parses the records and displays them in a visualized manner.
+
+
+## Available APIs
+
+
+### Kernel Mode
+
+The trace module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_trace.h).
+
+ **Table 1** APIs of the trace module
+
+| Category| Description|
+| -------- | -------- |
+| Starting/Stopping trace| **LOS_TraceStart**: starts trace.
**LOS_TraceStop**: stops trace. |
+| Managing trace records| **LOS_TraceRecordDump**: dumps data from the trace buffer.
**LOS_TraceRecordGet**: obtains the start address of the trace buffer.
**LOS_TraceReset**: clears events in the trace buffer. |
+| Filtering trace records| **LOS_TraceEventMaskSet**: sets the event mask to trace only events of the specified modules.|
+| Masking events of specified interrupt IDs| **LOS_TraceHwiFilterHookReg**: registers a hook to filter out events of specified interrupt IDs.|
+| Performing function instrumentation| **LOS_TRACE_EASY**: performs simple instrumentation.
**LOS_TRACE**: performs standard instrumentation. |
+
+You can perform function instrumentation in the source code to trace specific events. The system provides the following APIs for instrumentation:
+
+- **LOS_TRACE_EASY(TYPE, IDENTITY, params...)** for simple instrumentation
+
+ - You only need to insert this API into the source code.
+ - **TYPE** specifies the event type. The value range is 0 to 0xF. The meaning of each value is user-defined.
+ - **IDENTITY** specifies the object of the event operation. The value is of the **UIntPtr** type.
+ - **Params** specifies the event parameters. The value is of the **UIntPtr** type.
+ Example:
+
+ ```
+ Perform simple instrumentation for reading and writing files fd1 and fd2.
+ Set TYPE to 1 for read operations and 2 for write operations.
+ Insert the following to the position where the fd1 file is read:
+ LOS_TRACE_EASY(1, fd1, flag, size);
+ Insert the following to the position where the fd2 file is read:
+ LOS_TRACE_EASY(1, fd2, flag, size);
+ Insert the following to the position where the fd1 file is written:
+ LOS_TRACE_EASY(2, fd1, flag, size);
+ Insert the following in the position where the fd2 file is written:
+ LOS_TRACE_EASY(2, fd2, flag, size);
+ ```
+- **LOS_TRACE(TYPE, IDENTITY, params...)** for standard instrumentation.
+ - Compared with simple instrumentation, standard instrumentation supports dynamic event filtering and parameter tailoring. However, you need to extend the functions based on rules.
+ - **TYPE** specifies the event type. You can define the event type in **enum LOS_TRACE_TYPE** in the header file **los_trace.h**. For details about methods and rules for defining events, see other event types.
+ - The **IDENTITY** and **Params** are the same as those of simple instrumentation.
+ Example:
+
+ ```
+ 1. Set the event mask (module-level event type) in enum LOS_TRACE_MASK.
+ Format: TRACE_#MOD#_FLAG (MOD indicates the module name)
+ Example:
+ TRACE_FS_FLAG = 0x4000
+ 2. Define the event type in **enum LOS_TRACE_TYPE**.
+ Format: #TYPE# = TRACE_#MOD#_FLAG | NUMBER
+ Example:
+ FS_READ = TRACE_FS_FLAG | 0; // Read files.
+ FS_WRITE = TRACE_FS_FLAG | 1; // Write files.
+ 3. Set event parameters in the #TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ... format.
+ #TYPE# is the #TYPE# defined in step 2.
+ Example:
+ #define FS_READ_PARAMS(fp, fd, flag, size) fp, fd, flag, size
+ The parameters defined by the macro correspond to the event parameters recorded in the trace buffer. You can modify the parameters as required.
+ If no parameter is specified, events of this type are not traced.
+ #define FS_READ_PARAMS(fp, fd, flag, size) // File reading events are not traced.
+ 4. Insert a code stub in a proper position.
+ Format: LOS_TRACE(#TYPE#, #TYPE#_PARAMS(IDENTITY, parma1...))
+ LOS_TRACE(FS_READ, fp, fd, flag, size); // Code stub for reading files.
+ The parameters following #TYPE# are the input parameter of the **FS_READ_PARAMS** function in step 3.
+ ```
+
+ >  **NOTE**
+ > The trace event types and parameters can be modified as required. For details about the parameters, see **kernel\include\los_trace.h**.
+
+For **LOS_TraceEventMaskSet(UINT32 mask)**, only the most significant 28 bits (corresponding to the enable bit of the module in **LOS_TRACE_MASK**) of the mask take effect and are used only for module-based tracing. Currently, fine-grained event-based tracing is not supported. For example, in **LOS_TraceEventMaskSet(0x202)**, the effective mask is **0x200 (TRACE_QUE_FLAG)** and all events of the QUE module are collected. The recommended method is **LOS_TraceEventMaskSet(TRACE_EVENT_FLAG | TRACE_MUX_FLAG | TRACE_SEM_FLAG | TRACE_QUE_FLAG);**.
+
+To enable trace of only simple instrumentation events, set **Trace Mask** to **TRACE_MAX_FLAG**.
+
+The trace buffer has limited capacity. When the trace buffer is full, events will be overwritten. You can use **LOS_TraceRecordDump** to export data from the trace buffer and locate the latest records by **CurEvtIndex**.
+
+The typical trace operation process includes **LOS_TraceStart**, **LOS_TraceStop**, and **LOS_TraceRecordDump**.
+
+You can filter out interrupt events by interrupt ID to prevent other events from being overwritten due to frequent triggering of a specific interrupt in some scenarios. You can customize interrupt filtering rules.
+
+Example:
+
+```
+BOOL Example_HwiNumFilter(UINT32 hwiNum)
+{
+ if ((hwiNum == TIMER_INT) || (hwiNum == DMA_INT)) {
+ return TRUE;
}
- LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
- ```
+ return FALSE;
+}
+LOS_TraceHwiFilterHookReg(Example_HwiNumFilter);
+```
+
+The interrupt events with interrupt ID of **TIMER_INT** or **DMA_INT** are not traced.
+
+### User Mode
-The interrupt events with interrupt ID of **TIMER\_INT** or **DMA\_INT** are not traced.
+The trace character device is added in **/dev/trace**. You can use **read()**, **write()**, and **ioctl()** on the device node to read, write, and control trace in user mode.
-### User Mode
+- **read()**: reads the trace data in user mode.
-The trace character device is added in **/dev/trace**. You can use **read\(\)**, **write\(\)**, and **ioctl\(\)** on the device node to read, write, and control trace in user mode.
+- **write()**: writes an event in user mode.
-- **read\(\)**: reads the trace data in user mode.
-- **write\(\)**: writes an event in user mode.
-- **ioctl\(\)**: performs user-mode trace operations, including:
+- **ioctl()**: performs user-mode trace operations, including:
+
```
#define TRACE_IOC_MAGIC 'T'
#define TRACE_START _IO(TRACE_IOC_MAGIC, 1)
@@ -189,134 +138,77 @@ The trace character device is added in **/dev/trace**. You can use **read\(\)*
#define TRACE_SET_MASK _IO(TRACE_IOC_MAGIC, 5)
```
-The operations specified by the input parameter of **ioctl\(\)** correspond to **LOS\_TraceStart**, **LOS\_TraceStop**, **LOS\_TraceReset**, **LOS\_TraceRecordDump**, and **LOS\_TraceEventMaskSet**, respectively.
+The operations specified by the input parameter of **ioctl()** correspond to **LOS_TraceStart**, **LOS_TraceStop**, **LOS_TraceReset**, **LOS_TraceRecordDump**, and **LOS_TraceEventMaskSet**, respectively.
+
+For details, see [User-Mode Development Example](kernel-small-debug-trace.md#user-mode).
+
-For more details, see [User-mode Programming Example](https://gitee.com/openharmony/docs/blob/70744e1e0e34d66e11108a00c8db494eea49dd02/en/device-dev/kernel/kernel-small-debug-trace.md#section4.2.2).
+## Development Guidelines
-## Development Guidelines
-### Kernel-mode Development Process
+### Kernel-Mode Development Process
The typical trace process is as follows:
-1. Configure the macro related to the trace module.
-
- Configure the trace macro **LOSCFG\_KERNEL\_TRACE**, which is disabled by default. Run the **make update\_config** command in the **kernel/liteos\_a** directory, choose **Kernel** \> **Enable Hook Feature**, and set **Enable Trace Feature** to **YES**.
-
-
- Configuration
- |
- menuconfig Option
- |
- Description
- |
- Value
- |
-
-
- LOSCFG_KERNEL_TRACE
- |
- Enable Trace Feature
- |
- Specifies whether to enable the trace feature.
- |
- YES/NO
- |
-
- LOSCFG_RECORDER_MODE_OFFLINE
- |
- Trace work mode ->Offline mode
- |
- Specifies whether to enable the online trace mode.
- |
- YES/NO
- |
-
- LOSCFG_RECORDER_MODE_ONLINE
- |
- Trace work mode ->Online mode
- |
- Specifies whether to enable the offline trace mode.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_CLIENT_INTERACT
- |
- Enable Trace Client Visualization and Control
- |
- Specifies whether to enable interaction with Trace IDE (dev tools), including data visualization and process control.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_FRAME_CORE_MSG
- |
- Enable Record more extended content ->Record cpuid, hardware interrupt status, task lock status
- |
- Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_FRAME_EVENT_COUNT
- |
- Enable Record more extended content ->Record event count, which indicate the sequence of happend events
- |
- Specifies whether to enables recording of the event sequence number.
- |
- YES/NO
- |
-
- LOSCFG_TRACE_FRAME_MAX_PARAMS
- |
- Record max params
- |
- Specifies the maximum number of parameters for event recording.
- |
- INT
- |
-
- LOSCFG_TRACE_BUFFER_SIZE
- |
- Trace record buffer size
- |
- Specifies the trace buffer size.
- |
- INT
- |
-
-
-
-
-2. \(Optional\) Preset event parameters and stubs \(or use the default event parameter settings and event stubs\).
-3. \(Optional\) Call **LOS\_TraceStop** to stop trace and call **LOS\_TraceReset** to clear the trace buffer. \(Trace is started by default.\)
-4. \(Optional\) Call **LOS\_TraceEventMaskSet** to set the event mask for trace \(only the interrupts and task events are enabled by default\). For details about the event mask, see **LOS\_TRACE\_MASK** in **los\_trace.h**.
-5. Call **LOS\_TraceStart** at the start of the code where the event needs to be traced.
-6. Call **LOS\_TraceStop** at the end of the code where the event needs to be traced.
-7. Call **LOS\_TraceRecordDump** to output the data in the buffer. \(The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to Trace IDE.\)
-
-The methods in steps 3 to 7 are encapsulated with shell commands. After the shell is enabled, the corresponding commands can be executed. The mapping is as follows:
-
-- LOS\_TraceReset —— trace\_reset
-- LOS\_TraceEventMaskSet —— trace\_mask
-- LOS\_TraceStart —— trace\_start
-- LOS\_TraceStop —— trace\_stop
-- LOS\_TraceRecordDump —— trace\_dump
-
-## Kernel-mode Programming Example
+1. Configure the macro related to the trace module.
+
+ Configure the macro **LOSCFG_KERNEL_TRACE**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel** > **Enable Hook Feature**, and set **Enable Trace Feature** to **YES**.
+
+| Configuration Item | menuconfig Option| Description| Value|
+| -------- | -------- | -------- | -------- |
+| LOSCFG_KERNEL_TRACE | Enable Trace Feature | Specifies whether to enable the trace feature.| YES/NO |
+| LOSCFG_RECORDER_MODE_OFFLINE | Trace work mode ->Offline mode | Specifies whether to enable the online trace mode.| YES/NO |
+| LOSCFG_RECORDER_MODE_ONLINE | Trace work mode ->Online mode | Specifies whether to enable the offline trace mode.| YES/NO |
+| LOSCFG_TRACE_CLIENT_INTERACT | Enable Trace Client Visualization and Control | Enables interaction with Trace IDE (dev tools), including data visualization and process control.| YES/NO |
+| LOSCFG_TRACE_FRAME_CORE_MSG | Enable Record more extended content -
>Record cpuid, hardware interrupt
status, task lock status | Specifies whether to enable recording of the CPU ID, interruption state, and lock task state.| YES/NO |
+| LOSCFG_TRACE_FRAME_EVENT_COUNT | Enable Record more extended content
->Record event count,
which indicate the sequence of happend events | Specifies whether to enables recording of the event sequence number.| YES/NO |
+| LOSCFG_TRACE_FRAME_MAX_PARAMS | Record max params | Specifies the maximum number of parameters for event recording.| INT |
+| LOSCFG_TRACE_BUFFER_SIZE | Trace record buffer size | Specifies the trace buffer size.| INT |
+
+2. (Optional) Preset event parameters and stubs (or use the default event parameter settings and event stubs).
+
+3. (Optional) Call **LOS_TraceStop** to stop trace and call **LOS_TraceReset** to clear the trace buffer. (Trace is started by default.)
+
+4. (Optional) Call **LOS_TraceEventMaskSet** to set the event mask for trace (only the interrupts and task events are enabled by default). For details about the event mask, see **LOS_TRACE_MASK** in **los_trace.h**.
+
+5. Call **LOS_TraceStart** at the start of the code where the event needs to be traced.
+
+6. Call **LOS_TraceStop** at the end of the code where the event needs to be traced.
+
+7. Call **LOS_TraceRecordDump** to output the data in the buffer. (The input parameter of the function is of the Boolean type. The value **FALSE** means to output data in the specified format, and the value **TRUE** means to output data to Trace IDE.)
+
+The methods in steps 3 to 7 are encapsulated with shell commands. You can run these commands on shell. The mappings between the functions and commands are as follows:
+
+- LOS_TraceReset —— trace_reset
+
+- LOS_TraceEventMaskSet —— trace_mask
+
+- LOS_TraceStart —— trace_start
+
+- LOS_TraceStop —— trace_stop
+
+- LOS_TraceRecordDump —— trace_dump
+
+
+### Kernel-Mode Development Example
This example implements the following:
-1. Create a trace task.
-2. Set the event mask.
-3. Start trace.
-4. Stop trace.
-5. Output trace data in the specified format.
+1. Create a trace task.
+
+2. Set the event mask.
+
+3. Start trace.
+
+4. Stop trace.
+
+5. Output trace data in the specified format.
+
+
+### Kernel-Mode Sample Code
-## Kernel-mode Sample Code
+The sample code is as follows:
-The code is as follows:
```
#include "los_trace.h"
@@ -331,21 +223,21 @@ VOID Example_Trace(VOID)
dprintf("trace start error\n");
return;
}
- /* Trigger a task switching event.*/
+ /* Trigger a task switching event. */
LOS_TaskDelay(1);
LOS_TaskDelay(1);
LOS_TaskDelay(1);
- /* Stop trace.*/
+ /* Stop trace. */
LOS_TraceStop();
LOS_TraceRecordDump(FALSE);
}
UINT32 Example_Trace_test(VOID){
UINT32 ret;
TSK_INIT_PARAM_S traceTestTask;
- /* Create a trace task. */
+ /* Create a trace task. */
memset(&traceTestTask, 0, sizeof(TSK_INIT_PARAM_S));
traceTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)Example_Trace;
- traceTestTask.pcName = "TestTraceTsk"; /* Trace task name*/
+ traceTestTask.pcName = "TestTraceTsk"; /* Test task name. */
traceTestTask.uwStackSize = 0x800;
traceTestTask.usTaskPrio = 5;
traceTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
@@ -354,22 +246,24 @@ UINT32 Example_Trace_test(VOID){
dprintf("TraceTestTask create failed .\n");
return LOS_NOK;
}
- /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then restart trace. */
+ /* Trace is started by default. Therefore, you can stop trace, clear the buffer, and then start trace. */
LOS_TraceStop();
LOS_TraceReset();
- /* Enable trace of the Task module events. */
+ /* Enable trace of the Task module events. */
LOS_TraceEventMaskSet(TRACE_TASK_FLAG);
return LOS_OK;
}
LOS_MODULE_INIT(Example_Trace_test, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
-## Verification
+
+### Verification
The output is as follows:
+
```
-*******TraceInfo begin*******
+***TraceInfo begin***
clockFreq = 50000000
CurEvtIndex = 7
Index Time(cycles) EventType CurTask Identity params
@@ -381,36 +275,41 @@ Index Time(cycles) EventType CurTask Identity params
5 0x36eec810 0x45 0xc 0x1 0x9 0x8 0x1f
6 0x3706f804 0x45 0x1 0x0 0x1f 0x4 0x0
7 0x37070e59 0x45 0x0 0x1 0x0 0x8 0x1f
-*******TraceInfo end*******
+***TraceInfo end***
```
The output event information includes the occurrence time, event type, task in which the event occurs, object of the event operation, and other parameters of the event.
-- **EventType**: event type. For details, see **enum LOS\_TRACE\_TYPE** in the header file **los\_trace.h**.
-- **CurrentTask**: ID of the running task.
-- **Identity**: object of the event operation. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**.
-- **params**: event parameters. For details, see **\#TYPE\#\_PARAMS** in the header file **los\_trace.h**.
+- **EventType**: event type. For details, see **enum LOS_TRACE_TYPE** in the header file **los_trace.h**.
+
+- **CurrentTask**: ID of the running task.
+
+- **Identity**: object of the event operation. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
+
+- **params**: event parameters. For details, see **#TYPE#_PARAMS** in the header file **los_trace.h**.
The following uses output No. 0 as an example.
+
```
Index Time(cycles) EventType CurTask Identity params
0 0x366d5e88 0x45 0x1 0x0 0x1f 0x4
```
-- **Time \(cycles\)** can be converted into time \(in seconds\) by dividing the cycles by clockFreq.
-- **0x45** indicates the task switching event. **0x1** is the ID of the task in running.
-- For details about the meanings of **Identity** and **params**, see the **TASK\_SWITCH\_PARAMS** macro.
+- **Time (cycles)** can be converted into time (in seconds) by dividing the cycles by clockFreq.
+
+- **0x45** indicates the task switching event. **0x1** is the ID of the task in running.
+
+- For details about the meanings of **Identity** and **params**, see the **TASK_SWITCH_PARAMS** macro.
```
#define TASK_SWITCH_PARAMS(taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus) \
taskId, oldPriority, oldTaskStatus, newPriority, newTaskStatus
```
-Because of **\#TYPE\#\_PARAMS\(IDENTITY, parma1...\) IDENTITY, ...**, **Identity** is **taskId \(0x0\)** and the first parameter is **oldPriority \(0x1f\)**.
-
-> **NOTE:**
->The number of **param**s is specified by the **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** parameter. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG\_TRACE\_FRAME\_MAX\_PARAMS** based on service requirements.
+Because of **#TYPE#_PARAMS(IDENTITY, parma1...) IDENTITY, ...**, **Identity** is **taskId (0x0)** and the first parameter is **oldPriority (0x1f)**.
-Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**.
+>  **NOTE**
+> The number of parameters in **params** is specified by **LOSCFG_TRACE_FRAME_MAX_PARAMS**. The default value is **3**. Excess parameters are not recorded. You need to set **LOSCFG_TRACE_FRAME_MAX_PARAMS** based on service requirements.
+Task 0x1 is switched to Task 0x0. The priority of task 0x1 is **0x1f**, and the state is **0x4**. The priority of the task 0x0 is **0x0**.
diff --git a/en/device-dev/kernel/kernel-small-memory-lms.md b/en/device-dev/kernel/kernel-small-memory-lms.md
index 74595cb951918bad29df9240c52395866cc5e853..277cbea8a28268a9c4597be980a22bb69f8f85f8 100644
--- a/en/device-dev/kernel/kernel-small-memory-lms.md
+++ b/en/device-dev/kernel/kernel-small-memory-lms.md
@@ -1,186 +1,119 @@
# LMS
-## Basic Concepts
+## Basic Concepts
-Lite Memory Sanitizer \(LMS\) is a tool used to detect memory errors on a real-time basis. LMS can detect buffer overflow, Use-After-Free \(UAF\), and double free errors in real time, and notify the operating system immediately. Together with locating methods such as Backtrace, LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors.
+Lite Memory Sanitizer (LMS) is a tool used to detect memory errors on a real-time basis. LMS can detect buffer overflow, Use-After-Free (UAF), and double free errors in real time, and notify the operating system immediately. Together with locating methods such as Backtrace, LMS can locate the code line that causes the memory error. It greatly improves the efficiency of locating memory errors.
The LMS module of the OpenHarmony LiteOS-A kernel provides the following functions:
-- Supports check of multiple memory pools.
-- Checks the memory allocated by **LOS\_MemAlloc**, **LOS\_MemAllocAlign**, and **LOS\_MemRealloc**.
-- Checks the memory when bounds-checking functions are called \(enabled by default\).
-- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called.
-
-## Working Principles
-
-LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and **Freed**. The shadow memory is located in the tail of the memory pool.
-
-- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state.
-- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state.
-- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported.
-- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported.
-
-## Available APIs
-
-### Kernel Mode
-
-The LMS module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details about the APIs, see the [API](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_lms.h) reference.
-
-**Table 1** LMS module APIs
-
-
-Function
- |
-API
- |
-Description
- |
-
-
-Adding a memory pool to be checked
- |
-LOS_LmsCheckPoolAdd
- |
-Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, LOS_MemInit calls this API to add the initialized memory pool to the LMS check linked list by default.
- |
-
-Deleting a memory pool from the LMS check linked list
- |
-LOS_LmsCheckPoolDel
- |
-Cancels the validity check on the specified memory pool.
- |
-
-Protecting a specified memory chunk
- |
-LOS_LmsAddrProtect
- |
-Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.
- |
-
-Disabling protection of a specified memory chunk
- |
-LOS_LmsAddrDisableProtect
- |
-Unlocks a memory chunk to make it readable and writable.
- |
-
-
-
-
-### User Mode
+- Supports check of multiple memory pools.
+
+- Checks the memory allocated by **LOS_MemAlloc**, **LOS_MemAllocAlign**, and **LOS_MemRealloc**.
+
+- Checks the memory when bounds-checking functions are called (enabled by default).
+
+- Checks the memory when libc frequently accessed functions, including **memset**, **memcpy**, **memmove**, **strcat**, **strcpy**, **strncat** and **strncpy**, are called.
+
+
+## Working Principles
+
+LMS uses shadow memory mapping to mark the system memory state. There are three states: **Accessible**, **RedZone**, and **Freed**. The shadow memory is located in the tail of the memory pool.
+
+- After memory is allocated from the heap, the shadow memory in the data area is set to the **Accessible** state, and the shadow memory in the head node area is set to the **RedZone** state.
+
+- When memory is released from the heap, the shadow memory of the released memory is set to the **Freed** state.
+
+- During code compilation, a function is inserted before the read/write instructions in the code to check the address validity. The tool checks the state value of the shadow memory that accesses the memory. If the shadow memory is in the **RedZone** statue, an overflow error will be reported. If the shadow memory is in the **Freed** state, a UAF error will be reported.
+
+- When memory is released, the tool checks the state value of the shadow memory at the released address. If the shadow memory is in the **RedZone** state, a double free error will be reported.
+
+
+## Available APIs
+
+
+### Kernel Mode
+
+The LMS module of the OpenHarmony LiteOS-A kernel provides the following APIs. For more details, see [API reference](https://gitee.com/openharmony/kernel_liteos_a/blob/master/kernel/include/los_lms.h).
+
+ **Table 1** APIs of the LMS module
+
+| Category| API| Description|
+| -------- | -------- | -------- |
+| Adding a memory pool to be checked| LOS_LmsCheckPoolAdd | Adds the address range of a memory pool to the LMS check linked list. LMS performs a validity check when the accessed address is within the linked list. In addition, **LOS_MemInit** calls this API to add the initialized memory pool to the LMS check linked list by default.|
+| Deleting a memory pool from the LMS check linked list| LOS_LmsCheckPoolDel | Cancels the validity check on the specified memory pool.|
+| Protecting a specified memory chunk| LOS_LmsAddrProtect | Locks a memory chunk to prevent it from being read or written. Once the locked memory chunk is accessed, an error will be reported.|
+| Disabling protection of a specified memory chunk| LOS_LmsAddrDisableProtect | Unlocks a memory chunk to make it readable and writable.|
+
+
+### User Mode
The user mode provides only the LMS check library. It does not provide external APIs.
-## Development Guidelines
-### Kernel-mode Development Process
+## Development Guidelines
-The typical process for enabling LMS is as follows:
-1. Configure the macros related to the LMS module.
-
- Configure the LMS macro **LOSCFG\_KERNEL\_LMS**, which is disabled by default. Run the **make update\_config** command in the **kernel/liteos\_a** directory, choose **Kernel**, and select **Enable Lite Memory Sanitizer**.
-
-
- Macro
- |
- menuconfig Option
- |
- Description
- |
- Value
- |
-
-
- LOSCFG_KERNEL_LMS
- |
- Enable Lms Feature
- |
- Whether to enable LMS.
- |
- YES/NO
- |
-
- LOSCFG_LMS_MAX_RECORD_POOL_NUM
- |
- Lms check pool max num
- |
- Maximum number of memory pools that can be checked by LMS.
- |
- INT
- |
-
- LOSCFG_LMS_LOAD_CHECK
- |
- Enable lms read check
- |
- Whether to enable LMS read check.
- |
- YES/NO
- |
-
- LOSCFG_LMS_STORE_CHECK
- |
- Enable lms write check
- |
- Whether to enable LMS write check.
- |
- YES/NO
- |
-
- LOSCFG_LMS_CHECK_STRICT
- |
- Enable lms strict check, byte-by-byte
- |
- Whether to enable LMS byte-by-byte check.
- |
- YES/NO
- |
-
-
-
-
-2. Modify the compile script of the target module.
-
- Add "-fsanitize=kernel-address" to insert memory access checks, and add the **-O0** option to disable optimization performed by the compiler.
-
- The modifications vary depending on the compiler \(GCC or Clang\) used. The following is an example:
-
- ```
- if ("$ohos_build_compiler_specified" == "gcc") {
- cflags_c = [
- "-O0",
- "-fsanitize=kernel-address",
- ]
- } else {
- cflags_c = [
- "-O0",
- "-fsanitize=kernel-address",
- "-mllvm",
- "-asan-instrumentation-with-call-threshold=0",
- "-mllvm",
- "-asan-stack=0",
- "-mllvm",
- "-asan-globals=0",
- ]
- }
- ```
+### Kernel-Mode Development Process
-3. Recompile the code and check the serial port output. The memory problem detected will be displayed.
+The typical process for enabling LMS is as follows:
-## Kernel-mode Development Example
+1. Configure the macros related to the LMS module.
+
+ Configure the LMS macro **LOSCFG_KERNEL_LMS**, which is disabled by default. Run the **make update_config** command in the **kernel/liteos_a** directory, choose **Kernel**, and select **Enable Lite Memory Sanitizer**.
+
+ | Macro| menuconfig Option| Description| Value:|
+ | -------- | -------- | -------- | -------- |
+ | LOSCFG_KERNEL_LMS | Enable Lms Feature | Whether to enable LMS.| YES/NO |
+ | LOSCFG_LMS_MAX_RECORD_POOL_NUM | Lms check pool max num | Maximum number of memory pools that can be checked by LMS.| INT |
+ | LOSCFG_LMS_LOAD_CHECK | Enable lms read check | Whether to enable LMS read check.| YES/NO |
+ | LOSCFG_LMS_STORE_CHECK | Enable lms write check | Whether to enable LMS write check.| YES/NO |
+ | LOSCFG_LMS_CHECK_STRICT | Enable lms strict check, byte-by-byte | Whether to enable LMS byte-by-byte check.| YES/NO |
+
+
+2. Modify the build script of the target module.
+
+ Add **-fsanitize=kernel-address** to insert memory access checks, and add the **-O0** option to disable optimization performed by the compiler.
+
+ The modifications vary depending on the compiler (GCC or Clang) used. The following is an example:
+
+ ```
+ if ("$ohos_build_compiler_specified" == "gcc") {
+ cflags_c = [
+ "-O0",
+ "-fsanitize=kernel-address",
+ ]
+ } else {
+ cflags_c = [
+ "-O0",
+ "-fsanitize=kernel-address",
+ "-mllvm",
+ "-asan-instrumentation-with-call-threshold=0",
+ "-mllvm",
+ "-asan-stack=0",
+ "-mllvm",
+ "-asan-globals=0",
+ ]
+ }
+ ```
+
+3. Recompile the code and check the serial port output. The memory problem detected will be displayed.
+
+
+#### Kernel-Mode Development Example
This example implements the following:
-1. Create a task for LMS.
-2. Construct a buffer overflow error and a UAF error.
-3. Add "-fsanitize=kernel-address", execute the compilation, and check the output.
+1. Create a task for LMS.
-## Kernel-mode Sample Code
+2. Construct a buffer overflow error and a UAF error.
-The code is as follows:
+3. Add "-fsanitize=kernel-address", execute the compilation, and check the output.
+
+
+#### Kernel-Mode Sample Code
+
+ The sample code is as follows:
```
#define PAGE_SIZE (0x1000U)
@@ -221,10 +154,10 @@ VOID LmsTestCaseTask(VOID)
UINT32 Example_Lms_test(VOID){
UINT32 ret;
TSK_INIT_PARAM_S lmsTestTask;
- /* Create a task for LMS. */
+ /* Create a task for LMS. */
memset(&lmsTestTask, 0, sizeof(TSK_INIT_PARAM_S));
lmsTestTask.pfnTaskEntry = (TSK_ENTRY_FUNC)LmsTestCaseTask;
- lmsTestTask.pcName = "TestLmsTsk"; /* Task name. */
+ lmsTestTask.pcName = "TestLmsTsk"; /* Test task name. */
lmsTestTask.uwStackSize = 0x800;
lmsTestTask.usTaskPrio = 5;
lmsTestTask.uwResved = LOS_TASK_STATUS_DETACHED;
@@ -238,20 +171,21 @@ UINT32 Example_Lms_test(VOID){
LOS_MODULE_INIT(Example_Lms_test, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
-### Kernel-mode Verification
-The output is as follows:
+#### Kernel-Mode Verification
+
+ The output is as follows:
```
######LmsTestOsmallocOverflow start ######
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected Start *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected Start *
[ERR][KProcess:LmsTestCaseTask]Heap buffer overflow error detected
[ERR][KProcess:LmsTestCaseTask]Illegal READ address at: [0x4157a3c8]
[ERR][KProcess:LmsTestCaseTask]Shadow memory address: [0x4157be3c : 4] Shadow memory value: [2]
OsBackTrace fp = 0x402c0f88
runTask->taskName = LmsTestCaseTask
runTask->taskID = 2
-*******backtrace begin*******
+***backtrace begin***
traceback fp fixed, trace using fp = 0x402c0fd0
traceback 0 -- lr = 0x400655a4 fp = 0x402c0ff8
traceback 1 -- lr = 0x40065754 fp = 0x402c1010
@@ -269,18 +203,18 @@ traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca
[0x4157a3e0]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 0]: 3 3
[0x4157a3e8]: 00 00 00 00 00 00 00 00 | [0x4157be3e | 4]: 3 3
[0x4157a3f0]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 0]: 3 3
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected End *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected End *
str[20]=0xffffffba
######LmsTestOsmallocOverflow stop ######
###### LmsTestUseAfterFree start ######
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected Start *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected Start *
[ERR][KProcess:LmsTestCaseTask]Use after free error detected
[ERR][KProcess:LmsTestCaseTask]Illegal READ address at: [0x4157a3d4]
[ERR][KProcess:LmsTestCaseTask]Shadow memory address: [0x4157be3d : 2] Shadow memory value: [3]
OsBackTrace fp = 0x402c0f90
runTask->taskName = LmsTestCaseTask
runTask->taskID = 2
-*******backtrace begin*******
+***backtrace begin***
traceback fp fixed, trace using fp = 0x402c0fd8
traceback 0 -- lr = 0x40065680 fp = 0x402c0ff8
traceback 1 -- lr = 0x40065758 fp = 0x402c1010
@@ -298,35 +232,36 @@ traceback 3 -- lr = 0x40004e14 fp = 0xcacacaca
[0x4157a3e8]: ba dc cd ab c8 a3 57 41 | [0x4157be3e | 4]: 2 2
[0x4157a3f0]: 0c 1a 00 00 00 00 00 00 | [0x4157be3f | 0]: 2 3
[0x4157a3f8]: 00 00 00 00 00 00 00 00 | [0x4157be3f | 4]: 3 3
-[ERR][KProcess:LmsTestCaseTask]***** Kernel Address Sanitizer Error Detected End *****
+[ERR][KProcess:LmsTestCaseTask]* Kernel Address Sanitizer Error Detected End *
str[ 0]=0x 0
######LmsTestUseAfterFree stop ######
```
The key output information is as follows:
-- Error type:
- - Heap buffer overflow
- - UAF
+- Error type:
+ - Heap buffer overflow
+ - UAF
+
+- Incorrect operations:
+ - Illegal read
+ - Illegal write
+ - Illegal double free
-- Incorrect operations:
- - Illegal read
- - Illegal write
- - Illegal double free
+- Context:
+ - Task information (**taskName** and **taskId**)
+ - Backtrace
-- Context:
- - Task information \(**taskName** and **taskId**\)
- - Backtrace
+- Memory information of the error addresses:
+ - Memory value and the value of the corresponding shadow memory
+ - Memory address: memory value|[shadow memory address|shadow memory byte offset]: shadow memory value
+ - Shadow memory value. **0** (Accessible), **3** (Freed), **2** (RedZone), and **1** (filled value)
-- Memory information of the error addresses:
- - Memory value and the value of the corresponding shadow memory
- - Memory address: memory value|\[shadow memory address|shadow memory byte offset\]: shadow memory value
- - Shadow memory value. **0** \(Accessible\), **3** \(Freed\), **2** \(RedZone\), and **1** \(filled value\)
+### User-Mode Development Process
-### User-mode Development Process
+Add the following to the build script of the app to be checked. For details about the complete code, see **/kernel/liteos_a/apps/lms/BUILD.gn**.
-Add the following to the build script of the app to be checked. For details about the complete code, see **/kernel/liteos\_a/apps/lms/BUILD.gn**.
```
if ("$ohos_build_compiler_specified" == "gcc") {
@@ -369,16 +304,19 @@ if ("$ohos_build_compiler_specified" == "gcc") {
deps = [ "//kernel/liteos_a/kernel/extended/lms/usr:usrlmslib" ]
```
-### User-mode Development Example
+
+#### User-Mode Development Example
This example implements the following:
-1. Construct a buffer overflow error and a UAF error.
-2. Modify the build script and perform the build again.
+1. Construct a buffer overflow error and a UAF error.
+
+2. Modify the build script and perform the build again.
+
-### User-Mode Sample Code
+#### User-Mode Sample Code
-The code is as follows:
+ The code is as follows:
```
static void BufWriteTest(void *buf, int start, int end)
@@ -421,16 +359,17 @@ int main(int argc, char * const * argv)
}
```
-### User-mode Verification
-The output is as follows:
+#### User-Mode Verification
+
+ The output is as follows:
```
-***** Lite Memory Sanitizer Error Detected *****
+* Lite Memory Sanitizer Error Detected *
Heap buffer overflow error detected!
Illegal READ address at: [0x1f8b3edf]
Shadow memory address: [0x3d34d3ed : 6] Shadow memory value: [2]
-Accessable heap addr 0
+Accessible heap addr 0
Heap red zone 2
Heap freed buffer 3
Dump info around address [0x1f8b3edf]:
@@ -443,7 +382,7 @@ Dump info around address [0x1f8b3edf]:
[0x1f8b3ee8]: 09 00 00 00 00 00 00 00 | [0x3d34d3ee | 4]: 0 0
[0x1f8b3ef0]: 00 00 00 00 08 03 09 00 | [0x3d34d3ef | 0]: 2 2
[0x1f8b3ef8]: 00 00 00 00 00 00 00 00 | [0x3d34d3ef | 4]: 2 2
-***** Lite Memory Sanitizer Error Detected End *****
+* Lite Memory Sanitizer Error Detected End *
Backtrace() returned 5 addresses
#01: [0x4d6c] -> ./sample_usr_lms
#02: <(null)+0x2004074>[0x4074] -> ./sample_usr_lms
@@ -451,11 +390,11 @@ Backtrace() returned 5 addresses
#04: [0x363c] -> ./sample_usr_lms
#05: <(null)+0x1f856f30>[0x56f30] -> /lib/libc.so
-------- LMS_malloc_test End --------
-***** Lite Memory Sanitizer Error Detected *****
+* Lite Memory Sanitizer Error Detected *
Use after free error detected!
Illegal Double free address at: [0x1f8b3ee0]
Shadow memory address: [0x3d34d3ee : 0] Shadow memory value: [3]
-Accessable heap addr 0
+Accessible heap addr 0
Heap red zone 2
Heap freed buffer 3
Dump info around address [0x1f8b3ee0]:
@@ -468,7 +407,7 @@ Dump info around address [0x1f8b3ee0]:
[0x1f8b3ef0]: 20 40 8b 1f 20 20 8b 1f | [0x3d34d3ef | 0]: 3 3
[0x1f8b3ef8]: 00 00 00 00 00 00 00 00 | [0x3d34d3ef | 4]: 3 3
[0x1f8b3f00]: 00 00 00 00 00 00 00 00 | [0x3d34d3f0 | 0]: 3 3
-***** Lite Memory Sanitizer Error Detected End *****
+* Lite Memory Sanitizer Error Detected End *
Backtrace() returned 5 addresses
#01: [0x4d6c] -> ./sample_usr_lms
#02: [0x5548] -> ./sample_usr_lms
@@ -479,4 +418,3 @@ Backtrace() returned 5 addresses
```
The Backtrace output contains the names of the files where the addresses are located. You can locate the code line corresponding to the address in the related file.
-
diff --git a/en/device-dev/kernel/kernel-small-start-kernel.md b/en/device-dev/kernel/kernel-small-start-kernel.md
index c92af04ba02216c05708e280bd427b7b8cb128d8..01c4373ac8b51dc17a9ea91985c98688f4965311 100644
--- a/en/device-dev/kernel/kernel-small-start-kernel.md
+++ b/en/device-dev/kernel/kernel-small-start-kernel.md
@@ -1,99 +1,46 @@
# Startup in Kernel Mode
-## Kernel Startup Process
-
-The kernel startup process consists of the assembly startup and C language startup, as shown in the following figure. The assembly startup involves the following operations: initializing CPU settings, disabling dCache/iCache, enabling the FPU and NEON, setting the MMU to establish the virtual-physical address mapping, setting the system stack, clearing the BSS segment, and calling the main function of the C language. The C language startup involves the following operations: starting the OsMain function and starting scheduling. As shown in the following figure, the OsMain function is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. [Table 1](#table38544719428) describes each phase.
-
-**Figure 1** Kernel startup process
-
-
-**Table 1** Startup framework levels
-
-
-Level
- |
-Description
- |
-
-
-LOS_INIT_LEVEL_EARLIEST
- |
-Earliest initialization.
-The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.
-Example: trace module
- |
-
-LOS_INIT_LEVEL_ARCH_EARLY
- |
-Early initialization of the architecture.
-The initialization is architecture-dependent. Subsequent modules initialize the modules on which they depend. It is recommended that functions not required for startup be placed at LOS_INIT_LEVEL_ARCH.
- |
-
-LOS_INIT_LEVEL_PLATFORM_EARLY
- |
-Early initialization of the platform.
-The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend. It is recommended that functions required for startup be placed at LOS_INIT_LEVEL_PLATFORM.
- |
-
-LOS_INIT_LEVEL_KMOD_PREVM
- |
-Kernel module initialization before memory initialization.
-Initialize the modules that need to be enabled before memory initialization.
- |
-
-LOS_INIT_LEVEL_VM_COMPLETE
- |
-Initialization after the basic memory is ready.
-After memory initialization, initialize the modules that need to be enabled and do not depend on inter-process communication (IPC) and system processes.
-Example: shared memory function
- |
-
-LOS_INIT_LEVEL_ARCH
- |
-Late initialization of the architecture.
-The initialization is related to the architecture extension functions. Subsequent modules initialize the modules on which they depend.
- |
-
-LOS_INIT_LEVEL_PLATFORM
- |
-Late initialization of the platform.
-The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend.
-Example: initialization of the driver kernel abstraction layer (MMC and MTD)
- |
-
-LOS_INIT_LEVEL_KMOD_BASIC
- |
-Initialization of the kernel basic modules.
-Initialize the basic modules that can be detached from the kernel.
-Example: VFS initialization
- |
-
-LOS_INIT_LEVEL_KMOD_EXTENDED
- |
-Initialization of the kernel extended modules.
-Initialize the extended modules that can be detached from the kernel.
-Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC
- |
-
-LOS_INIT_LEVEL_KMOD_TASK
- |
-Kernel task creation
-Create kernel tasks (kernel tasks and software timer tasks).
-Example: creation of the resident resource reclaiming task, SystemInit task, and CPU usage statistics task.
- |
-
-
-
-
-## Programming Example
-
-### Example Description
+## Kernel Startup Process
+
+The kernel startup process consists of the assembly startup and C language startup, as shown in the following figure.
+
+The assembly startup involves the following operations: initializing CPU settings, disabling dCache/iCache, enabling the FPU and NEON, setting the MMU to establish the virtual-physical address mapping, setting the system stack, clearing the BSS segment, and calling the main function of the C language.
+
+The C language startup involves the following operations: starting the **OsMain** function and starting scheduling. As shown in the following figure, the **OsMain** function is used for basic kernel initialization and architecture- and board-level initialization. The kernel startup framework leads the initialization process. The right part of the figure shows the phase in which external modules can register with the kernel startup framework and starts. The table below describes each phase.
+
+
+ **Figure 1** Kernel startup process
+ 
+
+
+ **Table 1** Start framework
+
+| Level | Startup Description |
+| -------- | -------- |
+| LOS_INIT_LEVEL_EARLIEST | Earliest initialization.
The initialization is architecture-independent. The board and subsequent modules initialize the pure software modules on which they depend.
Example: trace module|
+| LOS_INIT_LEVEL_ARCH_EARLY | Early initialization of the architecture.
The initialization is architecture-dependent. Subsequent modules initialize the modules on which they depend. It is recommended that functions not required for startup be placed at **LOS_INIT_LEVEL_ARCH**.|
+| LOS_INIT_LEVEL_PLATFORM_EARLY | Early initialization of the platform.
The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend. It is recommended that functions required for startup be placed at **LOS_INIT_LEVEL_PLATFORM**.
Example: UART module|
+| LOS_INIT_LEVEL_KMOD_PREVM | Kernel module initialization before memory initialization.
Initialize the modules that need to be enabled before memory initialization.|
+| LOS_INIT_LEVEL_VM_COMPLETE | Initialization after the basic memory is ready.
After memory initialization, initialize the modules that need to be enabled and do not depend on inter-process communication (IPC) and system processes.
Example: shared memory function|
+| LOS_INIT_LEVEL_ARCH | Late initialization of the architecture.
The initialization is related to the architecture extension functions. Subsequent modules initialize the modules on which they depend.|
+| LOS_INIT_LEVEL_PLATFORM | Late initialization of the platform.
The initialization depends on the board platform and drivers. Subsequent modules initialize the modules on which they depend.
Example: initialization of the driver kernel abstraction layer (MMC and MTD)|
+| LOS_INIT_LEVEL_KMOD_BASIC | Initialization of the kernel basic modules.
Initialize the basic modules that can be detached from the kernel.
Example: VFS initialization|
+| LOS_INIT_LEVEL_KMOD_EXTENDED | Initialization of the kernel extended modules.
Initialize the extended modules that can be detached from the kernel.
Example: initialization of system call, ProcFS, Futex, HiLog, HiEvent, and LiteIPC|
+| LOS_INIT_LEVEL_KMOD_TASK | Kernel task creation.
Create kernel tasks (kernel tasks and software timer tasks).
Example: creation of the resident resource reclaiming task, SystemInit task, and CPU usage statistics task|
+
+
+## Programming Example
+
+**Example Description**
Add a kernel module and register the initialization function of the module to the kernel startup process through the kernel startup framework, so as to complete the module initialization during the kernel initialization process.
+
**Sample Code**
+
+
```
/* Header file of the kernel startup framework */
#include "los_init.h"
@@ -110,8 +57,11 @@ unsigned int OsSampleModInit(void)
LOS_MODULE_INIT(OsSampleModInit, LOS_INIT_LEVEL_KMOD_EXTENDED);
```
+
**Verification**
+
+
```
main core booting up...
OsSampleModInit SUCCESS!
@@ -120,9 +70,12 @@ cpu 1 entering scheduler
cpu 0 entering scheduler
```
+
According to the information displayed during the system startup, the kernel has called the initialization function of the registered module during the startup to initialize the module.
-> **NOTE:**
->Modules at the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required.
->You can view the symbol table in the **.rodata.init.kernel.\*** segment of the **OHOS\_Image.map** file generated after the build is complete, so as to learn about the initialization entry of each module that has been registered with the kernel startup framework and check whether the newly registered initialization entry has taken effect.
+>  **NOTE**
+>
+> Modules at the same level cannot depend on each other. It is recommended that a new module be split based on the preceding startup phase and be registered and started as required.
+>
+> You can view the symbol table in the **.rodata.init.kernel.*** segment of the **OHOS_Image.map** file generated after the build is complete, so as to learn about the initialization entry of each module that has been registered with the kernel startup framework and check whether the newly registered initialization entry has taken effect.
diff --git a/en/device-dev/kernel/kernel-standard-build.md b/en/device-dev/kernel/kernel-standard-build.md
index 747c9133458aec67156d3a1200d705b1a45df4a5..3c950570cf2ae2638fd00a68756c3cefaaf3ddce 100644
--- a/en/device-dev/kernel/kernel-standard-build.md
+++ b/en/device-dev/kernel/kernel-standard-build.md
@@ -1,14 +1,16 @@
# Compiling and Building the Linux Kernel
-## Example 1
+
+ **Example**
The following uses the Hi3516D V300 board and Ubuntu x86 server as an example.
-Perform a full build for the project to generate the **uImage** kernel image.
+
+Perform a full build for the project to generate the **uImage** kernel image.
+
```
-./build.sh --product-name hispark_taurus_standard # Build the hispark_taurus_standard image.
- --build-target build_kernel # Build the uImage kernel image of the hispark_taurus_standard.
- --gn-args linux_kernel_version=\"linux-5.10\" # Build the specified kernel version.
+./build.sh --product-name hispark_taurus_standard # Build the hispark_taurus_standard image.
+ --build-target build_kernel # Build the uImage kernel image of hispark_taurus_standard.
+ --gn-args linux_kernel_version=\"linux-5.10\" # Specify the kernel version.
```
-
diff --git a/en/device-dev/kernel/kernel-standard-sched-rtg.md b/en/device-dev/kernel/kernel-standard-sched-rtg.md
index 534cdcdab06c04c6f3abce5e29766411e4c819cc..61a36ab5bb7aad13789b0ce053e3dbcd73be6b25 100644
--- a/en/device-dev/kernel/kernel-standard-sched-rtg.md
+++ b/en/device-dev/kernel/kernel-standard-sched-rtg.md
@@ -51,11 +51,11 @@ STATE COMM PID PRIO CPU // Thread information, including th
## Available APIs
-The RTG provides the device node and ioctl APIs for querying and configuring group information. The device node is in `/dev/sched_rtg_ctrl`.
-
-| Device Node | request | Description |
-| ------------------- | ------------------- | ------------------- |
-| /dev/sched_rtg_ctrl | CMD_ID_SET_RTG | Creates an RTG, and adds, updates, or deletes threads in the group. |
-| | CMD_ID_SET_CONFIG | Configures global group attributes, for example, the maximum number of real-time RTGs.|
-| | CMD_ID_SET_RTG_ATTR | Configures specified group attributes, for example, the thread priority. |
-| | CMD_ID_SET_MIN_UTIL | Sets the minimum utilization of an RTG. |
+The RTG provides the device node and ioctl APIs for querying and configuring group information. The device node is in **/dev/sched_rtg_ctrl**.
+
+| Request | Description |
+| ------------------- | ------------------- |
+| CMD_ID_SET_RTG | Creates an RTG, and adds, updates, or deletes threads in the group. |
+| CMD_ID_SET_CONFIG | Sets global group attributes, for example, the maximum number of real-time RTGs. |
+| CMD_ID_SET_RTG_ATTR | Sets specified group attributes, for example, the thread priority. |
+| CMD_ID_SET_MIN_UTIL | Sets the minimum utilization of an RTG. |
diff --git a/en/device-dev/porting/porting-chip-prepare-knows.md b/en/device-dev/porting/porting-chip-prepare-knows.md
index 6422f0f6bddd007815c9122704f67713d5f78c7a..64a136cd4884c4d76a9ddf86c9160e410177cdc8 100644
--- a/en/device-dev/porting/porting-chip-prepare-knows.md
+++ b/en/device-dev/porting/porting-chip-prepare-knows.md
@@ -18,7 +18,7 @@ The implementation of the OpenHarmony project directories and functions relies o
| /build/lite | OpenHarmony basic compilation and building framework.|
| /kernel/liteos_m | Basic kernel. The implementation related to the chip architecture is in the **arch** directory.|
| /device | Board-level implementation, which complies with the OpenHarmony specifications. For details about the directory structure and porting process, see [Overview](../porting/porting-chip-board-overview.md).|
-| /vendor | Product-level implementation, which is contributed by Huawei or product vendors.|
+| /vendor | Product-level implementation, which is contributed by product vendors. |
The **device** directory is in the internal structure of **device/{Chip solution vendor}/{Development board}**. The following uses HiSilicon **hispark_taurus** as an example:
@@ -37,7 +37,7 @@ device
```
-The **vendor** directory is in the internal structure of **vendor/{Product solution vendor}/{Product name}**. The following uses the Huawei Wi-Fi IoT product as an example:
+The **vendor** directory is in the internal structure of **vendor/{Product solution vendor}/{Product name}**. The following uses the Wi-Fi IoT product as an example:
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001114129426.png b/en/device-dev/quick-start/figures/en-us_image_0000001114129426.png
index c5548cb227bd024b49aa3adba0a20869581448e8..8cff39968a2d34bdd93daa5de808a07558b56077 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001114129426.png and b/en/device-dev/quick-start/figures/en-us_image_0000001114129426.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001114129427.png b/en/device-dev/quick-start/figures/en-us_image_0000001114129427.png
new file mode 100644
index 0000000000000000000000000000000000000000..b4d11ba64f1f23a789167eabfc36f482fbc09697
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001114129427.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001160649343.png b/en/device-dev/quick-start/figures/en-us_image_0000001160649343.png
index 67d8044b72056d4ed6230ccc4ad99d5e954596b6..144950cb8cb1d260989d988242ca318ab584dfe6 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001160649343.png and b/en/device-dev/quick-start/figures/en-us_image_0000001160649343.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001160649344.png b/en/device-dev/quick-start/figures/en-us_image_0000001160649344.png
new file mode 100644
index 0000000000000000000000000000000000000000..82edf61fc871cc83e073036ee2593b89dea5e5cb
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001160649344.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001177478136.png b/en/device-dev/quick-start/figures/en-us_image_0000001177478136.png
index fcaf25e47e2e47ecad8aebe463aeccdf1d8bf85e..e83dad0b26392f009564d2e4014e374187ac1d7f 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001177478136.png and b/en/device-dev/quick-start/figures/en-us_image_0000001177478136.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001194504874.png b/en/device-dev/quick-start/figures/en-us_image_0000001194504874.png
index fdd12932d3777bd30a208e539a78ede6384cce19..0ba155fce3a06f53d085a1309cc00e9710e3c58d 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001194504874.png and b/en/device-dev/quick-start/figures/en-us_image_0000001194504874.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001194821710.png b/en/device-dev/quick-start/figures/en-us_image_0000001194821710.png
index 17d64a31a527a2b7453cc8490655609bd338ad7c..560240a18a081d50201d6185d25da46cc1c7a0eb 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001194821710.png and b/en/device-dev/quick-start/figures/en-us_image_0000001194821710.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001198566364.png b/en/device-dev/quick-start/figures/en-us_image_0000001198566364.png
index 1ba77b7feaca23043e71171824cdead7c4f8f108..1fef79a0d9ab7d7862be1e108ae947cec5eb16d2 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001198566364.png and b/en/device-dev/quick-start/figures/en-us_image_0000001198566364.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001198566365.png b/en/device-dev/quick-start/figures/en-us_image_0000001198566365.png
new file mode 100644
index 0000000000000000000000000000000000000000..5702f209752edc74d687e5e8ce7e210428f4551e
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001198566365.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001198722374.png b/en/device-dev/quick-start/figures/en-us_image_0000001198722374.png
index c6507f28b980b84c65102aa844e93f806cb490a9..6914f2d806dc8a2a8a26a8265f60832686dc2902 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001198722374.png and b/en/device-dev/quick-start/figures/en-us_image_0000001198722374.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001198943768.png b/en/device-dev/quick-start/figures/en-us_image_0000001198943768.png
index 5a709092da504fbb090ad8d44938e435712bc0eb..5702f209752edc74d687e5e8ce7e210428f4551e 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001198943768.png and b/en/device-dev/quick-start/figures/en-us_image_0000001198943768.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001220852753.png b/en/device-dev/quick-start/figures/en-us_image_0000001220852753.png
new file mode 100644
index 0000000000000000000000000000000000000000..58d4e1027aefb6650920d9d31fbb622bebc4f726
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001220852753.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001220852754.png b/en/device-dev/quick-start/figures/en-us_image_0000001220852754.png
index c3013a3f9bd3951e53e1f0848c12700024c5f5e8..a316d0a2c4117a16143c79426523dbc75c8dd1a8 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001220852754.png and b/en/device-dev/quick-start/figures/en-us_image_0000001220852754.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001220852755.png b/en/device-dev/quick-start/figures/en-us_image_0000001220852755.png
new file mode 100644
index 0000000000000000000000000000000000000000..884a8a0d8dfc1e14b3b2a256ede49bc88772c816
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001220852755.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001221012767.png b/en/device-dev/quick-start/figures/en-us_image_0000001221012767.png
new file mode 100644
index 0000000000000000000000000000000000000000..eead40cd3f889b23f73a6f02a9b7f44c822c2e37
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001221012767.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001221012768.png b/en/device-dev/quick-start/figures/en-us_image_0000001221012768.png
new file mode 100644
index 0000000000000000000000000000000000000000..d744afcd6c27ca674ae202bd4ca3511bb58bdbbc
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001221012768.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001221025048.png b/en/device-dev/quick-start/figures/en-us_image_0000001221025048.png
index f17d2dd5dbc86b98a659218ed4a5e3a69409ae54..f0d3cfc874effae73aad01dd26961ef4946c8f81 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001221025048.png and b/en/device-dev/quick-start/figures/en-us_image_0000001221025048.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001221172710.png b/en/device-dev/quick-start/figures/en-us_image_0000001221172710.png
index 29b22463c375704734e6925861551aa27ec7b295..cd6c3f1d8cea88d58a885446dad9cae3b74bce0b 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001221172710.png and b/en/device-dev/quick-start/figures/en-us_image_0000001221172710.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001221172711.png b/en/device-dev/quick-start/figures/en-us_image_0000001221172711.png
new file mode 100644
index 0000000000000000000000000000000000000000..d1992b49a9805cd0823c98c2d6f1500a10c5f249
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001221172711.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001221344980.png b/en/device-dev/quick-start/figures/en-us_image_0000001221344980.png
index 7bf0acc41746926462ab3c352f143f90f2e65358..86501f030f57eea30b724f8b7d32736a8ddc7f21 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001221344980.png and b/en/device-dev/quick-start/figures/en-us_image_0000001221344980.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001221356692.png b/en/device-dev/quick-start/figures/en-us_image_0000001221356692.png
index 8f5ee977c68bce18bed83887191ddf870df7d8e9..6d567bf69106c8bb266c7f7f445a317b5405c6a5 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001221356692.png and b/en/device-dev/quick-start/figures/en-us_image_0000001221356692.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001223190441.png b/en/device-dev/quick-start/figures/en-us_image_0000001223190441.png
index 63d053122f3c7beaa990f63431ccb16692562535..c3c0811c65d83f3a88f158f1c3336c1a950f4e69 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001223190441.png and b/en/device-dev/quick-start/figures/en-us_image_0000001223190441.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001225760456.png b/en/device-dev/quick-start/figures/en-us_image_0000001225760456.png
index 9e249959cad7e68b535f8732b44e20db9f6db2fc..61536a53597991971c997481624f1aedbc232c6d 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001225760456.png and b/en/device-dev/quick-start/figures/en-us_image_0000001225760456.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001227277128.png b/en/device-dev/quick-start/figures/en-us_image_0000001227277128.png
index fd2a5588e6576449bcb9ec1f92a12649dcd6c5d0..df66ac7a87d293ae8500eae978fbe5bcbc23e214 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001227277128.png and b/en/device-dev/quick-start/figures/en-us_image_0000001227277128.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001227757036.png b/en/device-dev/quick-start/figures/en-us_image_0000001227757036.png
index c354bdb69c0293fd19cb71905f828fca1fe7d09c..dea8677bfd7c9ba3f7b82f00c8422d695f85b86b 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001227757036.png and b/en/device-dev/quick-start/figures/en-us_image_0000001227757036.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001239661509.png b/en/device-dev/quick-start/figures/en-us_image_0000001239661509.png
index c3f10040538814eccbecf2ef37d472d59743e08f..541920af4791d36a3ad8eb3e8ccf154dc947944a 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001239661509.png and b/en/device-dev/quick-start/figures/en-us_image_0000001239661509.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001243704061.png b/en/device-dev/quick-start/figures/en-us_image_0000001243704061.png
index c93b7b610138e91c0b6b171cb515f540163e731b..f81b300b68edcc0400dcf72dfeb827fcf6ccaeea 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001243704061.png and b/en/device-dev/quick-start/figures/en-us_image_0000001243704061.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265492885.png b/en/device-dev/quick-start/figures/en-us_image_0000001265492885.png
index 7cc6ca102383151b5b67447332e73fc16c5ef85e..1fef79a0d9ab7d7862be1e108ae947cec5eb16d2 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265492885.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265492885.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265505181.png b/en/device-dev/quick-start/figures/en-us_image_0000001265505181.png
index eff6401bb39152c2d02b7f17e557b1cd5dbb0e87..da90fa7c0cd0da44ab6aff877eb8e11550dc7871 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265505181.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265505181.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265652869.png b/en/device-dev/quick-start/figures/en-us_image_0000001265652869.png
index 4c1ce174731a8e20b62d119cbe1728e9a8394176..fb6232380ebbc988a3b23dfec149daedd3f0c971 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265652869.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265652869.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265665157.png b/en/device-dev/quick-start/figures/en-us_image_0000001265665157.png
index 0a574b8ee51edd1f4049e5ca6821a9347a45c2de..56dabefba81dd9391d3bb5f52931bdbdc5753b22 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265665157.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265665157.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265676877.png b/en/device-dev/quick-start/figures/en-us_image_0000001265676877.png
index a87d8c651147e1b7cb1f3d60513a6b3139540399..f467c1b45f84730fd3fc45158004d9a03dec2551 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265676877.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265676877.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265772913.png b/en/device-dev/quick-start/figures/en-us_image_0000001265772913.png
index 659d732a4d044cfa4dacb84c5ec96bfc6b29707e..e5596ca2eac9b5d2cd1c96ffa50b1e390c68c904 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265772913.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265772913.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265785209.png b/en/device-dev/quick-start/figures/en-us_image_0000001265785209.png
index 0e5a65d7765d8bc936ca9a2d7db12f3adeffd831..1fef79a0d9ab7d7862be1e108ae947cec5eb16d2 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265785209.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265785209.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001265945173.png b/en/device-dev/quick-start/figures/en-us_image_0000001265945173.png
index f2447dd8f49268594e781e1c68751b209e01894c..d6dbd5d63c55c135dd8121d4ca1b4d11d5438897 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001265945173.png and b/en/device-dev/quick-start/figures/en-us_image_0000001265945173.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001266887264.png b/en/device-dev/quick-start/figures/en-us_image_0000001266887264.png
index f931e2cfba06791a3891248c5d8e6a9f0e86bf0e..e17047264d181b73e48e96a54c60517b57f42fb5 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001266887264.png and b/en/device-dev/quick-start/figures/en-us_image_0000001266887264.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001267532292.png b/en/device-dev/quick-start/figures/en-us_image_0000001267532292.png
index 8ed1535a6bc23dc5bd02fbd5a3f1392f46ad8d83..db92b0181a48b56990633058e3a4efce7ca5be82 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001267532292.png and b/en/device-dev/quick-start/figures/en-us_image_0000001267532292.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001271237241.png b/en/device-dev/quick-start/figures/en-us_image_0000001271237241.png
index caa9309b7f069597073ffa593a7fbc6820b4b2e9..0a150015345ea48708c486f21b76796f6e3ee36d 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001271237241.png and b/en/device-dev/quick-start/figures/en-us_image_0000001271237241.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001271237242.png b/en/device-dev/quick-start/figures/en-us_image_0000001271237242.png
new file mode 100644
index 0000000000000000000000000000000000000000..9a300afbcd842f7c61877123236675efc422f039
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001271237242.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001271442129.png b/en/device-dev/quick-start/figures/en-us_image_0000001271442129.png
new file mode 100644
index 0000000000000000000000000000000000000000..8587b80f4fc5cb91cd18462b47053451947d4833
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001271442129.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001271442261.png b/en/device-dev/quick-start/figures/en-us_image_0000001271442261.png
index 4e14740a2906da609abea693b77a2680fa7054a2..8587b80f4fc5cb91cd18462b47053451947d4833 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001271442261.png and b/en/device-dev/quick-start/figures/en-us_image_0000001271442261.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001271448821.png b/en/device-dev/quick-start/figures/en-us_image_0000001271448821.png
index 53cbcb8b0d0c30cb289b746d20b6c73927019d1a..0a150015345ea48708c486f21b76796f6e3ee36d 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001271448821.png and b/en/device-dev/quick-start/figures/en-us_image_0000001271448821.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001271477045.png b/en/device-dev/quick-start/figures/en-us_image_0000001271477045.png
index c55a6ddd1aa319adfa05987ff3f5c79231e7208d..8581b9663ab1f1597166d9e5b668c4d70c273e01 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001271477045.png and b/en/device-dev/quick-start/figures/en-us_image_0000001271477045.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001275592884.png b/en/device-dev/quick-start/figures/en-us_image_0000001275592884.png
new file mode 100644
index 0000000000000000000000000000000000000000..2186d2a5328684c1a479d4fca6b9fa74884c6a7b
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001275592884.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001276354454.png b/en/device-dev/quick-start/figures/en-us_image_0000001276354454.png
new file mode 100644
index 0000000000000000000000000000000000000000..2419d79327a7a13df83fe637916b9abeb180a2b0
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001276354454.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001278358765.png b/en/device-dev/quick-start/figures/en-us_image_0000001278358765.png
index 96b251c58071d4203ff51f28317f378d6ec71ebb..3bb58a00550fb0a0e195eb7f4cdb9e80be1ac6ab 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001278358765.png and b/en/device-dev/quick-start/figures/en-us_image_0000001278358765.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001279425450.png b/en/device-dev/quick-start/figures/en-us_image_0000001279425450.png
new file mode 100644
index 0000000000000000000000000000000000000000..fa3d1c40e18002a60a3c179b5e4e1396056a5b41
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001279425450.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001279426717.png b/en/device-dev/quick-start/figures/en-us_image_0000001279426717.png
index 53cbcb8b0d0c30cb289b746d20b6c73927019d1a..0a150015345ea48708c486f21b76796f6e3ee36d 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001279426717.png and b/en/device-dev/quick-start/figures/en-us_image_0000001279426717.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001279586409.png b/en/device-dev/quick-start/figures/en-us_image_0000001279586409.png
new file mode 100644
index 0000000000000000000000000000000000000000..e1cfe8323c13c750a03c4d5c86f2c383e554485d
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001279586409.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001279587085.png b/en/device-dev/quick-start/figures/en-us_image_0000001279587085.png
new file mode 100644
index 0000000000000000000000000000000000000000..084af8cfb40d4c59aa428890df7a1aee622a79d4
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001279587085.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001280938208.png b/en/device-dev/quick-start/figures/en-us_image_0000001280938208.png
new file mode 100644
index 0000000000000000000000000000000000000000..2e1c5ad3ffe3f4dcceeb78c33856c063aa506b43
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001280938208.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001312778829.png b/en/device-dev/quick-start/figures/en-us_image_0000001312778829.png
index 15791ccc963502062bd54537567db8876d9d7b63..eb1df60899dd8c41a61369410603d8f0adb77486 100644
Binary files a/en/device-dev/quick-start/figures/en-us_image_0000001312778829.png and b/en/device-dev/quick-start/figures/en-us_image_0000001312778829.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001322167645.png b/en/device-dev/quick-start/figures/en-us_image_0000001322167645.png
new file mode 100644
index 0000000000000000000000000000000000000000..b2d394f1debbbcf714a401630370639014d46160
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001322167645.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001326412233.png b/en/device-dev/quick-start/figures/en-us_image_0000001326412233.png
new file mode 100644
index 0000000000000000000000000000000000000000..e31eef74e95c2ecbb8e62d4ad897a2188e66d186
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001326412233.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001327429541.png b/en/device-dev/quick-start/figures/en-us_image_0000001327429541.png
new file mode 100644
index 0000000000000000000000000000000000000000..cc19b0a8e8f97ec07b29eab8b01f387c5c81903c
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001327429541.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001333642545.png b/en/device-dev/quick-start/figures/en-us_image_0000001333642545.png
new file mode 100644
index 0000000000000000000000000000000000000000..2186d2a5328684c1a479d4fca6b9fa74884c6a7b
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001333642545.png differ
diff --git a/en/device-dev/quick-start/figures/en-us_image_0000001333802045.png b/en/device-dev/quick-start/figures/en-us_image_0000001333802045.png
new file mode 100644
index 0000000000000000000000000000000000000000..1fef79a0d9ab7d7862be1e108ae947cec5eb16d2
Binary files /dev/null and b/en/device-dev/quick-start/figures/en-us_image_0000001333802045.png differ
diff --git a/en/device-dev/subsystems/subsys-aiframework-demo-plugin.md b/en/device-dev/subsystems/subsys-aiframework-demo-plugin.md
index fade965edad6eb099a69f7334608cc0954494a03..298489f6d6faf68f35c7e2b39616d0ae6c7e94b0 100644
--- a/en/device-dev/subsystems/subsys-aiframework-demo-plugin.md
+++ b/en/device-dev/subsystems/subsys-aiframework-demo-plugin.md
@@ -1,6 +1,6 @@
# KWS Plug-in
-1. Add the API of the KWS plug-in to the **//foundation/ai/engine/services/server/plugin** directory. This API is used to call AI capabilities. The following code snippet is an example API implementation of the KWS plug-in. The reference code is available at the **//foundation/ai/engine/services/server/plugin/asr/keyword\_spotting** directory.
+1. Add the API of the KWS plug-in to the **//foundation/ai/engine/services/server/plugin** directory. This API is used to call AI capabilities. The following code snippet is an example API implementation of the KWS plug-in. The reference code is available at the **//foundation/ai/engine/services/server/plugin/asr/keyword\_spotting** directory.
```
#include "plugin/i_plugin.h
@@ -20,72 +20,24 @@
};
```
- The preceding code implements the **IPlugin** API provided by the server. [Table 1](#table567211582104) shows the mapping between the client APIs and the plug-in APIs.
+ The preceding code implements the **IPlugin** API provided by the server. [Table 1](#table567211582104) shows the mapping between the client APIs and the plug-in APIs.
- **Table 1** Mapping between the client APIs and the plug-in APIs
+ **Table 1** Mapping between the client APIs and the plug-in APIs
-
- Client API
- |
- Plug-in API
- |
- Description
- |
-
-
- AieClientPrepare
- |
- Prepare
- |
- Initializes the inference algorithm plug-in. For KWS, this API loads the KWS model from the fixed location (/sdcard/wenwen_inst.wk) to the memory.
- |
-
- AieClientSyncProcess
- |
- SyncProcess
- |
- Executes the inference algorithm synchronously. For KWS, this API synchronously executes the audio inference algorithm to determine whether the specified wakeup keyword exists in the audio.
- |
-
- AieClientAsyncProcess
- |
- AsyncProcess
- |
- Executes the inference algorithm asynchronously. Currently, this API is not used in KWS. However, you can implement the API based on your use case.
- |
-
- AieClientSetOption
- |
- SetOption
- |
- Sets algorithm-related configuration items, such as the confidence threshold and delay. Currently, this API is not used in KWS. However, you can implement the API based on your use case.
- |
-
- AieClientGetOption
- |
- GetOption
- |
- Obtains algorithm-related configuration items. For KWS, this API can obtain the input and output scale of the KWS model. The input scale is the MFCC feature (fixed value: 4000) required by the KWS model, and the output scale is the confidence (fixed value: 2) of the result.
- |
-
- AieClientRelease
- |
- Release
- |
- Releases the algorithm model. For KWS, this API releases the specified algorithm model and clears the dynamic memory in the feature processor.
- |
-
-
-
-
- Note:
-
- 1. The **AieClientInit** and **AieClientDestroy** APIs are used to connect to and disconnect from the server, respectively. They are not called in the plug-in algorithm and therefore do not need to be defined in the plug-in.
-
- 2. The KWS plug-in needs to use the **PLUGIN\_INTERFACE\_IMPL** statement to expose the function pointer. Otherwise, the plug-in cannot be properly loaded.
+| Client API | Plug-in API | Description |
+| ---------- | ----------- | ----------- |
+| AieClientPrepare | Prepare | Initializes the inference algorithm plug-in. For KWS, this API loads the KWS model from the fixed location (/sdcard/wenwen_inst.wk) to the memory. |
+| AieClientSyncProcess | SyncProcess | Executes the inference algorithm synchronously. For KWS, this API synchronously executes the audio inference algorithm to determine whether the specified wakeup keyword exists in the audio. |
+| AieClientAsyncProcess | AsyncProcess | Executes the inference algorithm asynchronously. Currently, this API is not used in KWS. However, you can implement the API based on your use case. |
+| AieClientSetOption | SetOption | Sets algorithm-related configuration items, such as the confidence threshold and delay. Currently, this API is not used in KWS. However, you can implement the API based on your use case. |
+| AieClientGetOption | GetOption | Obtains algorithm-related configuration items. For KWS, this API can obtain the input and output scale of the KWS model. The input scale is the MFCC feature (fixed value: 4000) required by the KWS model, and the output scale is the confidence (fixed value: 2) of the result. |
+| AieClientRelease | Release | Releases the algorithm model. For KWS, this API releases the specified algorithm model and clears the dynamic memory in the feature processor. |
+>**NOTE**
+>- The **AieClientInit** and **AieClientDestroy** APIs are used to connect to and disconnect from the server, respectively. They are not called in the plug-in algorithm and therefore do not need to be defined in the plug-in.
+>- The KWS plug-in needs to use the **PLUGIN\_INTERFACE\_IMPL** statement to expose the function pointer. Otherwise, the plug-in cannot be properly loaded.
+
+
```
PLUGIN_INTERFACE_IMPL(KWSPlugin);
- ```
-
-
+ ```
\ No newline at end of file
diff --git a/en/device-dev/subsystems/subsys-aiframework-demo-sdk.md b/en/device-dev/subsystems/subsys-aiframework-demo-sdk.md
index 969d35269f74b0a7efe86fd387d4fe066409d2b2..c6e5dbe4195526413c7e86a6b48ecd956b3785e1 100644
--- a/en/device-dev/subsystems/subsys-aiframework-demo-sdk.md
+++ b/en/device-dev/subsystems/subsys-aiframework-demo-sdk.md
@@ -1,6 +1,6 @@
# KWS SDK
-1. Add the API of the KWS SDK to the **//foundation/ai/engine /interfaces/kits** directory. This API can be called by third-party applications. The following code snippet is an example API for the KWS SDK. The reference code is available at the **//foundation/ai/engine /interfaces/kits/asr/keyword\_spotting** directory.
+1. Add the API of the KWS SDK to the **//foundation/ai/engine /interfaces/kits** directory. This API can be called by third-party applications. The following code snippet is an example API for the KWS SDK. The reference code is available at the **//foundation/ai/engine /interfaces/kits/asr/keyword\_spotting** directory.
```
class KWSSdk {
@@ -22,7 +22,7 @@
};
```
-2. Add the API implementation of the SDK to the **//foundation/ai/engine/services/client/algorithm\_sdk** directory and call the APIs provided by the client to use the algorithm plug-in capabilities. The following code snippet is an example implementation of the **create** method in the API of the KWS SDK. For more details, see the reference code at **//foundation/ai/engine/services/client/algorithm\_sdk/asr/keyword\_spotting**.
+2. Add the API implementation of the SDK to the **//foundation/ai/engine/services/client/algorithm\_sdk** directory and call the APIs provided by the client to use the algorithm plug-in capabilities. The following code snippet is an example implementation of the **create** method in the API of the KWS SDK. For more details, see the reference code at **//foundation/ai/engine/services/client/algorithm\_sdk/asr/keyword\_spotting**.
```
int32_t KWSSdk::KWSSdkImpl::Create()
@@ -73,9 +73,8 @@
}
```
- The preceding code is the specific API implementation. The **create** function in the API of the KWS SDK calls the open **AieClientInit** and **AieClientPrepare** APIs provided by the client to connect to the server and load the algorithm model. For details, see the implementation of the **create** method in following sections.
-
- > **NOTE:**
- >The sequence for the SDK to call client APIs: **AieClientInit** -\> **AieClientPrepare** -\> **AieClientSyncProcess** or **AieClientAsyncProcess** -\> **AieClientRelease** -\> **AieClientDestroy**. An exception will be thrown if the call sequence is violated.
-
+ The preceding code is the specific API implementation. The **create** function in the API of the KWS SDK calls the open **AieClientInit** and **AieClientPrepare** APIs provided by the client to connect to the server and load the algorithm model. For details, see the implementation of the **create** method in following sections.
+ > **NOTE**
+ >
+ >The sequence for the SDK to call client APIs: **AieClientInit** -\> **AieClientPrepare** -\> **AieClientSyncProcess** or **AieClientAsyncProcess** -\> **AieClientRelease** -\> **AieClientDestroy**. An exception will be thrown if the call sequence is violated.
diff --git a/en/device-dev/subsystems/subsys-build-mini-lite.md b/en/device-dev/subsystems/subsys-build-mini-lite.md
index 5edca2ba8449a7001b207a3bc802bf9a29813471..fa47c3a94b36fdc69c207ae602c218574c9074c7 100644
--- a/en/device-dev/subsystems/subsys-build-mini-lite.md
+++ b/en/device-dev/subsystems/subsys-build-mini-lite.md
@@ -2,7 +2,7 @@
## Overview
- The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
+The Compilation and Building subsystem provides a build framework based on Generate Ninja (GN) and Ninja. This subsystem allows you to:
- Assemble components into a product and build the product.
@@ -75,7 +75,7 @@ You can build a component, a chipset solution, and a product solution. To ensure
### Component
- The component source code directory is named in the *{Domain}/{Subsystem}/{Component}* format. The component directory structure is as follows:
+The component source code directory is named in the *{Domain}/{Subsystem}/{Component}* format. The component directory structure is as follows:
>  **CAUTION**
> The .json file of the subsystem in the **build/lite/components** directory contains component attributes, including the name, source code directory, function description, mandatory or not, build targets, RAM, ROM, build outputs, adapted kernels, configurable features, and dependencies of the component. When adding a component, add the component information in the .json file of the corresponding subsystem. The component configured for a product must have been defined in a subsystem. Otherwise, the verification will fail.
@@ -94,42 +94,42 @@ component
```
{
- "name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the @Organization/Component name format.
- "description": "Sensor services", # 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", # Mode for publishing the HPM package. The default value is code-segment.
+ "name": "@ohos/sensor_lite", # OpenHarmony Package Manager (HPM) component name, in the "@Organization/Component name" format.
+ "description": "Sensor services", # 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", # Mode for publishing the HPM package. The default value is code-segment.
"segment": {
"destPath": ""
- }, # Code restoration path (source code path) set when "publishAs is code-segment.
- "dirs": {"base/sensors/sensor_lite"} # 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": {"base/sensors/sensor_lite"}, # 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": "sensor_lite", # Component name.
- "subsystem": "", # Subsystem to which the component belongs.
- "syscap": [], # System capabilities provided by the component for applications.
- "features": [], # List of the component's configurable features. Generally, this parameter corresponds to sub_component in build and can be configured.
- "adapted_system_type": [], # Adapted system types, which can be mini, small, and standard. Multiple values are allowed.
- "rom": "92KB", # Size of the component's ROM.
- "ram": "~200KB", # Size of the component's RAM.
+ "component": { # Component attributes.
+ "name": "sensor_lite", # Component name.
+ "subsystem": "", # Subsystem to which the component belongs.
+ "syscap": [], # System capabilities provided by the component for applications.
+ "features": [], # List of external configurable features of a component. Generally, this parameter corresponds to sub_component in build and can be configured by the product.
+ "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, and standard.
+ "rom": "92KB", # Component ROM size.
+ "ram": "~200KB",, # Component RAM size.
"deps": {
- "components": [ # Other components on which this component depends.
+ "components": [ # Other components on which this component depends.
"samgr_lite"
],
- "third_party": [ # Third-party open-source software on which this component depends.
+ "third_party": [ # Third-party open-source software on which this component depends.
"bounds_checking_function"
]
}
- "build": { # Build-related configurations.
+ "build": { # Build-related configuration.
"sub_component": [
""//base/sensors/sensor_lite/services:sensor_service"", # Component build entry
- ], # Component build entry. Configure the module here.
- "inner_kits": [], # APIs between components.
- "test": [] # Entry for building the component's test cases.
+ ], # Component build entry. Configure modules here.
+ "inner_kits": [], # APIs between components.
+ "test": [] # Entry for building the component's test cases.
}
}
}
@@ -195,28 +195,28 @@ component
### Chipset Solution
-The chipset solution is a special component. It is built based on a development board, including the drivers, device API adaptation, and SDK.
+- The chipset solution is a special component. It is built based on a development board, including the drivers, device API adaptation, and SDK.
-The source code path is named in the **device/{Development board}/{Chipset solution vendor}** format.
+- The source code path is named in the **device/{Development board}/{Chipset solution vendor}** format.
-The chipset solution component is built by default based on the development board selected.
-
-The chipset solution directory structure is as follows:
+- The chipset solution component is built by default based on the development board selected.
+
+- The chipset solution directory structure is as follows:
-```
-device
-└── board # Chipset solution vendor
- └── company # Development board name
- ├── BUILD.gn # Build script
- ├── hals # OS device API adaptation
- ├── linux # (Optional) Linux kernel version
- │ └── config.gni # Linux build configuration
- └── liteos_a # (Optional) LiteOS kernel version
- └── config.gni # LiteOS_A build configuration
-```
+ ```
+ device
+ └── board # Chipset solution vendor
+ └── company # Development board name
+ ├── BUILD.gn # Build script
+ ├── hals # OS device API adaptation
+ ├── linux # (Optional) Linux kernel version
+ │ └── config.gni # Linux build configuration
+ └── liteos_a # (Optional) LiteOS kernel version
+ └── config.gni # LiteOS_A build configuration
+ ```
->  **NOTE**
-> The **config.gni** file contains build-related configuration of the development board. The parameters in the file are used to build all OS components, and are globally visible to the system during the build process.
+ >  **NOTE**
+ > The **config.gni** file contains build-related configuration of the development board. The parameters in the file are used to build all OS components, and are globally visible to the system during the build process.
- The **config.gni** file contains the following key parameters:
@@ -267,18 +267,21 @@ The key directories and files are described as follows:
This file is the configuration file for the **init** process to start services. Currently, the following commands are supported:
- **start**: starts a service.
-- **mkdir**: creates a folder.
-
+
+ - **mkdir**: creates a folder.
+
- **chmod**: changes the permission on a specified directory or file.
-- **chown**: changes the owner group of a specified directory or file.
- - **mount**: mounts a device.
- The fields in the file are described as follows:
+ - **chown**: changes the owner group of a specified directory or file.
+
+ - **mount**: mounts a device.
+
+ The fields in the file are described as follows:
```
{
"jobs" : [{ # Job array. A job corresponds to a command set. Jobs are executed in the following sequence: pre-init > init > post-init.
- "name" : "pre-init",
+ "name" : "pre-init",
"cmds" : [
"mkdir /storage/data", # Create a directory.
"chmod 0755 /storage/data", #Modify the permissions. The format of the permission value is 0xxx, for example, 0755.
@@ -314,7 +317,7 @@ The key directories and files are described as follows:
]
}
```
-
+
3. **vendor/company/product/init_configs/hals**
This file contains the OS adaptation of the product. For details about APIs for implementing OS adaptation, see the readme file of each component.
@@ -361,9 +364,9 @@ The key directories and files are described as follows:
source_dir: (Optional) specifies target file directory in the out directory. If this field is not specified, an empty directory will be created in the file system based on target_dir.
target_dir: (Mandatory) specifies the file directory in the file system.
ignore_files: (Optional) declares ignored files during the copy operation.
- dir_mode: (Optional) specifies the file directory permissions. The default value is 755.
- file_mode: (Optional) specifies the permissions of all files in the directory. The default value is 555.
- fs_filemode: (Optional) specifies the files that require special permissions. Each file corresponds to a list.
+ dir_mode: (Optional) specifies the file directory permissions. The default value is 755.
+ file_mode: (Optional) specifies the permissions of all files in the directory. The default value is 555.
+ fs_filemode: (Optional) specifies the files that require special permissions. Each file corresponds to a list.
file_dir: (Mandatory) specifies the detailed file path in the file system.
file_mode: (Mandatory) declares file permissions.
fs_symlink: (Optional) specifies the soft link of the file system.
@@ -373,11 +376,12 @@ The key directories and files are described as follows:
The **fs_symlink** and **fs_make_cmd** fields support the following variables:
- - ${root_path}: code root directory, which corresponds to **${ohos_root_path}** of GN.
- - ${out_path}: **out** directory of the product, which corresponds to **${root_out_dir}** of GN.
- - ${fs_dir}: file system directory, which consists of variables ${root_path} and ${fs_dir_name}.
->  **NOTE**
-> **fs.yml** is optional and not required for devices without a file system.
+ - **${root_path}**: Code root directory, which corresponds to **${ohos_root_path}** of GN.
+ - **${out_path}**: The **out** directory of the product, which corresponds to **${root_out_dir}** of GN.
+ - **${fs_dir}**: File system directory, which consists of variables **${root_path}** and **${fs_dir_name}**.
+
+ >  **NOTE**
+ > **fs.yml** is optional and not required for devices without a file system.
6. **vendor/company/product/BUILD.gn**
@@ -405,7 +409,7 @@ The development environment has GN, Ninja, Python 3.9.2 or later, and hb availab
**hb** is an OpenHarmony command line tool for executing build commands. Common hb commands are described as follows:
- **hb set**
+**hb set**
```
hb set -h
@@ -438,7 +442,7 @@ hb env
[OHOS INFO] device path: xxx/device/hisilicon/hispark_taurus/sdk_linux_4.19
```
- **hb build**
+**hb build**
```
hb build -h
@@ -660,7 +664,6 @@ The following uses the RTL8720 development board provided by Realtek as an examp
```
4. Build the chipset solution.
-
Run the **hb build** command in the development board directory to start the build.
### Adding a Product Solution
@@ -668,7 +671,6 @@ The following uses the RTL8720 development board provided by Realtek as an examp
You can customize a product solution by flexibly assembling a chipset solution and components. The procedure is as follows:
1. Create a product directory based on the [configuration rules](#product-solution).
-
The following uses the Wi-Fi IoT module on the RTL8720 development board as an example. Run the following command in the root directory to create a product directory:
```
@@ -676,9 +678,8 @@ You can customize a product solution by flexibly assembling a chipset solution a
```
2. Assemble the product.
-
- Create a **config.json** file, for example for wifiiot, in the product directory. The **vendor/my_company/wifiiot/config.json** file is as follows:
-
+ Create a **config.json** file, for example for wifiiot, in the product directory. The **vendor/my_company/wifiiot/config.json** file is as follows:
+
```
{
"product_name": "wifiiot", # Product name
@@ -704,25 +705,22 @@ You can customize a product solution by flexibly assembling a chipset solution a
}
```
->  **CAUTION**
-> Before the build, the Compilation and Building subsystem checks the validity of fields in **config.json**. The **device_company**, **board**, **kernel_type**, and **kernel_version** fields must match the fields of the chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file.
+ >  **CAUTION**
+ > Before the build, the Compilation and Building subsystem checks the validity of fields in **config.json**. The **device_company**, **board**, **kernel_type**, and **kernel_version** fields must match the fields of the chipset solution, and **subsystem** and **component** must match the component description in the **build/lite/components** file.
3. Implement adaptation to OS APIs.
-
Create the **hals** directory in the product directory and save the source code as well as the build script for OS adaptation in this directory.
4. Configure system services.
-
Create the **init_configs** directory in the product directory and then the **init.cfg** file in the **init_configs** directory, and configure the system services to be started.
5. (Optional) Configure the init process for the Linux kernel.
-
Create the **etc** directory in the **init_configs** directory, and then the **init.d** folder and the **fstab** file in the **etc** directory. Then, create the **rcS** and **S***xxx* files in the **init.d** file and edit them based on product requirements.
6. (Optional) Configure the file system image for the development board that supports the file system.
-
+
Create a **fs.yml** file in the product directory and configure it as required. A typical **fs.yml** file is as follows:
-
+
```
-
fs_dir_name: rootfs # Image name
@@ -823,7 +821,7 @@ You can customize a product solution by flexibly assembling a chipset solution a
- ${root_path}/build/lite/make_rootfs/rootfsimg_linux.sh ${fs_dir} ext4
```
-
+
7. (Optional) Configure patches if the product and components need to be patched.
Create a **patch.yml** file in the product directory and configure it as required. A typical **patch.yml** file is as follows:
@@ -841,14 +839,14 @@ You can customize a product solution by flexibly assembling a chipset solution a
...
```
+
Add **--patch** when running the **hb build** command. Then, the patch files can be added to the specified directory before the build.
- ```
- hb build -f --patch
- ```
+ ```
+ hb build -f --patch
+ ```
8. Write the build script.
-
Create a **BUILD.gn** file in the product directory and write the script. The following **BUILD.gn** file uses the Wi-Fi IoT module in step 1 as an example:
```
@@ -864,9 +862,9 @@ You can customize a product solution by flexibly assembling a chipset solution a
```
9. Build the product.
-
Run the **hb set** command in the code root directory, select the new product as prompted, and run the **hb build** command.
+
## Troubleshooting
### "usr/sbin/ninja: invalid option -- w" Displayed During the Build Process
@@ -892,10 +890,10 @@ You can customize a product solution by flexibly assembling a chipset solution a
- **Possible Causes**
The ncurses library is not installed.
-
+
- **Solution**
- ```
+ ```
sudo apt-get install lib32ncurses5-dev
```
@@ -929,9 +927,9 @@ You can customize a product solution by flexibly assembling a chipset solution a
1. Run the following command to locate **gcc_riscv32**:
- ```
+ ```
which riscv32-unknown-elf-gcc
- ```
+ ```
2. Run the **chmod** command to change the directory permission to **755**.
diff --git a/en/device-dev/subsystems/subsys-xts-guide.md b/en/device-dev/subsystems/subsys-xts-guide.md
index d9ee3223e3aa282f5e7e847a07f7a20b00c628c5..90992e3e0449cd9a883ba5ddba171f5ae8fefb9d 100644
--- a/en/device-dev/subsystems/subsys-xts-guide.md
+++ b/en/device-dev/subsystems/subsys-xts-guide.md
@@ -2,7 +2,7 @@
## Introduction
-The X test suite \(XTS\) subsystem contains a set of OpenHarmony compatibility test suites, including the currently supported application compatibility test suite \(ACTS\) and the device compatibility test suite \(DCTS\) that will be supported in the future.
+The X test suite (XTS) subsystem contains a set of OpenHarmony compatibility test suites, including the currently supported application compatibility test suite (ACTS) and the device compatibility test suite (DCTS) that will be supported in the future.
This subsystem contains the ACTS and **tools** software package.
@@ -19,7 +19,7 @@ OpenHarmony supports the following systems:
- Small system
- A small system runs on a device that comes with memory greater than or equal to 1 MiB and application processors such as ARM Cortex-A. It provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders \(EDRs\) for smart travel.
+ A small system runs on a device that comes with memory greater than or equal to 1 MiB and application processors such as ARM Cortex-A. It provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders (EDRs) for smart travel.
- Standard system
@@ -34,7 +34,7 @@ OpenHarmony supports the following systems:
│ └── subsystem # Source code of subsystem test cases for the standard system
│ └── subsystem_lite # Source code of subsystems test cases for mini and small systems
│ └── BUILD.gn # Build configuration of test cases for the standard system
-│ └── build_lite
+│ └── build_lite # Build configuration of test cases for the mini and small systems.
│ └── BUILD.gn # Build configuration of test cases for mini and small systems
└── tools # Test tool code
```
@@ -72,9 +72,9 @@ Test cases for the mini system must be developed in C, and those for the small s
| Performance | Tests the processing capability of the tested object under specific preset conditions and load models. The processing capability is measured by the service volume that can be processed in a unit time, for example, call per second, frame per second, or event processing volume per second. |
| Power | Tests the power consumption of the tested object in a certain period of time under specific preset conditions and load models. |
| Reliability | Tests the service performance of the tested object under common and uncommon input conditions, or specified service volume pressure and long-term continuous running pressure. The test covers stability, pressure handling, fault injection, and Monkey test times. |
-| Security | - Tests the capability of defending against security threats, including but not limited to unauthorized access, use, disclosure, damage, modification, and destruction, to ensure information confidentiality, integrity, and availability.
- Tests the privacy protection capability to ensure that the collection, use, retention, disclosure, and disposal of users' private data comply with laws and regulations.
- Tests the compliance with various security specifications, such as security design, security requirements, and security certification of the Ministry of Industry and Information Technology (MIIT).
|
+| Security | Tests the capability of defending against security threats, including but not limited to unauthorized access, use, disclosure, damage, modification, and destruction, to ensure information confidentiality, integrity, and availability.
Tests the privacy protection capability to ensure that the collection, use, retention, disclosure, and disposal of users' private data comply with laws and regulations.
Tests the compliance with various security specifications, such as security design, security requirements, and security certification of the Ministry of Industry and Information Technology (MIIT). |
| Global | Tests the internationalized data and localization capabilities of the tested object, including multi-language display, various input/output habits, time formats, and regional features, such as currency, time, and culture taboos. |
-| Compatibility | - Tests backward compatibility of an application with its own data, the forward and backward compatibility with the system, and the compatibility with different user data, such as audio file content of the player and smart SMS messages.
- Tests system backward compatibility with its own data and the compatibility of common applications in the ecosystem.
- Tests software compatibility with related hardware.
|
+| Compatibility | Tests backward compatibility of an application with its own data, the forward and backward compatibility with the system, and the compatibility with different user data, such as audio file content of the player and smart SMS messages.
Tests system backward compatibility with its own data and the compatibility of common applications in the ecosystem.
Tests software compatibility with related hardware. |
| User | Tests user experience of the object in real user scenarios. All conclusions and comments should come from the users, which are all subjective evaluation in this case. |
| Standard | Tests the compliance with industry and company-specific standards, protocols, and specifications. The standards here do not include any security standards that should be classified into the security test. |
| Safety | Tests the safety property of the tested object to avoid possible hazards to personal safety, health, and the object itself. |
@@ -92,107 +92,109 @@ The test framework and programming language vary with the system type.
| Small | HCPPTest | C++ |
| Standard | HJSUnit and HCPPTest | JavaScript and C++ |
-### Developing Test Cases in C (for the Mini System\)
+### Developing Test Cases in C (for the Mini System)
**Developing Test Cases for the Mini System**
HCTest and the C language are used to develop test cases. HCTest is enhanced and adapted based on the open-source test framework Unity.
-1. Define the test case directory. The test cases are stored to **test/xts/acts**.
+1. Define the test case directory. The test cases are stored to **test/xts/acts**.
+
+ ```
+ ├── acts
+ │ └──subsystem_lite
+ │ │ └── module_hal
+ │ │ │ └── BUILD.gn
+ │ │ │ └── src
+ │ └──build_lite
+ │ │ └── BUILD.gn
+ ```
- ```
- ├── acts
- │ └──subsystem_lite
- │ │ └── module_hal
- │ │ │ └── BUILD.gn
- │ │ │ └── src
- │ └──build_lite
- │ │ └── BUILD.gn
- ```
2. Write the test case in the **src** directory.
- a) Include the test framework header file.
+ (1) Include the test framework header file.
- ```
- #include "hctest.h"
- ```
+ ```
+ #include "hctest.h"
+ ```
- b) Use the **LITE\_TEST\_SUIT** macro to define names of the subsystem, module, and test suite.
+ (2) Use the **LITE_TEST_SUIT** macro to define names of the subsystem, module, and test suite.
- ```
- /**
- * @brief Registers a test suite named IntTestSuite.
- * @param test Subsystem name
- * @param example Module name
- * @param IntTestSuite Test suite name
- */
- LITE_TEST_SUIT(test, example, IntTestSuite);
- ```
+ ```
+ /**
+ * @brief register a test suite named "IntTestSuite"
+ * @param test subsystem name
+ * @param example module name
+ * @param IntTestSuite test suite name
+ */
+ LITE_TEST_SUIT(test, example, IntTestSuite);
+ ```
- c) Define Setup and TearDown.
+ (3) Define Setup and TearDown.
- Format: Test suite name+Setup, Test suite name+TearDown.
+ Format: Test suite name+Setup, Test suite name+TearDown.
+ The Setup and TearDown functions must exist, but function bodies can be empty.
+
+ (4) Use the **LITE_TEST_CASE** macro to write the test case.
- The Setup and TearDown functions must exist, but function bodies can be empty.
+ Three parameters are involved: test suite name, test case name, and test case properties (including type, granularity, and level).
+
+ ```
+ LITE_TEST_CASE(IntTestSuite, TestCase001, Function | MediumTest | Level1)
+ {
+ // Do something.
+ };
+ ```
+
+ (5) Use the **RUN_TEST_SUITE** macro to register the test suite.
- d) Use the **LITE\_TEST\_CASE** macro to write the test case.
+ ```
+ RUN_TEST_SUITE(IntTestSuite);
+ ```
- Three parameters are involved: test suite name, test case name, and test case properties \(including type, granularity, and level\).
+3. Create the configuration file (**BUILD.gn**) of the test module.
- ```
- LITE_TEST_CASE(IntTestSuite, TestCase001, Function | MediumTest | Level1)
- {
- // Do something
- };
- ```
+ Create a **BUILD.gn** (example) file in each test module directory, and specify the name of the built static library and its dependent header files and libraries.
- e) Use the **RUN\_TEST\_SUITE** macro to register the test suite.
+ The format is as follows:
```
- RUN_TEST_SUITE(IntTestSuite);
+ import("//test/xts/tools/lite/build/suite_lite.gni")
+ hctest_suite("ActsDemoTest") {
+ suite_name = "acts"
+ sources = [
+ "src/test_demo.c",
+ ]
+ include_dirs = [ ]
+ cflags = [ "-Wno-error" ]
+ }
```
-3. Create the configuration file \(**BUILD.gn**\) of the test module.
-
- Create a **BUILD.gn** \(example\) file in each test module directory, and specify the name of the built static library and its dependent header files and libraries. The format is as follows:
-
- ```
- import("//test/xts/tools/lite/build/suite_lite.gni")
- hctest_suite("ActsDemoTest") {
- suite_name = "acts"
- sources = [
- "src/test_demo.c",
- ]
- include_dirs = [ ]
- cflags = [ "-Wno-error" ]
- }
- ```
+4. Add build options to the **BUILD.gn** file in the **acts** directory.
-4. Add build options to the **BUILD.gn** file in the **acts** directory.
+ You need to add the test module to the **test/xts/acts/build\_lite/BUILD.gn** script in the **acts** directory.
- You need to add the test module to the **test/xts/acts/build\_lite/BUILD.gn** script in the **acts** directory.
-
- ```
- lite_component("acts") {
- ...
- if(board_name == "liteos_m") {
- features += [
- ...
- "//xts/acts/subsystem_lite/module_hal:ActsDemoTest"
- ]
- }
- }
- ```
+ ```
+ lite_component("acts") {
+ ...
+ if(board_name == "liteos_m") {
+ features += [
+ ...
+ "//xts/acts/subsystem_lite/module_hal:ActsDemoTest"
+ ]
+ }
+ }
+ ```
-5. Run build commands.
+5. Run build commands.
- Test suites are built along with the OS version. The ACTS is built together with the debug version.
+ Test suites are built along with the OS version. The ACTS is built together with the debug version.
- > **NOTE**
The ACTS build middleware is a static library, which will be linked to the image.
+ > **NOTE**
The ACTS build middleware is a static library, which will be linked to the image.
-### Executing Test Cases in C (for the Mini System\)
+### Executing Test Cases in C (for the Mini System)
**Executing Test Cases for the Mini System**
@@ -211,120 +213,122 @@ The log for each test suite starts with "Start to run test suite:" and ends wit
### Developing Test Cases in C++ (for Standard and Small Systems)
-**Developing Test Cases for Small-System Devices** \(for the standard system, see the **global/i18n\_standard directory**.\)
+**Developing Test Cases for Small-System Devices** (for the standard system, see the **global/i18n_standard directory**.)
The HCPPTest framework, an enhanced version based on the open-source framework Googletest, is used.
-1. Define the test case directory. The test cases are stored to **test/xts/acts**.
-
- ```
- ├── acts
- │ └──subsystem_lite
- │ │ └── module_posix
- │ │ │ └── BUILD.gn
- │ │ │ └── src
- │ └──build_lite
- │ │ └── BUILD.gn
- ```
-
-2. Write the test case in the **src** directory.
-
- a) Include the test framework header file.
-
- The following statement includes **gtest.h**.
+1. Define the test case directory. The test cases are stored to **test/xts/acts**.
```
- #include "gtest/gtest.h"
+ ├── acts
+ │ └──subsystem_lite
+ │ │ └── module_posix
+ │ │ │ └── BUILD.gn
+ │ │ │ └── src
+ │ └──build_lite
+ │ │ └── BUILD.gn
```
- b) Define Setup and TearDown.
-
- ```
- using namespace std;
- using namespace testing::ext;
- class TestSuite: public testing::Test {
- protected:
- // Preset action of the test suite, which is executed before the first test case
- static void SetUpTestCase(void){
- }
- // Test suite cleanup action, which is executed after the last test case
- static void TearDownTestCase(void){
- }
- // Preset action of the test case
- virtual void SetUp()
- {
- }
- // Cleanup action of the test case
- virtual void TearDown()
- {
- }
- };
- ```
-
- c) Use the **HWTEST** or **HWTEST\_F** macro to write the test case.
-
- **HWTEST**: definition of common test cases, including the test suite name, test case name, and case annotation.
-
- **HWTEST\_F**: definition of SetUp and TearDown test cases, including the test suite name, test case name, and case annotation.
-
- Three parameters are involved: test suite name, test case name, and test case properties \(including type, granularity, and level\).
+2. Write the test case in the **src** directory.
- ```
- HWTEST_F(TestSuite, TestCase_0001, Function | MediumTest | Level1) {
- // Do something
- }
- ```
+ (1) Include the test framework.
+
+ Include **gtest.h**.
+ ```
+ #include "gtest/gtest.h"
+ ```
+
+
+ (2) Define Setup and TearDown.
+
+ ```
+ using namespace std;
+ using namespace testing::ext;
+ class TestSuite: public testing::Test {
+ protected:
+ // Preset action of the test suite, which is executed before the first test case
+ static void SetUpTestCase(void){
+ }
+ // Test suite cleanup action, which is executed after the last test case
+ static void TearDownTestCase(void){
+ }
+ // Preset action of the test case
+ virtual void SetUp()
+ {
+ }
+ // Cleanup action of the test case
+ virtual void TearDown()
+ {
+ }
+ };
+ ```
+
+
+ (3) Use the **HWTEST** or **HWTEST_F** macro to write the test case.
+
+ **HWTEST**: definition of common test cases, including the test suite name, test case name, and case annotation.
+
+ **HWTEST_F**: definition of SetUp and TearDown test cases, including the test suite name, test case name, and case annotation.
+
+ Three parameters are involved: test suite name, test case name, and test case properties (including type, granularity, and level).
+
+ ```
+ HWTEST_F(TestSuite, TestCase_0001, Function | MediumTest | Level1) {
+ // Do something
+ ```
-3. Create a configuration file \(**BUILD.gn**\) of the test module.
+3. Create a configuration file (**BUILD.gn**) of the test module.
Create a **BUILD.gn** file in each test module directory, and specify the name of the built static library and its dependent header files and libraries. Each test module is independently built into a **.bin** executable file, which can be directly pushed to the development board for testing.
Example:
-
- ```
- import("//test/xts/tools/lite/build/suite_lite.gni")
- hcpptest_suite("ActsDemoTest") {
- suite_name = "acts"
- sources = [
- "src/TestDemo.cpp"
- ]
-
- include_dirs = [
- "src",
- ...
- ]
- deps = [
- ...
- ]
- cflags = [ "-Wno-error" ]
- }
+
+ ```
+ import("//test/xts/tools/lite/build/suite_lite.gni")
+ hcpptest_suite("ActsDemoTest") {
+ suite_name = "acts"
+ sources = [
+ "src/TestDemo.cpp"
+ ]
+
+ include_dirs = [
+ "src",
+ ...
+ ]
+ deps = [
+ ...
+ ]
+ cflags = [ "-Wno-error" ]
+ }
+ ```
- ```
-
4. Add build options to the **BUILD.gn** file in the **acts** directory.
- Add the test module to the **test/xts/acts/build\_lite/BUILD.gn** script in the **acts** directory.
+ Add the test module to the **test/xts/acts/build_lite/BUILD.gn** script in the **acts** directory.
+
+ ```
+ lite_component("acts") {
+ ...
+ else if(board_name == "liteos_a") {
+ features += [
+ ...
+ "//xts/acts/subsystem_lite/module_posix:ActsDemoTest"
+ ]
+ }
+ }
+ ```
- ```
- lite_component("acts") {
- ...
- else if(board_name == "liteos_a") {
- features += [
- ...
- "//xts/acts/subsystem_lite/module_posix:ActsDemoTest"
- ]
- }
- }
- ```
5. Run build commands.
Test suites are built along with the OS version. The ACTS is built together with the debug version.
- > **NOTE**
The ACTS for the small system is independently built to an executable file \(.bin\) and archived in the **suites\\acts** directory of the build result.
+ > **NOTE**
+ >
+ >The ACTS for the small system is independently built to an executable file (.bin) and archived in the **suites\acts** directory of the build result.
-### Executing Test Cases in C++ (for Standard and Small Systems\)
+### Executing Test Cases in C++ (for Standard and Small Systems)
**Executing Test Cases for the Small System**
@@ -332,24 +336,29 @@ Currently, test cases are shared by the NFS and mounted to the development board
**Setting Up the Environment**
-1. Use a network cable or wireless network to connect the development board to your PC.
-2. Configure the IP address, subnet mask, and gateway for the development board. Ensure that the development board and the PC are in the same network segment.
-3. Install and register the NFS server on the PC and start the NFS service.
+1. Use a network cable or wireless network to connect the development board to your PC.
+
+2. Configure the IP address, subnet mask, and gateway for the development board. Ensure that the development board and the PC are in the same network segment.
+
+3. Install and register the NFS server on the PC and start the NFS service.
+
4. Run the **mount** command for the development board to ensure that the development board can access NFS shared files on the PC.
Format: **mount** _NFS server IP address_**:/**_NFS shared directory_ **/**_development board directory_ **nfs**
- Example:
+ Example:
```
mount 192.168.1.10:/nfs /nfs nfs
```
+
+
**Executing Test Cases**
Execute **ActsDemoTest.bin** to trigger test case execution, and analyze serial port logs generated after the execution is complete.
-### Developing Test Cases in JavaScript (for the Standard System\)
+### Developing Test Cases in JavaScript (for the Standard System)
The HJSUnit framework is used to support automated test of OpenHarmony apps that are developed using the JavaScript language based on the JS application framework.
@@ -366,73 +375,82 @@ The test cases are developed with the JavaScript language and must meet the prog
| beforeEach | Presets a test-case-level action executed before each test case is executed. The number of execution times is the same as the number of test cases defined by it. You can pass the action function as the only parameter. | No |
| afterEach | Presets a test-case-level clear action executed after each test case is executed. The number of execution times is the same as the number of test cases defined by it. You can pass the clear function as the only parameter. | No |
| describe | Defines a test suite. You can pass two parameters: test suite name and test suite function. The describe statement supports nesting. You can use beforeall, beforeEach, afterEach, and afterAll in each describe statement. | Yes |
-| it | Defines a test case. You can pass three parameters: test case name, filter parameter, and test case function.
**Usage of the filter parameter:**
The value of the filter parameter is a 32-bit integer. Setting different bits to 1 means different configurations:
- Bit 0: whether the filter parameter takes effect. 1 means that the test case is used for the function test and other settings of the parameter do not take effect.
- Bits 0-10: test case categories
- Bits 16-18: test case scales
- Bits 24-28: test levels
**Test case categories**: Bits 0-10 indicate FUNCTION (function test), PERFORMANCE (performance test), POWER (power consumption test), RELIABILITY (reliability test), SECURITY (security compliance test), GLOBAL (integrity test), COMPATIBILITY (compatibility test), USER (user test), STANDARD (standard test), SAFETY (security feature test), and RESILIENCE (resilience test), respectively.
**Test case scales**: Bits 16-18 indicate SMALL (small-scale test), MEDIUM (medium-scale test), and LARGE (large-scale test), respectively.
**Test levels**: Bits 24-28 indicate LEVEL0 (level-0 test), LEVEL1 (level-1 test), LEVEL2 (level-2 test), LEVEL3 (level-3 test), and LEVEL4 (level-4 test), respectively. | Yes |
+| it | Defines a test case. You can pass three parameters: test case name, filter parameter, and test case function.
**Filter parameter:**
The value is a 32-bit integer. Setting different bits to 1 means different configurations.
- Setting bit 0 to **1** means bypassing the filter.
- Setting bits 0-10 to **1** specifies the test case type, which can be FUNCTION (function test), PERFORMANCE (performance test), POWER (power consumption test), RELIABILITY (reliability test), SECURITY (security compliance test), GLOBAL (integrity test), COMPATIBILITY (compatibility test), USER (user test), STANDARD (standard test), SAFETY (security feature test), and RESILIENCE (resilience test), respectively.
- Setting bits 16-18 to **1** specifies the test case scale, which can be SMALL (small-scale test), MEDIUM (medium-scale test), and LARGE (large-scale test), respectively.
- Seting bits 24-28 to **1** specifies the test level, which can be LEVEL0 (level-0 test), LEVEL1 (level-1 test), LEVEL2 (level-2 test), LEVEL3 (level-3 test), and LEVEL4 (level-4 test), respectively.
| Yes |
Use the standard syntax of Jasmine to write test cases. The ES6 specification is supported.
1. Define the test case directory. The test cases are stored in the **entry/src/main/js/test** directory.
```
- ├── BUILD.gn
- │ └──entry
- │ │ └──src
- │ │ │ └──main
- │ │ │ │ └──js
- │ │ │ │ │ └──default
- │ │ │ │ │ │ └──pages
- │ │ │ │ │ │ │ └──index
- │ │ │ │ │ │ │ │ └──index.js # Entry file
- │ │ │ │ │ └──test # Test code
- │ │ │ └── resources # HAP resources
- │ │ │ └── config.json # HAP configuration file
- ```
+ ├── BUILD.gn
+ │ └──entry
+ │ │ └──src
+ │ │ │ └──main
+ │ │ │ │ └──js
+ │ │ │ │ │ └──default
+ │ │ │ │ │ │ └──pages
+ │ │ │ │ │ │ │ └──index
+ │ │ │ │ │ │ │ │ └──index.js # Entry file
+ │ │ │ │ │ └──test # Test code directory
+ │ │ │ └── resources # HAP resources
+ │ │ │ └── config.json # HAP configuration file
+ ```
-2. Start the JS test framework and load test cases. The following is an example for **index.js**.
- ```
- // Start the JS test framework and load test cases.
+2. Start the JS test framework and load test cases.
+
+ The following is an example for **index.js**.
+
+ ```
+ // Start the JS test framework and load test cases.
import {Core, ExpectExtend} from 'deccjsunit/index'
export default {
- data: {
- title: ""
- },
- onInit() {
- this.title = this.$t('strings.world');
- },
- onShow() {
- console.info('onShow finish')
- const core = Core.getInstance()
- const expectExtend = new ExpectExtend({
- 'id': 'extend'
- })
- core.addService('expect', expectExtend)
- core.init()
- const configService = core.getDefaultService('config')
- configService.setConfig(this)
- require('../../../test/List.test')
- core.execute()
- },
- onReady() {
- },
- }
- ```
+ data: {
+ title: ""
+ },
+ onInit() {
+ this.title = this.$t('strings.world');
+ },
+ onShow() {
+ console.info('onShow finish')
+ const core = Core.getInstance()
+ const expectExtend = new ExpectExtend({
+ 'id': 'extend'
+ })
+ core.addService('expect', expectExtend)
+ core.init()
+ const configService = core.getDefaultService('config')
+ configService.setConfig(this)
+ require('../../../test/List.test')
+ core.execute()
+ },
+ onReady() {
+ },
+ }
+ ```
-3. Write a unit test case by referring to the following example:
+
- ```
- // Use HJSUnit to perform the unit test.
- describe('appInfoTest', function () {
- it('app_info_test_001', 0, function () {
- var info = app.getInfo()
- expect(info.versionName).assertEqual('1.0')
- expect(info.versionCode).assertEqual('3')
- })
- })
- ```
+3. Write a unit test case.
+
+ The following is an example:
+
+ ```
+ // Example 1: Use HJSUnit to perform a unit test.
+ describe('appInfoTest', function () {
+ it('app_info_test_001', 0, function () {
+ var info = app.getInfo()
+ expect(info.versionName).assertEqual('1.0')
+ expect(info.versionCode).assertEqual('3')
+ })
+ })
+ ```
+
-### Packaging Test Cases in JavaScript (for the Standard System\)
+
+### Packaging Test Cases in JavaScript (for the Standard System)
For details about how to build a HAP, see the JS application development guide of the standard system [Building and Creating HAPs](https://developer.harmonyos.com/en/docs/documentation/doc-guides/build_overview-0000001055075201).
@@ -444,12 +462,15 @@ Run the following command:
./build.sh suite=acts system_size=standard
```
+
+
+
Test case directory: **out/release/suites/acts/testcases**
Test framework and test case directory: **out/release/suites/acts** \(the test suite execution framework is compiled during the build process)
-## Executing Test Cases in a Full Build (for Small and Standard Systems\)
+## Executing Test Cases in a Full Build (for Small and Standard Systems)
**Setting Up a Test Environment**
@@ -468,29 +489,30 @@ Install Python 3.7 or a later version on a Windows environment and ensure that t
**Executing Test Cases**
-1. On the Windows environment, locate the directory in which the test cases are stored \(**out/release/suites/acts**, copied from the Linux server\), go to the directory in the Windows command window, and run **acts\\run.bat**.
+1. On the Windows environment, locate the directory in which the test cases are stored \(**out/release/suites/acts**, copied from the Linux server), go to the directory in the Windows command window, and run **acts\\run.bat**.
-1. Enter the command for executing the test case.
+2. Enter the command for executing the test case.
- Execute all test cases.
- ```
- run acts
- ```
-
- 
-
- - Execute the test cases of a module \(view specific module information in **\\acts\\testcases\\**\).
-
- ```
- run –l ActsSamgrTest
- ```
-
- 
-
- Wait until the test cases are complete.
-
+ ```
+ run acts
+ ```
+
+ 
+
+ - Execute the test cases of a module \(view specific module information in **\acts\testcases\**).
+
+ ```
+ run –l ActsSamgrTest
+ ```
+
+ 
+
+ You can view specific module information in **\acts\testcases\**.
+
+ Wait until the test cases are complete.
3. View the test report.
- Go to **acts\\reports\\**, obtain the current execution record, and open **summary\_report.html** to view the test report.
+ Go to **acts\reports**, obtain the current execution record, and open **summary_report.html** to view the test report.
diff --git a/en/device-dev/website.md b/en/device-dev/website.md
index 5807147be58a44f7fe2e9da0ee47bd33e267f1ea..058c142b50164cd3f0e38649a61024b6e8eac8c8 100644
--- a/en/device-dev/website.md
+++ b/en/device-dev/website.md
@@ -24,6 +24,7 @@
- Appendix
- [Introduction to the Hi3861 Development Board](quick-start/quickstart-ide-lite-introduction-hi3861.md)
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-ide-lite-introduction-hi3516.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- Getting Started with Mini and Small Systems (Installation Package Mode)
- [Mini and Small System Overview](quick-start/quickstart-lite-overview.md)
- [Environment Preparation](quick-start/quickstart-lite-env-setup.md)
@@ -51,6 +52,7 @@
- [Introduction to the Hi3861 Development Board](quick-start/quickstart-lite-introduction-hi3861.md)
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-lite-introduction-hi3516.md)
- [Reference](quick-start/quickstart-lite-reference.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- Getting Started with Standard System (IDE Mode, Recommended)
- [Standard System Overview](quick-start/quickstart-ide-standard-overview.md)
- Environment Preparation
@@ -71,6 +73,7 @@
- Appendix
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-ide-standard-board-introduction-hi3516.md)
- [Introduction to the RK3568 Development Board](quick-start/quickstart-ide-standard-board-introduction-rk3568.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- Getting Started with Standard System (Installation Package Mode)
- [Standard System Overview](quick-start/quickstart-standard-overview.md)
- [Setting Up Environments for Standard System](quick-start/quickstart-standard-env-setup.md)
@@ -94,6 +97,7 @@
- [Introduction to the Hi3516 Development Board](quick-start/quickstart-standard-board-introduction-hi3516.md)
- [Introduction to the RK3568 Development Board](quick-start/quickstart-standard-board-introduction-rk3568.md)
- [Reference](quick-start/quickstart-standard-reference.md)
+ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md)
- [Obtaining Source Code](get-code/sourcecode-acquire.md)
- Compatibility and Security
@@ -379,6 +383,7 @@
- [Audio](driver/driver-peripherals-audio-des.md)
- [Camera](driver/driver-peripherals-camera-des.md)
- [Facial Authentication](driver/driver-peripherals-face_auth-des.md)
+ - [Fingerprint Authentication](driver/driver-peripherals-fingerprint_auth-des.md)
- [LCD](driver/driver-peripherals-lcd-des.md)
- [Light](driver/driver-peripherals-light-des.md)
- [PIN Authentication](driver/driver-peripherals-pinauth-des.md)
diff --git a/en/readme/DeviceProfile.md b/en/readme/DeviceProfile.md
index 0fe6134cbcb337c7e1dff1c111e98ab44e628f47..d1e4fdc0bfbc4ff5da9f219e52f2c60ac6dbd2d1 100644
--- a/en/readme/DeviceProfile.md
+++ b/en/readme/DeviceProfile.md
@@ -171,14 +171,13 @@ subscribeInfos.emplace_back(info2);
std::list failedEvents;
// Call SubscribeProfileEvents.
-DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents(subscribeInfos,
- callback, failedEvents);
+DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents(subscribeInfos, callback, failedEvents);
sleep(SUBSCRIBE_SLEEP_TIME);
std::list profileEvents;
profileEvents.emplace_back(ProfileEvent::EVENT_PROFILE_CHANGED);
failedEvents.clear();
// Cancel the subscription.
-DistributedDeviceProfileClient::GetInstance().UnsubscribeProfileEvents(profileEvents,
+DistributedDeviceProfileClient::GetInstance().UnsubscribeProfileEvents(profileEvents, callback, failedEvents);
callback, failedEvents);
```
diff --git a/en/release-notes/OpenHarmony-v3.1.1-release.md b/en/release-notes/OpenHarmony-v3.1.1-release.md
index 81a705cb5ab619bb9bf1163077f96bfa96b6bcd7..bcff1ffc13392f7b2e563b7e97e679a6e048bee7 100644
--- a/en/release-notes/OpenHarmony-v3.1.1-release.md
+++ b/en/release-notes/OpenHarmony-v3.1.1-release.md
@@ -21,7 +21,7 @@ Distributed data management is now compatible with the **\@system.storage** APIs
Bundle management supports application-specific installation status query. The common event and notification subsystem provides APIs for sending and canceling notifications.
-The Feature Ability (FA) model supports ability-level screen orientation query and setting, lock screen display, and screen-on during ability startup. DFX features, such as Application Not Response (ANR) and suspension detection for an application's main thread, are added. More basic capabilities are added for FA widgets.
+The Feature Ability (FA) model supports ability-level screen orientation query and setting, lock screen display, and screen-on during ability startup. DFX features, such as Application Not Response and suspension detection for an application's main thread, are added. More basic capabilities are added for FA widgets.
**Enhanced application capabilities for the standard system**
@@ -32,12 +32,13 @@ The Contacts application allows third-party applications to invoke the system ca
**Table 1** Version mapping of software and tools
-| Software/Tool| Version| Remarks|
+| Software/Tool| Version| Remarks|
| -------- | -------- | -------- |
-| OpenHarmony | 3.1.1 Release | NA |
-| SDK | Ohos_sdk_full 3.1.6.5 (API Version 8 Release) | NA |
-| (Optional) HUAWEI DevEco Studio| 3.0 Beta3 for OpenHarmony | Recommended for developing OpenHarmony applications|
-| (Optional) HUAWEI DevEco Device Tool| 3.0 Release | Recommended for developing OpenHarmony devices|
+| OpenHarmony | 3.1.1 Release | NA |
+| Public SDK | Ohos_sdk_public 3.1.6.6 (API Version 8 Release)| This toolkit is intended for application developers and does not contain system APIs that require system permissions.
It is provided as standard in DevEco Studio 3.0 Beta4 or later.
The public SDK of API version 8 was released on July 6, 2022.|
+| Full SDK | Ohos_sdk_full 3.1.6.5 (API Version 8 Release) | This toolkit is intended for original equipment manufacturers (OEMs) and contains system APIs that require system permissions.
To use the full SDK, manually obtain it from the mirror and switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../application-dev/quick-start/full-sdk-switch-guide.md).|
+| (Optional) HUAWEI DevEco Studio| 3.0 Beta3 for OpenHarmony | This tool is recommended for developing OpenHarmony applications.|
+| (Optional) HUAWEI DevEco Device Tool| 3.0 Release | This tool is recommended for developing OpenHarmony smart devices.|
## Source Code Acquisition
@@ -101,8 +102,10 @@ repo forall -c 'git lfs pull'
| Hi3861 mini system solution (binary) | 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/hispark_pegasus.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/hispark_pegasus.tar.gz.sha256) |
| Hi3516 mini system solution - LiteOS (binary)| 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/hispark_taurus.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/hispark_taurus.tar.gz.sha256) |
| Hi3516 mini system solution - Linux (binary) | 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/hispark_taurus_linux.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/hispark_taurus_linux.tar.gz.sha256) |
-| Standard system SDK package (macOS) | 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-mac-full.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-mac-full.tar.gz.sha256)|
-| Standard system SDK package (Windows/Linux) | 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-full.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-full.tar.gz.sha256)|
+| Full SDK package for the standard system (macOS) | 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-mac-full.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-mac-full.tar.gz.sha256)|
+| Full SDK package for the standard system (Windows/Linux) | 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-full.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-full.tar.gz.sha256)|
+| Public SDK package for the standard system (macOS)| 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-mac-public.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-mac-public.tar.gz.sha256)|
+| Public SDK package for the standard system (Windows/Linux)| 3.1.1 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-public.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/ohos-sdk-public.tar.gz.sha256)|
## What's New
@@ -114,21 +117,22 @@ This version has the following updates to OpenHarmony 3.1 Release.
**Table 3** New and enhanced features
- | Subsystem| Standard System| Mini and Small Systems|
+| Subsystem| Standard System| Mini and Small Systems|
| -------- | -------- | -------- |
-| System service management| Added group verification.
The following requirement is involved:
I52G5Q Adding group verification| NA |
-| Power management| Added the APIs for brightness adjustment and battery information query.
The following requirements are involved:
I526UP Supporting the **\@system.brightness** APIs
I526UP Supporting the **\@system.battery** APIs| NA |
-| Bundle management| Added the APIs for querying whether a specified application is installed.
The following requirements are involved:
I56EWD Test framework configuration
I55RZJ Querying whether a specified application is installed| NA |
-| Location service| Added compatibility with basic positioning APIs.
The following requirement is involved:
I53WFP Basic positioning capabilities and system APIs| NA |
-| Ability| Added the following features to the FA model: ability-level screen orientation query and setting, lock screen display, and screen-on upon startup.
The following requirements are involved:
I56EH7 Querying and setting the landscape/portrait mode for an ability in the FA model
I50D5Y Lock screen display for an ability in the FA model
I56EH7 Screen-on during ability startup in the FA model
I55WB0 Carrying images in widget data
I55WB0 FA widget capability supplement - formManager reconstruction
I55WB0 FA widget capability supplement - widget status query
I55WB0 FA widget capability supplement - deleting invalid widgets
I55WB0 FA widget capability supplement - separate setting of the visibility and update status of widgets
I50D8H Interception of uncatched exceptions
I50D91 ANR processing| NA |
-| Media| Added APIs related to audio focus and audio decoding.
The following requirements are involved:
I56REO Supplementing audio focus/device APIs
I522W0 AMR audio encoding| NA |
-| Window manager| Added support for setting window properties.
The following requirement is involved:
I56EH7 Window property setting| NA |
-| Network management| Added support for WebSocket and fetch APIs and Ethernet connections.
The following requirements are involved:
I53CKH Supporting the **\@system.fetch** APIs
I53CJX Supporting the **\@system.network** APIs
I53CKT WebSocket support
I580PC Ethernet connections| NA |
-| Misc services| Added compatibility with HTTP file download APIs.
The following requirement is involved:
I56Q4X Supporting file download APIs| NA |
-| Common event and notification| Added the APIs for sending and canceling notifications.
The following requirements are involved:
I50EEW APIs for sending and canceling notifications| NA |
-| Distributed data management| Added compatibility with the **\@system.storage** APIs.
The following requirement is involved:
I56RF3 Supporting the **\@system.storage** APIs| NA |
-| Startup| Added compatibility with the **\@system.device** APIs.
The following requirement is involved:
I56GBS Supporting the **\@system.device** APIs| NA |
-| System applications| The Contacts application allows third-party applications to invoke the system call capability.
The following requirements are involved:
I58ZQ4 The Contacts application allows third-party applications to invoke the system call capability.| NA |
+| SDK | SDKs are classified into full SDKs and public SDKs.
Note: The public SDK of API version 8 was released on July 6, 2022.| NA |
+| System service management| Added group verification.
The following requirement is involved:
I52G5Q Adding group verification| NA |
+| Power management| Added the APIs for brightness adjustment and battery information query.
The following requirements are involved:
I526UP Supporting the **\@system.brightness** APIs
I526UP Supporting the **\@system.battery** APIs| NA |
+| Bundle management| Added the APIs for querying whether a specified application is installed.
The following requirements are involved:
I56EWD Test framework configuration
I55RZJ Querying whether a specified application is installed| NA |
+| Location service| Added compatibility with basic positioning APIs.
The following requirement is involved:
I53WFP Basic positioning capabilities and system APIs| NA |
+| Ability| Added the following features to the FA model: ability-level screen orientation query and setting, lock screen display, and screen-on upon startup.
The following requirements are involved:
I56EH7 Querying and setting the landscape/portrait mode for an ability in the FA model
I50D5Y Lock screen display for an ability in the FA model
I56EH7 Screen-on during ability startup in the FA model
I55WB0 Carrying images in widget data
I55WB0 FA widget capability supplement - formManager reconstruction
I55WB0 FA widget capability supplement - widget status query
I55WB0 FA widget capability supplement - deleting invalid widgets
I55WB0 FA widget capability supplement - separate setting of the visibility and update status of widgets
I50D8H Interception of uncatched exceptions
I50D91 Application Not Response processing| NA |
+| Media| Added APIs related to audio focus and audio decoding.
The following requirements are involved:
I56REO Supplementing audio focus/device APIs
I522W0 AMR audio encoding| NA |
+| Window manager| Added support for setting window properties.
The following requirement is involved:
I56EH7 Window property setting| NA |
+| Network management| Added support for WebSocket and fetch APIs and Ethernet connections.
The following requirements are involved:
I53CKH Supporting the **\@system.fetch** APIs
I53CJX Supporting the **\@system.network** APIs
I53CKT WebSocket support
I580PC Ethernet connections| NA |
+| Misc services| Added compatibility with HTTP file download APIs.
The following requirement is involved:
I56Q4X Supporting file download APIs| NA |
+| Common event and notification| Added the APIs for sending and canceling notifications.
The following requirements are involved:
I50EEW APIs for sending and canceling notifications| NA |
+| Distributed data management| Added compatibility with the **\@system.storage** APIs.
The following requirement is involved:
I56RF3 Supporting the **\@system.storage** APIs| NA |
+| Startup| Added compatibility with the **\@system.device** APIs.
The following requirement is involved:
I56GBS Supporting the **\@system.device** APIs| NA |
+| System applications| The Contacts application allows third-party applications to invoke the system call capability.
The following requirements are involved:
I58ZQ4 The Contacts application allows third-party applications to invoke the system call capability.| NA |
### API Updates
@@ -159,4 +163,4 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| ------------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------- | ------------ |
| [I4Z3G9](https://gitee.com/openharmony/graphic_graphic_2d/issues/I4Z3G9) | [RK3568] Screen flickering occurs when the secondary window is opened in the immersive primary window.| Developer experience is affected. | 2022-06-15 |
| [I58GFY](https://gitee.com/openharmony/communication_wifi/issues/I58GFY) | [RK3568] On the 2.4 GHz and 5 GHz frequency bands, connections fail in WPA+TKIP/AES encryption mode. | The TP-Link AX50 router cannot connect to the Wi-Fi network. | 2022-06-30 |
-| [I59P32](https://gitee.com/openharmony/device_manager/issues/I59P32) | [RK3568] After the trust period of a device expires, PIN authentication cannot be performed. | This issue occurs when the timer waiting for the PIN code input times out. It can be resolved by restarting the device.| 2022-06-15 |
+| [I59P32](https://gitee.com/openharmony/distributedhardware_device_manager/issues/I59P32) | [RK3568] After the trust period of a device expires, PIN authentication cannot be performed. | This issue occurs when the timer waiting for the PIN code input times out. It can be resolved by restarting the device.| 2022-06-15 |
diff --git a/en/release-notes/api-change/v3.2-beta/js-apidiff-distributedschedule.md b/en/release-notes/api-change/v3.2-beta/js-apidiff-distributedschedule.md
new file mode 100644
index 0000000000000000000000000000000000000000..d07a990a8e198a5f02adff1e3ad68960713eedb3
--- /dev/null
+++ b/en/release-notes/api-change/v3.2-beta/js-apidiff-distributedschedule.md
@@ -0,0 +1,16 @@
+# JS API Changes of the Distributed Scheduler Subsystem
+
+The table below lists the APIs changes of the distributed scheduler subsystem in OpenHarmony 3.2 Beta1 over OpenHarmony 3.1 Release.
+
+## API Changes
+
+| Module| Class| Method/Attribute/Enumeration/Constant| Change Type|
+|---|---|---|---|
+| ohos.continuation.continuationManager | continuationManager | on(type: "deviceConnect", token: number, callback: Callback\>): void; | Added|
+| ohos.continuation.continuationManager | continuationManager | off(type: "deviceConnect", token: number): void; | Added|
+| ohos.continuation.continuationManager | continuationManager | on(type: "deviceDisconnect", token: number, callback: Callback\>): void; | Added|
+| ohos.continuation.continuationManager | continuationManager | off(type: "deviceDisconnect", token: number): void; | Added|
+| ohos.continuation.continuationManager | continuationManager | on(type: "deviceConnect", callback: Callback\): void; | Deprecated|
+| ohos.continuation.continuationManager | continuationManager | off(type: "deviceConnect", callback?: Callback\): void; | Deprecated|
+| ohos.continuation.continuationManager | continuationManager | on(type: "deviceDisconnect", callback: Callback\): void; | Deprecated|
+| ohos.continuation.continuationManager | continuationManager | off(type: "deviceDisconnect", callback?: Callback\): void; | Deprecated|
diff --git a/zh-cn/OpenHarmony-Overview_zh.md b/zh-cn/OpenHarmony-Overview_zh.md
index ef80e6f0d7140b6e17a37a5506e6db83d67a6e39..d1e7d2846472ee5b603c6b576560b8ba4afe2ac9 100644
--- a/zh-cn/OpenHarmony-Overview_zh.md
+++ b/zh-cn/OpenHarmony-Overview_zh.md
@@ -1,27 +1,10 @@
# OpenHarmony开源项目
-- [项目介绍](#section1270210396435)
-- [技术架构](#section2502124574318)
-- [技术特性](#section12212842173518)
-- [系统类型](#section145241459142416)
-- [详细特征](#section25831825174419)
-- [支持的开发板](#section25831825174123)
-- [快速入门](#section44681652104210)
-- [代码仓地址](#section107651249181914)
-- [开发者文档](#section21031470109)
-- [源码下载](#section39011923144212)
-- [示例教程](#sectionsamples)
-- [如何参与](#section19611528174215)
-- [许可协议](#section1245517472115)
-- [联系方式](#section61728335424)
-
-[View English](https://gitee.com/openharmony/docs/blob/master/en/OpenHarmony-Overview.md)
-
-## 项目介绍
+## 项目介绍
OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及运营的开源项目,目标是面向全场景、全连接、全智能时代,基于开源的方式,搭建一个智能终端设备操作系统的框架和平台,促进万物互联产业的繁荣发展。
-## 技术架构
+## 技术架构
OpenHarmony整体遵从分层设计,从下向上依次为:内核层、系统服务层、框架层和应用层。系统功能按照“系统 \> 子系统 \> 组件”逐级展开,在多设备部署场景下,支持根据实际需求裁剪某些非必要的组件。OpenHarmony技术架构如下所示:
@@ -57,47 +40,47 @@ OpenHarmony整体遵从分层设计,从下向上依次为:内核层、系统
应用层包括系统应用和第三方非系统应用。应用由一个或多个FA(Feature Ability)或PA(Particle Ability)组成。其中,FA有UI界面,提供与用户交互的能力;而PA无UI界面,提供后台运行任务的能力以及统一的数据访问抽象。基于FA/PA开发的应用,能够实现特定的业务功能,支持跨设备调度与分发,为用户提供一致、高效的应用体验。
-## 技术特性
+## 技术特性
-1. **硬件互助,资源共享**
+**硬件互助,资源共享**
- 主要通过下列模块达成
+主要通过下列模块达成
- - 分布式软总线
+- 分布式软总线
- 分布式软总线是多设备终端的统一基座,为设备间的无缝互联提供了统一的分布式通信能力,能够快速发现并连接设备,高效地传输任务和数据。
+ 分布式软总线是多设备终端的统一基座,为设备间的无缝互联提供了统一的分布式通信能力,能够快速发现并连接设备,高效地传输任务和数据。
- - 分布式数据管理
+- 分布式数据管理
- 分布式数据管理位于基于分布式软总线之上的能力,实现了应用程序数据和用户数据的分布式管理。用户数据不再与单一物理设备绑定,业务逻辑与数据存储分离,应用跨设备运行时数据无缝衔接,为打造一致、流畅的用户体验创造了基础条件
+ 分布式数据管理位于基于分布式软总线之上的能力,实现了应用程序数据和用户数据的分布式管理。用户数据不再与单一物理设备绑定,业务逻辑与数据存储分离,应用跨设备运行时数据无缝衔接,为打造一致、流畅的用户体验创造了基础条件
- - 分布式任务调度
+- 分布式任务调度
- 分布式任务调度基于分布式软总线、分布式数据管理、分布式Profile等技术特性,构建统一的分布式服务管理(发现、同步、注册、调用)机制,支持对跨设备的应用进行远程启动、远程调用、绑定/解绑、以及迁移等操作,能够根据不同设备的能力、位置、业务运行状态、资源使用情况并结合用户的习惯和意图,选择最合适的设备运行分布式任务
+ 分布式任务调度基于分布式软总线、分布式数据管理、分布式Profile等技术特性,构建统一的分布式服务管理(发现、同步、注册、调用)机制,支持对跨设备的应用进行远程启动、远程调用、绑定/解绑、以及迁移等操作,能够根据不同设备的能力、位置、业务运行状态、资源使用情况并结合用户的习惯和意图,选择最合适的设备运行分布式任务
- - 设备虚拟化
+- 设备虚拟化
- 分布式设备虚拟化平台可以实现不同设备的资源融合、设备管理、数据处理,将周边设备作为手机能力的延伸,共同形成一个超级虚拟终端。
+ 分布式设备虚拟化平台可以实现不同设备的资源融合、设备管理、数据处理,将周边设备作为手机能力的延伸,共同形成一个超级虚拟终端。
-2. **一次开发,多端部署**
+**一次开发,多端部署**
- OpenHarmony提供用户程序框架、Ability框架以及UI框架,能够保证开发的应用在多终端运行时保证一致性。一次开发、多端部署。
+OpenHarmony提供用户程序框架、Ability框架以及UI框架,能够保证开发的应用在多终端运行时保证一致性。一次开发、多端部署。
- 多终端软件平台API具备一致性,确保用户程序的运行兼容性。
+多终端软件平台API具备一致性,确保用户程序的运行兼容性。
- - 支持在开发过程中预览终端的能力适配情况(CPU/内存/外设/软件资源等)。
- - 支持根据用户程序与软件平台的兼容性来调度用户呈现。
+- 支持在开发过程中预览终端的能力适配情况(CPU/内存/外设/软件资源等)。
+- 支持根据用户程序与软件平台的兼容性来调度用户呈现。
-3. **统一OS,弹性部署**
+**统一OS,弹性部署**
- OpenHarmony通过组件化和组件弹性化等设计方法,做到硬件资源的可大可小,在多种终端设备间,按需弹性部署,全面覆盖了ARM、RISC-V、x86等各种CPU,从百KiB到GiB级别的RAM。
+OpenHarmony通过组件化和组件弹性化等设计方法,做到硬件资源的可大可小,在多种终端设备间,按需弹性部署,全面覆盖了ARM、RISC-V、x86等各种CPU,从百KiB到GiB级别的RAM。
-## 系统类型
+## 系统类型
OpenHarmony支持如下几种系统类型:
@@ -114,7 +97,7 @@ OpenHarmony支持如下几种系统类型:
面向应用处理器例如Arm Cortex-A的设备,支持的设备最小内存为128MiB,可以提供增强的交互能力、3D GPU以及硬件合成能力、更多控件以及动效更丰富的图形能力、完整的应用框架。可支撑的产品如高端的冰箱显示屏。
-## 详细特征
+## 详细特征
在介绍OpenHarmony特性前,需要先明确以下两个基本概念:
@@ -126,228 +109,42 @@ OpenHarmony支持如下几种系统类型:
对子系统的进一步拆分,可复用的软件单元,它包含源码、配置文件、资源文件和编译脚本;能独立构建,以二进制方式集成,具备独立验证能力的二进制单元。
-
以下为OpenHarmony中相关的子系统简介,详细介绍见子系统Readme文档,入口:[https://gitee.com/openharmony/docs/tree/master/zh-cn/readme](https://gitee.com/openharmony/docs/tree/master/zh-cn/readme)。
-
-
-子系 统
- |
-简 介
- |
-适用范围
- |
-
-
-内核
- |
-支持适用于嵌入式设备及资源受限设备,具有小体积、高性能、低功耗等特征的LiteOS内核;支持基于linux kernel演进的适用于标准系统的linux内核。
- |
-小型系统
-标准系统
- |
-
-分布式文件
- |
-提供本地同步JS文件接口。
- |
-标准系统
- |
-
-图形
- |
-主要包括UI组件、布局、动画、字体、输入事件、窗口管理、渲染绘制等模块,构建基于轻量OS应用框架满足硬件资源较小的物联网设备或者构建基于标准OS的应用框架满足富设备(如平板和轻智能机等)的OpenHarmony系统应用开发。
- |
-所有系统
- |
-
-驱动
- |
-OpenHarmony驱动子系统采用C面向对象编程模型构建,通过平台解耦、内核解耦,兼容不同内核,提供了归一化的驱动平台底座,旨在为开发者提供更精准、更高效的开发环境,力求做到一次开发,多系统部署。
- |
-所有系统
- |
-
-电源管理服务
- |
-电源管理服务子系统提供如下功能:重启系统;管理休眠运行锁;系统电源状态管理和查询;充电和电池状态查询和上报;显示亮灭屏状态管理,包括显示亮度调节。
- |
-标准系统
- |
-
-泛Sensor服务
- |
-泛Sensor中包含传感器和小器件,传感器用于侦测环境中所发生事件或变化,并将此消息发送至其他电子设备,小器件用于向外传递信号的设备,包括马达和LED灯,对开发者提供控制马达振动和LED灯开关的能力。
- |
-小型系统
- |
-
-多模输入
- |
-OpenHarmony旨在为开发者提供NUI(Natural User Interface)的交互方式,有别于传统操作系统的输入,在OpenHarmony上,我们将多种维度的输入整合在一起,开发者可以借助应用程序框架、系统自带的UI组件或API接口轻松地实现具有多维、自然交互特点的应用程序。具体来说,多模输入子系统目前支持传统的输入交互方式,例如按键和触控。
- |
-标准系统
- |
-
-启动恢复
- |
-启动恢复负责在内核启动之后,应用启动之前的操作系统中间层的启动。并提供系统属性查询、修改及设备恢复出厂设置的功能。
- |
-所有系统
- |
-
-升级服务
- |
-可支持OpenHarmony设备的OTA(Over The Air)升级。
- |
-标准系统
- |
-
-帐号
- |
-支持在端侧对接厂商云帐号应用,提供分布式帐号登录状态查询和更新的管理能力。
- |
-标准系统
- |
-
-编译构建
- |
-编译构建子系统提供了一个基于Gn和ninja的编译构建框架。
- |
-所有系统
- |
-
-测试
- |
-开发过程采用测试驱动开发模式,开发者基于系统新增特性可以通过开发者自己开发用例保证,对于系统已有特性的修改,也可通过修改项目中原有的测试用例保证,开发者测试旨在帮助开发者在开发阶段就能开发出高质量代码。
- |
-所有系统
- |
-
-数据管理
- |
-数据管理支持应用本地数据管理和分布式数据管理:
-- 支持应用本地数据管理,包括轻量级偏好数据库,关系型数据库。
- 支持分布式数据服务,为应用程序提供不同设备间数据库数据分布式的能力。
- |
-标准系统
- |
-
-语言编译运行时
- |
-语言运行时提供了JS、C/C++语言程序的编译、执行环境,提供支撑运行时的基础库,以及关联的API接口、编译器和配套工具。
- |
-所有系统
- |
-
-分布式任务调度
- |
-提供系统服务的启动、注册、查询及管理能力。
- |
-所有系统
- |
-
-JS UI框架
- |
-JS UI框架是OpenHarmony UI开发框架,支持类Web范式编程。
- |
-所有系统
- |
-
-媒体
- |
-提供音频、视频、相机等简单有效的媒体组件开发接口,使得应用开发者轻松使用系统的多媒体资源。
- |
-所有系统
- |
-
-事件通知
- |
-公共事件管理实现了订阅、退订、发布、接收公共事件(例如亮灭屏事件、USB插拔事件)的能力。
- |
-标准系统
- |
-
-杂散软件服务
- |
-提供设置时间的能力。
- |
-标准系统
- |
-
-包管理子系统
- |
-提供包安装、卸载、更新、查询等能力。
- |
-所有系统
- |
-
-电话服务
- |
-提供SIM卡、搜网、蜂窝数据、蜂窝通话、短彩信等蜂窝移动网络基础通信能力,可管理多类型通话和数据网络连接,为应用开发者提供便捷一致的通信API。
- |
-标准系统
- |
-
-公共基础类库
- |
-公共基础库存放OpenHarmony通用的基础组件。这些基础组件可被OpenHarmony各业务子系统及上层应用所使用。
- |
-所有系统
- |
-
-研发工具链
- |
-提供设备连接调试器hdc;提供了性能跟踪能力和接口;提供了性能调优框架,旨在为开发者提供一套性能调优平台,可以用来分析内存、性能等问题。
- |
-标准系统
- |
-
-分布式软总线
- |
-分布式软总线旨在为OpenHarmony系统提供跨进程或跨设备的通信能力,主要包含软总线和进程间通信两部分。其中,软总线为应用和系统提供近场设备间分布式通信的能力,提供不区分通信方式的设备发现,连接,组网和传输功能;而进程间通信则提供了对设备内或设备间无差别的进程间通信能力。
- |
-所有系统
- |
-
-XTS
- |
-XTS是OpenHarmony兼容性测试套件的集合,当前包括acts(application compatibility test suite)应用兼容性测试套,后续会拓展dcts(device compatibility test suite)设备兼容性测试套等。
- |
-所有系统
- |
-
-系统应用
- |
-系统应用提供了OpenHarmony标准版上的部分系统应用,如桌面、SystemUI、设置等应用,为开发者提供了构建标准版应用的具体实例,这些应用支持在所有标准版系统的设备上使用。
- |
-标准系统
- |
-
-DFX
- |
-DFX是OpenHarmony非功能属性能力,包含日志系统、应用和系统事件日志接口、事件日志订阅服务、故障信息生成采集等功能。
- |
-所有系统
- |
-
-全球化
- |
-当OpenHarmony设备或应用在全球不同区域使用时,系统和应用需要满足不同市场用户关于语言、文化习俗的需求。全球化子系统提供支持多语言、多文化的能力,包括资源管理能力和国际化能力。
- |
-所有系统
- |
-
-安全
- |
-安全子系统包括系统安全、数据安全、应用安全等模块,为OpenHarmony提供了保护系统和和用户数据的能力。安全子系统当前开源的功能,包括应用完整性保护、应用权限管理、设备认证、密钥管理服务。
- |
-所有系统
- |
-
-
-
-
-## 支持的开发板
+
+| 子系统 | 简 介 | 适用范围 |
+| -------- | -------- | -------- |
+| 内核 | 支持适用于嵌入式设备及资源受限设备,具有小体积、高性能、低功耗等特征的LiteOS内核;支持基于linux kernel演进的适用于标准系统的linux内核。 | 小型系统
标准系统 |
+| 分布式文件 | 提供本地同步JS文件接口。 | 标准系统 |
+| 图形 | 主要包括UI组件、布局、动画、字体、输入事件、窗口管理、渲染绘制等模块,构建基于轻量OS应用框架满足硬件资源较小的物联网设备或者构建基于标准OS的应用框架满足富设备(如平板和轻智能机等)的OpenHarmony系统应用开发。 | 所有系统 |
+| 驱动 | OpenHarmony驱动子系统采用C面向对象编程模型构建,通过平台解耦、内核解耦,兼容不同内核,提供了归一化的驱动平台底座,旨在为开发者提供更精准、更高效的开发环境,力求做到一次开发,多系统部署。 | 所有系统 |
+| 电源管理服务 | 电源管理服务子系统提供如下功能:重启系统;管理休眠运行锁;系统电源状态管理和查询;充电和电池状态查询和上报;显示亮灭屏状态管理,包括显示亮度调节。 | 标准系统 |
+| 泛Sensor服务 | 泛Sensor中包含传感器和小器件,传感器用于侦测环境中所发生事件或变化,并将此消息发送至其他电子设备,小器件用于向外传递信号的设备,包括马达和LED灯,对开发者提供控制马达振动和LED灯开关的能力。 | 小型系统 |
+| 多模输入 | OpenHarmony旨在为开发者提供NUI(Natural User Interface)的交互方式,有别于传统操作系统的输入,在OpenHarmony上,我们将多种维度的输入整合在一起,开发者可以借助应用程序框架、系统自带的UI组件或API接口轻松地实现具有多维、自然交互特点的应用程序。具体来说,多模输入子系统目前支持传统的输入交互方式,例如按键和触控。 | 标准系统 |
+| 启动恢复 | 启动恢复负责在内核启动之后,应用启动之前的操作系统中间层的启动。并提供系统属性查询、修改及设备恢复出厂设置的功能。 | 所有系统 |
+| 升级服务 | 可支持OpenHarmony设备的OTA(Over The Air)升级。 | 标准系统 |
+| 帐号 | 支持在端侧对接厂商云帐号应用,提供分布式帐号登录状态查询和更新的管理能力。 | 标准系统 |
+| 编译构建 | 编译构建子系统提供了一个基于Gn和ninja的编译构建框架。 | 所有系统 |
+| 测试 | 开发过程采用测试驱动开发模式,开发者基于系统新增特性可以通过开发者自己开发用例保证,对于系统已有特性的修改,也可通过修改项目中原有的测试用例保证,开发者测试旨在帮助开发者在开发阶段就能开发出高质量代码。 | 所有系统 |
+| 数据管理 | 数据管理支持应用本地数据管理和分布式数据管理:
- 支持应用本地数据管理,包括轻量级偏好数据库,关系型数据库。
- 支持分布式数据服务,为应用程序提供不同设备间数据库数据分布式的能力。 | 标准系统 |
+| 语言编译运行时 | 语言运行时提供了JS、C/C++语言程序的编译、执行环境,提供支撑运行时的基础库,以及关联的API接口、编译器和配套工具。 | 所有系统 |
+| 分布式任务调度 | 提供系统服务的启动、注册、查询及管理能力。 | 所有系统 |
+| JS UI框架 | JS UI框架是OpenHarmony UI开发框架,支持类Web范式编程。 | 所有系统 |
+| 媒体 | 提供音频、视频、相机等简单有效的媒体组件开发接口,使得应用开发者轻松使用系统的多媒体资源。 | 所有系统 |
+| 事件通知 | 公共事件管理实现了订阅、退订、发布、接收公共事件(例如亮灭屏事件、USB插拔事件)的能力。 | 标准系统 |
+| 杂散软件服务 | 提供设置时间的能力。 | 标准系统 |
+| 包管理子系统 | 提供包安装、卸载、更新、查询等能力。 | 所有系统 |
+| 电话服务 | 提供SIM卡、搜网、蜂窝数据、蜂窝通话、短彩信等蜂窝移动网络基础通信能力,可管理多类型通话和数据网络连接,为应用开发者提供便捷一致的通信API。 | 标准系统 |
+| 公共基础类库 | 公共基础库存放OpenHarmony通用的基础组件。这些基础组件可被OpenHarmony各业务子系统及上层应用所使用。 | 所有系统 |
+| 研发工具链 | 提供设备连接调试器hdc;提供了性能跟踪能力和接口;提供了性能调优框架,旨在为开发者提供一套性能调优平台,可以用来分析内存、性能等问题。 | 标准系统 |
+| 分布式软总线 | 分布式软总线旨在为OpenHarmony系统提供跨进程或跨设备的通信能力,主要包含软总线和进程间通信两部分。其中,软总线为应用和系统提供近场设备间分布式通信的能力,提供不区分通信方式的设备发现,连接,组网和传输功能;而进程间通信则提供了对设备内或设备间无差别的进程间通信能力。 | 所有系统 |
+| XTS | XTS是OpenHarmony兼容性测试套件的集合,当前包括acts(application compatibility test suite)应用兼容性测试套,后续会拓展dcts(device compatibility test suite)设备兼容性测试套等。 | 所有系统 |
+| 系统应用 | 系统应用提供了OpenHarmony标准版上的部分系统应用,如桌面、SystemUI、设置等应用,为开发者提供了构建标准版应用的具体实例,这些应用支持在所有标准版系统的设备上使用。 | 标准系统 |
+| DFX | DFX是OpenHarmony非功能属性能力,包含日志系统、应用和系统事件日志接口、事件日志订阅服务、故障信息生成采集等功能。 | 所有系统 |
+| 全球化 | 当OpenHarmony设备或应用在全球不同区域使用时,系统和应用需要满足不同市场用户关于语言、文化习俗的需求。全球化子系统提供支持多语言、多文化的能力,包括资源管理能力和国际化能力。 | 所有系统 |
+| 安全 | 安全子系统包括系统安全、数据安全、应用安全等模块,为OpenHarmony提供了保护系统和和用户数据的能力。安全子系统当前开源的功能,包括应用完整性保护、应用权限管理、设备认证、密钥管理服务。 | 所有系统 |
+
+## 支持的开发板
当前OpenHarmony社区支持17款开发板,下表介绍3款(此处选择三种系统类型首款进入OpenHarmony主干的开发板),更多开发板信息,请参考[社区支持的开发板清单](device-dev/dev-board-on-the-master.md),社区每日构建版本获取地址请参考http://ci.openharmony.cn/dailys/dailybuilds
@@ -357,14 +154,14 @@ OpenHarmony支持如下几种系统类型:
|小型系统 | Hispark_
Taurus | Hi3516DV
300 | 主要能力:
Hi3516DV300是新一
代Smart HD IP摄像
机SOC,集成新一代
ISP(Image Signal P
rocessor)、H.265视频压缩编码
器、高性能NNIE引擎,在低码率
、高画质、智能处理和分析、低
功耗等方面有较好的性能。 | 带屏智能硬件,
比如带屏
冰箱、车
机等。 | [device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_hisilicon](http://gitee.com/openharmony/device_board_hisilicon)
[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon)
|
|轻量系统 | Multi-modal
V200Z-R | BES2600 | 主要能力:
Multi-
modal V200Z-R开发板是基
于恒玄科技BES2600WM芯片的一
款高性能、多功能、高性价比
AIoT SoC开发板Multi-
modal V200Z-R开发板,单
模组集成四核ARM处理器(最高
主频1GHz),集成双频
WiFi + 双模蓝牙,
支持标准的
802.11 a/b/g/n/协议,支
持BT/BLE 5.2协议,内建
多种容量的RAM(最大42MB)和
Flash(最大32MB),支持
MIPI DSI及CSI,适用于各
种AIoT多模态
VUI + GUI交互硬件
场景。
适配案例:
[Multi-modal V200Z-R适配案例](device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md) | 智能硬件、带屏
类模组产
品,如音
箱、手表
等。 | [device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)
[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)
[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic)
|
-## 快速入门
+## 快速入门
- [设备开发快速入门](device-dev/quick-start/quickstart-ide-lite-overview.md)
- [应用开发快速入门](application-dev/quick-start/start-overview.md)
-## 代码仓地址
+## 代码仓地址
OpenHarmony主库组织地址:[https://gitee.com/openharmony](https://gitee.com/openharmony)
@@ -374,7 +171,7 @@ OpenHarmony三方库组织地址:[https://gitee.com/openharmony-tpc](https://g
OpenHarmony归档组织地址:[https://gitee.com/openharmony-retired](https://gitee.com/openharmony-retired)
-## 开发者文档
+## 开发者文档
[访问官网](https://www.openharmony.cn/)
@@ -382,29 +179,29 @@ OpenHarmony归档组织地址:[https://gitee.com/openharmony-retired](https://
[English Version](https://gitee.com/openharmony/docs/tree/master/en)
-## 源码下载
+## 源码下载
获取OpenHarmony源码:[下载说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md)
-## 示例教程
+## 示例教程
Samples:[示例代码](https://gitee.com/openharmony/app_samples)
Codelabs:[教程指导](https://gitee.com/openharmony/codelabs)
-## 如何参与
+## 如何参与
参与社区:[社区介绍](https://gitee.com/openharmony/community/blob/master/README.md)
参与贡献:[如何贡献](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/%E5%8F%82%E4%B8%8E%E8%B4%A1%E7%8C%AE.md)
-## 许可协议
+## 许可协议
OpenHarmony主要遵循Apache License V2.0协议,详情请参考各代码仓LICENSE声明。
OpenHarmony引用三方开源软件及许可证说明,参考[第三方开源软件说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BC%80%E6%BA%90%E8%BD%AF%E4%BB%B6%E5%8F%8A%E8%AE%B8%E5%8F%AF%E8%AF%81%E8%AF%B4%E6%98%8E.md)。
-## 联系方式
+## 联系方式
网站:
diff --git a/zh-cn/application-dev/ability/fa-serviceability.md b/zh-cn/application-dev/ability/fa-serviceability.md
index bae0e29ea3a3947ac0fe5db65d10a2b4e5256a85..58991ec7147c2789774dff1892c68f8a34d72653 100644
--- a/zh-cn/application-dev/ability/fa-serviceability.md
+++ b/zh-cn/application-dev/ability/fa-serviceability.md
@@ -32,7 +32,7 @@
},
onConnect(want) {
console.log('ServiceAbility OnConnect');
- return null;
+ return new FirstServiceAbilityStub('test');
},
onDisconnect(want) {
console.log('ServiceAbility OnDisConnect');
@@ -139,41 +139,36 @@ let promise = featureAbility.startAbility(
```javascript
import prompt from '@system.prompt'
- let mRemote;
- function onConnectCallback(element, remote){
- console.log('onConnectLocalService onConnectDone element: ' + element);
- console.log('onConnectLocalService onConnectDone remote: ' + remote);
- mRemote = remote;
- if (mRemote == null) {
- prompt.showToast({
- message: "onConnectLocalService not connected yet"
- });
- return;
- }
- let option = new rpc.MessageOption();
- let data = new rpc.MessageParcel();
- let reply = new rpc.MessageParcel();
- data.writeInt(1);
- data.writeInt(99);
- mRemote.sendRequest(1, data, reply, option).then((result) => {
- console.log('sendRequest success');
- let msg = reply.readInt();
+ var option = {
+ onConnect: function onConnectCallback(element, proxy) {
+ console.log(`onConnectLocalService onConnectDone`)
+ if (proxy === null) {
+ prompt.showToast({
+ message: "Connect service failed"
+ })
+ return
+ }
+ let data = rpc.MessageParcel.create()
+ let reply = rpc.MessageParcel.create()
+ let option = new rpc.MessageOption()
+ data.writeInterfaceToken("connect.test.token")
+ proxy.sendRequest(0, data, reply, option)
prompt.showToast({
- message: "onConnectLocalService connect result: " + msg,
- duration: 3000
- });
- }).catch((e) => {
- console.log('sendRequest error:' + e);
- });
-
- }
-
- function onDisconnectCallback(element){
- console.log('ConnectAbility onDisconnect Callback')
- }
-
- function onFailedCallback(code){
- console.log('ConnectAbility onFailed Callback')
+ message: "Connect service success"
+ })
+ },
+ onDisconnect: function onDisconnectCallback(element) {
+ console.log(`onConnectLocalService onDisconnectDone element:${element}`)
+ prompt.showToast({
+ message: "Disconnect service success"
+ })
+ },
+ onFailed: function onFailedCallback(code) {
+ console.log(`onConnectLocalService onFailed errCode:${code}`)
+ prompt.showToast({
+ message: "Connect local service onFailed"
+ })
+ }
}
```
@@ -201,44 +196,27 @@ let promise = featureAbility.startAbility(
```javascript
import rpc from "@ohos.rpc";
- let mMyStub;
- export default {
- onStart() {
- class MyStub extends rpc.RemoteObject{
- constructor(des) {
- if (typeof des === 'string') {
- super(des);
- }
- return null;
- }
- onRemoteRequest(code, data, reply, option) {
- console.log("ServiceAbility onRemoteRequest called");
- if (code === 1) {
- let op1 = data.readInt();
- let op2 = data.readInt();
- console.log("op1 = " + op1 + ", op2 = " + op2);
- reply.writeInt(op1 + op2);
- } else {
- console.log("ServiceAbility unknown request code");
- }
- return true;
- }
- }
- mMyStub = new MyStub("ServiceAbility-test");
- },
- onCommand(want, startId) {
- console.log('ServiceAbility onCommand');
- },
- onConnect(want) {
- console.log('ServiceAbility OnConnect');
- return mMyStub;
- },
- onDisconnect(want) {
- console.log('ServiceAbility OnDisConnect');
- },
- onStop() {
- console.log('ServiceAbility onStop');
- },
+ class FirstServiceAbilityStub extends rpc.RemoteObject {
+ constructor(des: any) {
+ if (typeof des === 'string') {
+ super(des)
+ } else {
+ return
+ }
+ }
+
+ onRemoteRequest(code: number, data: any, reply: any, option: any) {
+ console.log(printLog + ` onRemoteRequest called`)
+ if (code === 1) {
+ let string = data.readString()
+ console.log(printLog + ` string=${string}`)
+ let result = Array.from(string).sort().join('')
+ console.log(printLog + ` result=${result}`)
+ reply.writeString(result)
+ } else {
+ console.log(printLog + ` unknown request code`)
+ }
+ return true;
}
```
@@ -255,40 +233,36 @@ let promise = featureAbility.startAbility(
```ts
import prompt from '@system.prompt'
-let mRemote;
-function onConnectCallback(element, remote){
- console.log('onConnectRemoteService onConnectDone element: ' + element);
- console.log('onConnectRemoteService onConnectDone remote: ' + remote);
- mRemote = remote;
- if (mRemote == null) {
- prompt.showToast({
- message: "onConnectRemoteService not connected yet"
- });
- return;
- }
- let option = new rpc.MessageOption();
- let data = new rpc.MessageParcel();
- let reply = new rpc.MessageParcel();
- data.writeInt(1);
- data.writeInt(99);
- mRemote.sendRequest(1, data, reply, option).then((result) => {
- console.log('sendRequest success');
- let msg = reply.readInt();
+var option = {
+ onConnect: function onConnectCallback(element, proxy) {
+ console.log(`onConnectRemoteService onConnectDone`)
+ if (proxy === null) {
+ prompt.showToast({
+ message: "Connect service failed"
+ })
+ return
+ }
+ let data = rpc.MessageParcel.create()
+ let reply = rpc.MessageParcel.create()
+ let option = new rpc.MessageOption()
+ data.writeInterfaceToken("connect.test.token")
+ proxy.sendRequest(0, data, reply, option)
prompt.showToast({
- message: "onConnectRemoteService connect result: " + msg,
- duration: 3000
- });
- }).catch((e) => {
- console.log('sendRequest error:' + e);
- });
-}
-
-function onDisconnectCallback(element){
- console.log('ConnectRemoteAbility onDisconnect Callback')
-}
-
-function onFailedCallback(code){
- console.log('ConnectRemoteAbility onFailed Callback')
+ message: "Connect service success"
+ })
+ },
+ onDisconnect: function onDisconnectCallback(element) {
+ console.log(`onConnectRemoteService onDisconnectDone element:${element}`)
+ prompt.showToast({
+ message: "Disconnect service success"
+ })
+ },
+ onFailed: function onFailedCallback(code) {
+ console.log(`onConnectRemoteService onFailed errCode:${code}`)
+ prompt.showToast({
+ message: "Connect local service onFailed"
+ })
+ }
}
```
@@ -374,23 +348,25 @@ Service侧把自身的实例返回给调用侧的代码示例如下:
```ts
import rpc from "@ohos.rpc";
-class FirstServiceAbilityStub extends rpc.RemoteObject{
- constructor(des) {
+class FirstServiceAbilityStub extends rpc.RemoteObject {
+ constructor(des: any) {
if (typeof des === 'string') {
- super(des);
+ super(des)
} else {
- return null;
+ return
}
}
- onRemoteRequest(code, data, reply, option) {
- console.log("ServiceAbility onRemoteRequest called");
+
+ onRemoteRequest(code: number, data: any, reply: any, option: any) {
+ console.log(printLog + ` onRemoteRequest called`)
if (code === 1) {
- let op1 = data.readInt();
- let op2 = data.readInt();
- console.log("op1 = " + op1 + ", op2 = " + op2);
- reply.writeInt(op1 + op2);
+ let string = data.readString()
+ console.log(printLog + ` string=${string}`)
+ let result = Array.from(string).sort().join('')
+ console.log(printLog + ` result=${result}`)
+ reply.writeString(result)
} else {
- console.log("ServiceAbility unknown request code");
+ console.log(printLog + ` unknown request code`)
}
return true;
}
diff --git a/zh-cn/application-dev/ability/stage-ability-continuation.md b/zh-cn/application-dev/ability/stage-ability-continuation.md
index 260f37a05751269cf368f539214de8632c935e8e..b50cab8a17cfbcb49e8ff6098e410c76b1c3ae18 100755
--- a/zh-cn/application-dev/ability/stage-ability-continuation.md
+++ b/zh-cn/application-dev/ability/stage-ability-continuation.md
@@ -13,7 +13,8 @@
|接口名 | 描述|
|:------ | :------|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | 迁移**发起端**在该回调中保存迁移所需要的数据,同时返回是否同意迁移:AGREE表示同意,REJECT表示拒绝;MISMATCH表示版本不匹配。 |
-| onCreate(want: Want, param : LaunchParam): void | 迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
+| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | 多实例应用迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
+| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | 单实例应用迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
@@ -21,10 +22,12 @@

-迁移实际上是Ability携带数据的跨端启动。触发迁移动作时,会在A设备上通过系统回调应用的onContinue()方法,开发者需要在此方法中实现当前数据的保存。然后系统发起在B设备上的跨端启动,并将数据一同传输到B设备。B设备系统回调onCreate()方法,开发者需要在此方法中实现传输过来的数据的恢复。
+迁移实际上是Ability携带数据的跨端启动。触发迁移动作时,会在A设备上通过系统回调应用的onContinue()方法,开发者需要在此方法中实现当前数据的保存。然后系统发起在B设备上的跨端启动,并将数据一同传输到B设备。B设备系统回调onCreate()/onNewWant()方法,开发者需要在此方法中实现传输过来的数据的恢复。
## 开发步骤
+下文代码片段来自参考[示例](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/samples/continuationManualTestSuite)。
+
### 迁移应用
1. 配置
@@ -32,9 +35,17 @@
- 配置应用支持迁移
在module.json5中配置continuable字段:true表示支持迁移,false表示不支持,默认为false。配置为false的应用将被系统识别为无法迁移。
-
+
```javascript
- "continuable": true
+ {
+ "module": {
+ "abilities": [
+ {
+ "continuable": true,
+ }
+ ]
+ }
+ }
```
@@ -42,30 +53,53 @@
- 配置应用启动类型
- 迁移当前只支持多实例应用,需要在在module.json5中配置launchType字段为standard。
+ 多实例应用在module.json5中将launchType字段配置为standard,目标端将会拉起一个新的应用,并恢复页面;单实例将该字段配置为singleton,如果目标端应用已经打开,迁移将会将已有页面栈清空,并根据迁移数据恢复页面。关于单实例与多实例的更多信息详见[ability开发指导](./stage-ability.md)启动模式。
+
+ 多实例:
```javascript
- "launchType": "standard"
+ {
+ "module": {
+ "abilities": [
+ {
+ "launchType": "standard",
+ }
+ ]
+ }
+ }
```
-
-
-
+ 缺省或如下配置为单实例:
+
+ ```javascript
+ {
+ "module": {
+ "abilities": [
+ {
+ "launchType": "singleton",
+ }
+ ]
+ }
+ }
+ ```
+
+
+
- 申请分布式权限
支持跨端迁移的应用需要在module.json5申请分布式权限 DISTRIBUTED_DATASYNC。
-
+
```javascript
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
},
```
-
+
这个权限需要在应用首次启动的时候弹窗让用户授予,可以通过在ability的onWindowStageCreate中添加如下代码实现:
-
+
```javascript
requestPermissions = async () => {
let permissions: Array = [
@@ -102,12 +136,11 @@
}
}
```
-
-
-2. 实现onContinue()接口
+
+2. 实现onContinue接口
onContinue()接口在发起端被调用,主要用于在迁移发起时,通知开发者保存控件状态变量和内存中数据,准备迁移。当应用准备完成后,需要返回OnContinueResult.AGREE(0)表示同意迁移,否则返回相应的错误码拒绝迁移。如果不实现该接口,系统将默认为拒绝迁移。
@@ -119,22 +152,25 @@
```
要实现迁移,此接口必须实现并返回AGREE,否则默认为拒绝迁移。
-
+
+ 另外,在该接口的入参wantParam中可以获取目标设备的deviceId(key为“targetDevice”),以及目标设备上所安装的应用的版本号(key为“version”)。版本号可用来与本应用版本进行对比,做兼容性判断,如果判定本应用版本与远端不兼容,可以返回OnContinueResult.MISMATCH拒绝迁移。
+
示例
-
+
```javascript
- onContinue(wantParam : {[key: string]: any}) {
- Logger.info("onContinue using distributedObject")
- // set user input data into want params
- wantParam["input"] = AppStorage.Get('ContinueInput');
- Logger.info(`onContinue input = ${wantParam["input"]}`);
- return AbilityConstant.OnContinueResult.AGREE
- }
+ onContinue(wantParam : {[key: string]: any}) {
+ Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
+ let workInput = AppStorage.Get('ContinueWork');
+ // set user input data into want params
+ wantParam["work"] = workInput // set user input data into want params
+ Logger.info(`onContinue input = ${wantParam["input"]}`);
+ return AbilityConstant.OnContinueResult.AGREE
+ }
```
-
+
-3. 在onCreate()接口中实现迁移逻辑
+3. 在onCreate/onNewWant接口中实现迁移逻辑
onCreate()接口在迁移目标端被调用,在目标端ability被拉起时,通知开发者同步已保存的内存数据和控件状态,完成后触发页面的恢复。如果不实现该接口中迁移相关逻辑,ability将会作为普通的启动方式拉起,无法恢复页面。
@@ -142,22 +178,34 @@
完成数据恢复后,开发者需要调用restoreWindowStage来触发页面恢复。
- 示例
+
+ 在入参want中也可以通过want.parameters.version来获取发起端的应用版本号。
+
+ 示例
+
```javascript
- onCreate(want, launchParam) {
- Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
- globalThis.abilityWant = want;
- if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
- let input = want.parameters.input // get user data from want params
- AppStorage.SetOrCreate('ContinueInput', input)
- Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
-
- this.contentStorage = new ContentStorage();
- this.context.restoreWindowStage(this.contentStorage);
- }
- }
+ import Ability from '@ohos.application.Ability';
+ import distributedObject from '@ohos.data.distributedDataObject';
+
+ export default class MainAbility extends Ability {
+ storage : LocalStorag;
+
+ onCreate(want, launchParam) {
+ Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
+ if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
+ // get user data from want params
+ let workInput = want.parameters.work
+ Logger.info(`work input ${workInput}`)
+ AppStorage.SetOrCreate('ContinueWork', workInput)
+
+ this.storage = new LocalStorage();
+ this.context.restoreWindowStage(this.storage);
+ }
+ }
+ }
```
+如果是单实例应用,则同样的代码实现onNewWant接口即可。
@@ -165,32 +213,42 @@
使用分布式对象
-分布式数据对象提供了与本地变量类似的操作,实现两个设备的数据同步,当设备1的应用A的分布式数据对象增、删、改数据后,设备2的应用A也可以获取到对应的数据变化,同时还能监听数据变更以及对端数据对象的上下线。用法详见[分布式对象指导文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/database-distributedobject-guidelines.md)。
+分布式数据对象提供了与本地变量类似的操作,实现两个设备的数据同步,当设备1的应用A的分布式数据对象增、删、改数据后,设备2的应用A也可以获取到对应的数据变化,同时还能监听数据变更以及对端数据对象的上下线。用法详见[分布式对象指导文档](../database/database-distributedobject-guidelines.md)。
迁移场景中,分布式对象(distributedDataObject)主要用于将本机内存数据同步到目标设备。
-- 发起端在onContinue()中,将待迁移的数据存入分布式对象中,然后设置好session id,并通过wantParam将session id传到远端设备。
+- 发起端在onContinue()中,将待迁移的数据存入分布式对象中,并调用save接口将数据保存并同步到远端,然后设置好session id,并通过wantParam将session id传到远端设备。
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
- var g_object = distributedObject.createDistributedObject({name:undefined});
+ var g_object = distributedObject.createDistributedObject({data:undefined});
export default class MainAbility extends Ability {
- contentStorage : ContentStorage
sessionId : string;
onContinue(wantParam : {[key: string]: any}) {
- Logger.info("onContinue using distributedObject")
- this.sessionId = distributedObject.genSessionId();
- //set distributed data object session id
- g_object.setSessionId(this.sessionId);
- g_object.name = "Amy";
- // set session id into want params
- wantParam["session"] = this.sessionId;
- return AbilityConstant.OnContinueResult.AGREE
- }
+ Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
+
+ if (g_object.__sessionId === undefined) {
+ this.sessionId = distributedObject.genSessionId()
+ Logger.info(`onContinue generate new sessionId`)
+ }
+ else {
+ this.sessionId = g_object.__sessionId;
+ }
+
+ wantParam["session"] = this.sessionId
+ g_object.data = AppStorage.Get('ContinueStudy');
+ Logger.info(`onContinue sessionId = ${this.sessionId}, name = ${g_object.data}`)
+ g_object.setSessionId(this.sessionId);
+ g_object.save(wantParam.targetDevice, (result, data)=>{
+ Logger.info("save callback");
+ Logger.info("save sessionId " + data.sessionId);
+ Logger.info("save version " + data.version);
+ Logger.info("save deviceId " + data.deviceId);
+ });
```
@@ -201,15 +259,11 @@
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
- var g_object = distributedObject.createDistributedObject({name:undefined});
+ var g_object = distributedObject.createDistributedObject({data:undefined});
export default class MainAbility extends Ability {
- contentStorage : ContentStorage
- sessionId : string;
+ storage : LocalStorag;
- statusCallback(sessionId, networkid, status) {
- Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`)
- }
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
@@ -218,15 +272,40 @@
this.sessionId = want.parameters.session
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
- g_object.on("status", this.statusCallback);
- // set session id, so it will sync data from remote device
- g_object.setSessionId(this.sessionId);
+ // in order to fetch from remote, reset g_object.data to undefined first
+ g_object.data = undefined;
+ // set session id, so it will fetch data from remote
+ g_object.setSessionId(this.sessionId);
- this.contentStorage = new ContentStorage();
- this.context.restoreWindowStage(this.contentStorage);
+ AppStorage.SetOrCreate('ContinueStudy', g_object.data)
+ this.storage = new LocalStorage();
+ this.context.restoreWindowStage(this.storage);
}
+
}
}
```
+
+
+
+### 其他说明
+
+1. 超时机制:
+
+ - 如果目标端迁移应用未安装,系统会去查询在目标端设备上能否安装,这段最大时间为4s,超出此时间,调用者会收到超时错误码,视为不可在目标端安装。若可安装,则系统会提示用户在目标端安装,安装完成后可再次尝试发起迁移。
+ - 如果目标端迁移应用已安装 ,那么发起迁移后超时时间为20s,若超过此时间,调用者会收到超时错误码,视为此次迁移失败。
+
+2. 当前系统默认支持页面栈信息的迁移,即发起端页面栈会被自动迁移到目标端,无需开发者适配。
+
+
+
+### 约束
+
+1. 迁移要求在同ability之间进行,也就是需要相同的bundleName、moduleName和abilityName,具体含义[应用包配置文件说明](../quick-start/stage-structure.md)。
+2. 当前应用只能实现迁移能力,但迁移的动作只能由系统发起。
+
+
+### 最佳实践
+ 为了获得最佳体验,建议100kb以下的数据直接使用wantParam传输,大于100kb的数据采用分布式对象传输。
\ No newline at end of file
diff --git a/zh-cn/application-dev/ability/stage-ability.md b/zh-cn/application-dev/ability/stage-ability.md
index fc43d7b00c5d1a68fa67c98bd5988c65cb4bb001..061faac68db96402e30ad0cf89b1d1136c9c5660 100644
--- a/zh-cn/application-dev/ability/stage-ability.md
+++ b/zh-cn/application-dev/ability/stage-ability.md
@@ -72,7 +72,7 @@ Ability功能如下(Ability类,具体的API详见[接口文档](../reference
```
4. 实现Ability生命周期接口。
- 在`onWindowStageCreate(windowStage)`中通过loadContent接口设置应用要加载的页面,window接口的使用详见[窗口开发指导](../windowmanager/window-guidelines.md)。
+ 在`onWindowStageCreate(windowStage)`中通过loadContent接口设置应用要加载的页面,window接口的使用详见[窗口开发指导](../windowmanager/application-window-stage.md)。
```ts
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
diff --git a/zh-cn/application-dev/database/database-distributedobject-guidelines.md b/zh-cn/application-dev/database/database-distributedobject-guidelines.md
index dac9fb45126a7f3b3dce8f9ee0cc194ec625ff93..61db857faf49b8f9f3d1adbdd14e1737c63712bc 100644
--- a/zh-cn/application-dev/database/database-distributedobject-guidelines.md
+++ b/zh-cn/application-dev/database/database-distributedobject-guidelines.md
@@ -128,16 +128,16 @@
以下为加入同步组网的代码示例:
```js
- //发起方
+ // 发起方
var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true,
- parent:{mother:"jack mom",father:"jack Dad"},list:[{mother:"jack mom"}, {father:"jack Dad"}]});
+ parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]});
local_object.setSessionId(sessionId);
- //被拉起方
+ // 被拉起方
var remote_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true,
parent:undefined, list:undefined});
remote_object.setSessionId(sessionId);
- //收到status上线后remote_object同步数据,即name变成jack,age是18
+ // 收到status上线后remote_object同步数据,即name变成jack,age是18
```
5. 监听对象数据变更。可监听对端数据的变更,以callback作为变更回调实例。
@@ -166,16 +166,16 @@
local_object.name = "jack";
local_object.age = 19;
local_object.isVis = false;
- local_object.parent = {mother:"jack mom",father:"jack Dad"};
+ local_object.parent = {mother:"jack mom", father:"jack Dad"};
local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}];
```
>  **说明:**
> 针对复杂类型的数据修改,目前支持对根属性的修改,暂不支持对下级属性的修改。示例如下:
```js
- //支持的修改方式
+ // 支持的修改方式
local_object.parent = {mother:"mom", father:"dad"};
- //不支持的修改方式
+ // 不支持的修改方式
local_object.parent.mother = "mom";
```
@@ -189,9 +189,9 @@
以下为取消监听数据变更的代码示例:
```js
- //删除变更回调changeCallback
+ // 删除变更回调changeCallback
local_object.off("change", changeCallback);
- //删除所有的变更回调
+ // 删除所有的变更回调
local_object.off("change");
```
9. 监听分布式对象的上下线。可以监听对端分布式数据对象的上下线。
@@ -210,14 +210,14 @@
```js
// 保存数据对象
- local_object.save("local", (result, data)=>{
+ local_object.save("local", (result, data) => {
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// 撤回保存的数据对象
- local_object.revokeSave((result, data) =>{
+ local_object.revokeSave((result, data) => {
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
@@ -225,7 +225,7 @@
2.Promise方式
```js
// 保存数据对象
- g_object.save("local").then((result)=>{
+ g_object.save("local").then((result) => {
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
@@ -233,7 +233,7 @@
console.info("save local failed.");
});
// 撤回保存的数据对象
- g_object.revokeSave().then((result)=>{
+ g_object.revokeSave().then((result) => {
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
@@ -243,9 +243,9 @@
以下为取消监听数据变更的代码示例:
```js
- //删除上下线回调statusCallback
+ // 删除上下线回调statusCallback
local_object.off("status", this.statusCallback);
- //删除所有的上下线回调
+ // 删除所有的上下线回调
local_object.off("status");
```
12. 退出同步组网。分布式对象退出组网后,本地的数据变更对端不会同步。
diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md
index 785a513f5bc434892d88b3f75b5f5c2491f07b6b..f4f1d95d0ee94b3b323ebaa17a3148c401bdd8c1 100644
--- a/zh-cn/application-dev/database/database-relational-guidelines.md
+++ b/zh-cn/application-dev/database/database-relational-guidelines.md
@@ -100,7 +100,7 @@
| RdbPredicates | glob(field: string, value: string): RdbPredicates | 配置RdbPredicates匹配数据字段为String的指定字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | 将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。
- field:数据库表中的列名。
- low:指示与谓词匹配的最小值。
- high:指示与谓词匹配的最大值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | 配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。
- field:数据库表中的列名。
- low:指示与谓词匹配的最小值。
- high:指示与谓词匹配的最大值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
-| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | 配置谓词以匹配数据字段为ValueType且值大于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
+| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值大于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为valueType且value小于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 |
@@ -288,9 +288,9 @@
```js
"requestPermissions":
- {
- "name": "ohos.permission.DISTRIBUTED_DATASYNC"
- }
+ {
+ "name": "ohos.permission.DISTRIBUTED_DATASYNC"
+ }
```
(2) 获取应用权限。
@@ -331,7 +331,7 @@
promise.then((result) => {
console.log('sync done.')
for (let i = 0; i < result.length; i++) {
- console.log('device=' + result[i][0] + ' status=' + result[i][1])
+ console.log('device=' + result[i][0] + 'status=' + result[i][1])
}
}).catch((err) => {
console.log('sync failed')
@@ -349,7 +349,7 @@
```js
function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) {
- console.log('device=' + device[i] + ' data changed')
+ console.log('device=' + device[i] + 'data changed')
}
}
try {
@@ -382,17 +382,17 @@
```js
let promiseBackup = rdbStore.backup("dbBackup.db")
- promiseBackup.then(()=>{
+ promiseBackup.then(() => {
console.info('Backup success.')
- }).catch((err)=>{
+ }).catch((err) => {
console.info('Backup failed, err: ' + err)
})
```
```js
let promiseRestore = rdbStore.restore("dbBackup.db")
- promiseRestore.then(()=>{
+ promiseRestore.then(() => {
console.info('Restore success.')
- }).catch((err)=>{
+ }).catch((err) => {
console.info('Restore failed, err: ' + err)
})
```
diff --git a/zh-cn/application-dev/device/sensor-guidelines.md b/zh-cn/application-dev/device/sensor-guidelines.md
index 6259723f5680f363646aca21d9341c6a22435622..8ffc74e20dea5ce602b497d67405ed87312ccf87 100644
--- a/zh-cn/application-dev/device/sensor-guidelines.md
+++ b/zh-cn/application-dev/device/sensor-guidelines.md
@@ -87,7 +87,7 @@
```
import sensor from "@ohos.sensor"
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){
- console.info("Subscription succeeded. data = " + data);//调用成功,打印对应传感器的数据
+ console.info("Subscription succeeded. data = " + data);// 调用成功,打印对应传感器的数据
}
);
```
@@ -101,7 +101,7 @@
```
import sensor from "@ohos.sensor"
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() {
- console.info("Succeeded in unsubscribing from acceleration sensor data.");//注销成功,返回打印结果
+ console.info("Succeeded in unsubscribing from acceleration sensor data.");// 注销成功,返回打印结果
}
);
```
@@ -115,7 +115,7 @@
```
import sensor from "@ohos.sensor"
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
- console.info("Data obtained successfully. data=" + data);//获取数据成功,打印对应传感器的数据
+ console.info("Data obtained successfully. data=" + data);// 获取数据成功,打印对应传感器的数据
}
);
```
@@ -129,7 +129,7 @@
```
try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
- console.info("Data obtained successfully. data=" + data);//获取数据成功,打印对应传感器的数据
+ console.info("Data obtained successfully. data=" + data);// 获取数据成功,打印对应传感器的数据
});
} catch (error) {
console.error(error);
diff --git a/zh-cn/application-dev/media/audio-interruptmode.md b/zh-cn/application-dev/media/audio-interruptmode.md
index 6bd6386ab04a6f2894df3e4619b780e8078e4a5a..897fa18ec4091959fc8883d637d53f14c7b9e8b8 100644
--- a/zh-cn/application-dev/media/audio-interruptmode.md
+++ b/zh-cn/application-dev/media/audio-interruptmode.md
@@ -48,7 +48,7 @@
```js
var mode_ = audio.InterruptMode.SHARE_MODE;
- await this.audioRenderer.setInterruptMode(mode_).then(()=>{
+ await this.audioRenderer.setInterruptMode(mode_).then(() => {
console.log('[JSAR] [SetInterruptMode] 设置: ' + (mode_ == 0 ? "共享模式":"独立焦点模式") + "成功" );
});
```
diff --git a/zh-cn/application-dev/media/audio-playback.md b/zh-cn/application-dev/media/audio-playback.md
index d5fb8cf6df69f69998a10337f57437f0d2f33947..6313ac85397e94b8e26c955ff647fc2d5c6208f3 100644
--- a/zh-cn/application-dev/media/audio-playback.md
+++ b/zh-cn/application-dev/media/audio-playback.md
@@ -193,12 +193,12 @@ export class AudioDemo {
}).catch((err) => {
console.info('open fd failed err is' + err);
});
- audioPlayer.src = nextFdPath; //设置src属性,并重新触发触发'dataLoad'事件回调
+ audioPlayer.src = nextFdPath; // 设置src属性,并重新触发触发'dataLoad'事件回调
}
async audioPlayerDemo() {
- let audioPlayer = media.createAudioPlayer(); //创建一个音频播放实例
- this.setCallBack(audioPlayer); //设置事件回调
+ let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例
+ this.setCallBack(audioPlayer); // 设置事件回调
let fdPath = 'fd://'
// path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" 命令,将其推送到设备上
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
@@ -210,7 +210,7 @@ export class AudioDemo {
}).catch((err) => {
console.info('open fd failed err is' + err);
});
- audioPlayer.src = fdPath; //设置src属性,并触发'dataLoad'事件回调
+ audioPlayer.src = fdPath; // 设置src属性,并触发'dataLoad'事件回调
}
}
```
diff --git a/zh-cn/application-dev/media/opensles-playback.md b/zh-cn/application-dev/media/opensles-playback.md
index 3f3b891f824fc15004f8a8f1e0d6150f3d765875..66e90957f3fe127f53714bf6615bb4f85541b61a 100644
--- a/zh-cn/application-dev/media/opensles-playback.md
+++ b/zh-cn/application-dev/media/opensles-playback.md
@@ -39,7 +39,7 @@
0
};
- //具体参数需要根据音频文件格式进行适配
+ // 具体参数需要根据音频文件格式进行适配
SLDataFormat_PCM pcmFormat = {
SL_DATAFORMAT_PCM,
2,
@@ -82,7 +82,7 @@
return;
}
- //wavFile_ 需要设置为用户想要播放的文件描述符
+ // wavFile_ 需要设置为用户想要播放的文件描述符
wavFile_ = fopen(path, "rb");
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
```
diff --git a/zh-cn/application-dev/notification/common-event.md b/zh-cn/application-dev/notification/common-event.md
index f3fc6028caf819da2ffae07934fc66232ae8166b..fd6f6a31e73ae42d5ed52c2f2196d22801ffb5f6 100644
--- a/zh-cn/application-dev/notification/common-event.md
+++ b/zh-cn/application-dev/notification/common-event.md
@@ -98,11 +98,11 @@ import commonEvent from '@ohos.commonEvent';
```js
//发布公共事件
commonEvent.publish("event", (err) => {
- if (err.code) {
- console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
- } else {
- console.info("[CommonEvent]Publish1")
- }
+ if (err.code) {
+ console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
+ } else {
+ console.info("[CommonEvent]Publish1")
+ }
})
```
@@ -118,8 +118,8 @@ import commonEvent from '@ohos.commonEvent'
```js
//公共事件相关信息
var options = {
- code: 1, //公共事件的初始代码
- data: "initial data",//公共事件的初始数据
+ code: 1, //公共事件的初始代码
+ data: "initial data",//公共事件的初始数据
}
```
@@ -128,11 +128,11 @@ var options = {
```js
//发布公共事件
commonEvent.publish("event", options, (err) => {
- if (err.code) {
- console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
- } else {
- console.info("[CommonEvent]Publish2")
- }
+ if (err.code) {
+ console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
+ } else {
+ console.info("[CommonEvent]Publish2")
+ }
})
```
diff --git a/zh-cn/application-dev/quick-start/package-structure.md b/zh-cn/application-dev/quick-start/package-structure.md
index 6345a071e3ec1d01af0169dcc9ab1de1567f3cf3..fab0b688c882f775baca2f5675fbab106a1db7db 100644
--- a/zh-cn/application-dev/quick-start/package-structure.md
+++ b/zh-cn/application-dev/quick-start/package-structure.md
@@ -505,6 +505,7 @@ skills示例:
| name | 需要使用的权限名称。 | 字符串 | 否 |
| reason | 描述申请权限的原因。不能超过256个字节。需要做多语种适配。 | 字符串 | 分情况:当申请的权限为user_grant时,必须填写此字段,否则不允许在应用市场上架;其它权限可缺省,缺省为空 |
| usedScene | 描述权限使用的场景和时机。场景类型有:ability、when。ability:ability的名称,可配置多个。when:调用时机,可填的值有inuse(使用时)、always(始终) | 对象 | ability分情况:申请的权限有user_grant时,ability必填;没有user_grant时可缺省,缺省值为空。when可缺省,缺省值为“inuse” |
+具体示例可参考[访问控制开发指导](../security/accesstoken-guidelines.md#fa模型)。
表22 js对象的内部结构说明
diff --git a/zh-cn/application-dev/quick-start/stage-structure.md b/zh-cn/application-dev/quick-start/stage-structure.md
index fa20a6d5d3cf8cbef28290a52b06576796e7fa9c..808ab2b55571653ca795e7f37379ad2821828e8a 100644
--- a/zh-cn/application-dev/quick-start/stage-structure.md
+++ b/zh-cn/application-dev/quick-start/stage-structure.md
@@ -507,6 +507,7 @@ requestPermissions示例 :
}
}
```
+权限访问的更多说明,可参考[访问控制开发指导](../security/accesstoken-guidelines.md)
#### form对象内部结构
diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md
index dd960f8294fa7b03b3183bedb0431e73dfc29809..cd16f889508f3adcefabc621304527d06c1a2b88 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md
@@ -2,7 +2,8 @@
本模块提供内部包的管理
->  **说明:**
+> **说明:**
+>
> 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
@@ -48,7 +49,7 @@ SystemCapability.BundleManager.BundleFramework
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
| bundleName | string | 是 | 要查询的应用程序包名称。 |
| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
-| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回程序信息。 |
+| callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回程序信息。 |
@@ -81,7 +82,7 @@ SystemCapability.BundleManager.BundleFramework
| 类型 | 说明 |
| ------------------------------------------------------------ | ------------------------- |
-| Promise\<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)> | Promise形式返回程序信息。 |
+| Promise\> | Promise形式返回程序信息。 |
## innerBundleManager.on
@@ -107,7 +108,7 @@ SystemCapability.BundleManager.BundleFramework
| -------------------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | 是 | 指示应执行命令。 |
| bundleStatusCallback | BundleStatusCallback | 是 | 指示要注册的回调。 |
-| callback | AsyncCallback | 是 | 程序启动作为入参的回调函数,返回正确结果或错误信息。 |
+| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回正确结果或错误信息。 |
## innerBundleManager.on
@@ -138,7 +139,7 @@ SystemCapability.BundleManager.BundleFramework
| 类型 | 说明 |
| --------------- | ----------------------------------- |
-| Promise | Promise形式返回正确结果或错误信息。 |
+| Promise\ | Promise形式返回正确结果或错误信息。 |
## innerBundleManager.off
@@ -163,7 +164,7 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 |
| -------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | 是 | 指示应执行命令。 |
-| callback | AsyncCallback | 是 | 程序启动作为入参的回调函数,返回正确结果或错误信息。 |
+| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回正确结果或错误信息。 |
## innerBundleManager.off
@@ -193,13 +194,13 @@ SystemCapability.BundleManager.BundleFramework
| 类型 | 说明 |
| --------------- | ----------------------------------- |
-| Promise | Promise形式返回正确结果或错误信息。 |
+| Promise\ | Promise形式返回正确结果或错误信息。 |
## innerBundleManager.getAllLauncherAbilityInfos
getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void;
-以异步方法根据给定的包名获取所有的LauncherAbilityInfos,使用callback形式返回结果。
+以异步方法获取所有的LauncherAbilityInfos,使用callback形式返回结果。
**需要权限:**
@@ -218,13 +219,13 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
-| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回程序信息。 |
+| callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回程序信息。 |
## innerBundleManager.getAllLauncherAbilityInfos
getAllLauncherAbilityInfos(userId: number) : Promise<Array<LauncherAbilityInfo>>
-以异步方法根据给定的包名获取LauncherAbilityInfos,使用Promise形式返回结果。
+以异步方法获取LauncherAbilityInfos,使用Promise形式返回结果。
**需要权限:**
@@ -248,7 +249,7 @@ SystemCapability.BundleManager.BundleFramework
| 类型 | 说明 |
| ------------------------------------------------------------ | ------------------------- |
-| Promise\<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)> | Promise形式返回程序信息。 |
+| Promise\> | Promise形式返回程序信息。 |
## innerBundleManager.getShortcutInfos
@@ -273,7 +274,7 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 |
| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- |
| bundleName | string | 是 | 要查询的应用程序包名称。 |
-| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回快捷方式信息。 |
+| callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回快捷方式信息。 |
## innerBundleManager.getShortcutInfos
@@ -303,5 +304,5 @@ SystemCapability.BundleManager.BundleFramework
| 类型 | 说明 |
| -------------------------------------------------------- | ----------------------------- |
-| Promise\<[ShortcutInfo](js-apis-bundle-ShortcutInfo.md)> | Promise形式返回快捷方式信息。 |
+| Promise\> | Promise形式返回快捷方式信息。 |
diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md
index 4d56ae1f358889500fcc3787560a3dc8eeea27b3..a32fdcc7d7e01ff4e05ce885ec2cdfeee288c6dc 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md
@@ -1,8 +1,9 @@
# distributedBundle模块(JS端SDK接口)
-本模块提供内部包的管理
+本模块提供分布式包的管理
->  **说明:**
+> **说明:**
+>
> 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
@@ -27,7 +28,7 @@ SystemCapability.BundleManager.DistributedBundleFramework
getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void;
-以异步方法根据给定的包名获取有关远程设备AbilityInfo信息,使用callback形式返回结果。
+以异步方法根据给定的ElementName获取有关远程设备AbilityInfo信息,使用callback形式返回结果。
**需要权限:**
@@ -54,7 +55,7 @@ SystemCapability.BundleManager.DistributedBundleFramework
getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo>
-以异步方法根据给定的包名获取有关远程设备AbilityInfo信息,使用Promise形式返回结果。
+以异步方法根据给定的ElementName获取有关远程设备AbilityInfo信息,使用Promise形式返回结果。
**需要权限:**
@@ -84,7 +85,7 @@ SystemCapability.BundleManager.DistributedBundleFramework
getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void;
-以异步方法根据给定的包名获取有关远程设备AbilityInfos信息,使用callback形式返回结果。
+以异步方法根据给定的ElementName获取有关远程设备AbilityInfos信息,使用callback形式返回结果。
**需要权限:**
@@ -111,7 +112,7 @@ SystemCapability.BundleManager.DistributedBundleFramework
getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>>
-以异步方法根据给定的包名获取有关远程设备AbilityInfo信息,使用Promise形式返回结果。
+以异步方法根据给定的ElementName获取有关远程设备AbilityInfos信息,使用Promise形式返回结果。
**需要权限:**
@@ -129,7 +130,7 @@ SystemCapability.BundleManager.DistributedBundleFramework
| 名称 | 类型 | 必填 | 描述 |
| ------------ | --------------------------------------------------- | ---- | ----------------------- |
-| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | 是 | 获得的ElementName信息。 |
+| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | 是 | ElementName信息,最大数组长度为10。 |
**返回值:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md
index ce4e117c246682340b6c063ffaf33fe5b80755be..a6f72ea31f0587717e76cdee65fd91273c0d0b56 100755
--- a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md
@@ -12,10 +12,6 @@
import bundle from '@ohos.bundle';
```
-## 系统能力
-
-SystemCapability.BundleManager.BundleFramework
-
## 权限列表
| 权限 | 权限等级 | 描述 |
@@ -536,7 +532,7 @@ SystemCapability.BundleManager.BundleFramework
## bundle.setAbilityEnabled8+
-setApplicationEnabled(bundleName: string, isEnable: boolean, callback: AsyncCallback<void>): void;
+setAbilityEnabled(info: AbilityInfo, isEnable: boolean, callback: AsyncCallback<void>): void;
设置是否启用指定的功能
@@ -1510,7 +1506,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId)
queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void
-以异步方法根据给定的意图获取获取指定用户下Ability信息,使用callback形式返回结果。
+以异步方法根据给定的意图获取指定用户下Ability信息,使用callback形式返回结果。
**需要权限:**
@@ -1897,8 +1893,8 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 |
| -------------- | ------ | ---- | ---------------------------------------- |
| want | [Want](js-apis-application-Want.md) | 是 | 包含要查询的应用程序包名称的意图。 |
-| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#ExtensionAbilityType9) |
-| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#ExtensionFlag9) |
+| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#extensionabilitytype9) |
+| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#extensionflag9) |
| userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0 |
**返回值:**
@@ -1946,8 +1942,8 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 |
| -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-Want.md) | 是 | 指示包含要查询的应用程序包名称的意图。 |
-| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#ExtensionAbilityType9) |
-| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#ExtensionFlag9)|
+| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#extensionabilitytype9) |
+| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#extensionflag9)|
| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0 |
| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回ExtensionAbility信息。 |
@@ -1989,8 +1985,8 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 |
| -------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| want | [Want](js-apis-application-Want.md) | 是 | 指示包含要查询的应用程序包名称的意图。 |
-| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#ExtensionAbilityType9) |
-| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#ExtensionFlag9) |
+| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#extensionabilitytype9) |
+| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#extensionflag9) |
| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回ExtensionAbility信息。 |
**示例:**
@@ -2147,7 +2143,7 @@ bundle.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataNa
setDisposedStatus(bundleName: string, status: number, callback: AsyncCallback\): void;
-此接口为系统接口,以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用callback形式返回结果。
+以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用callback形式返回结果。
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
@@ -2179,7 +2175,7 @@ bundle.setDisposedStatus(bundleName, status, caller)
setDisposedStatus(bundleName: string, status: number): Promise\;
-此接口为系统接口,以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用Promise形式返回结果。
+以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用Promise形式返回结果。
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
@@ -2217,6 +2213,8 @@ bundle.setDisposedStatus(bundleName, status).then(data=>{
getDisposedStatus(bundleName: string, callback: AsyncCallback\): void;
+以异步方法根据给定的bundleName来获取对应应用的处置状态,使用callback形式返回结果。
+
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
**系统能力:** SystemCapability.BundleManager.BundleFramework
@@ -2245,7 +2243,7 @@ bundle.getDisposedStatus(bundleName, caller)
getDisposedStatus(bundleName: string): Promise\;
-此接口为系统接口,以异步方法根据给定的bundleName来获取对应应用的处置状态,使用Promise形式返回结果。
+以异步方法根据给定的bundleName来获取对应应用的处置状态,使用Promise形式返回结果。
**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md
index db88c9d3067846b7135fa205633522c4c7277470..f834060bd898647d06fc810281923bde08a42fd7 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md
@@ -248,7 +248,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数,返回Ability结果。 |
**示例:**
@@ -284,7 +284,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
@@ -323,7 +323,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**返回值:**
@@ -431,7 +431,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -465,7 +465,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
**示例:**
@@ -564,7 +564,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -598,7 +598,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\<
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
**示例:**
@@ -786,7 +786,7 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | 否 | 远端对象实例。 |
**返回值:**
@@ -930,7 +930,7 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\<
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
**示例:**
@@ -965,7 +965,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。|
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 |
@@ -1004,7 +1004,7 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions):
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 |
-| accountId | number | 是 | 需要启动的accountId。 |
+| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 |
| options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 |
**示例:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md
index 3c585bdd09536059377027115a5c85e561674196..4d3076f97c57dd54f485927a5cef3ca0ad6d4de2 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md
@@ -20,11 +20,13 @@ var args = AbilityDelegatorRegistry.getArguments();
测试参数信息
+**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
+
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ |
-| bundleName | string | 是 | 是 | 当前被测试应用的包名
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| parameters | {[key:string]: string} | 是 | 是 | 当前启动单元测试的参数
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| testCaseNames | string | 是 | 是 | 测试用例名称
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| testRunnerClassName | string | 是 | 是 | 执行测试用例的测试执行器的名称
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
+| bundleName | string | 是 | 是 | 当前被测试应用的包名 |
+| parameters | {[key:string]: string} | 是 | 是 | 当前启动单元测试的参数 |
+| testCaseNames | string | 是 | 是 | 测试用例名称 |
+| testRunnerClassName | string | 是 | 是 | 执行测试用例的测试执行器的名称 |
diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-abilityMonitor.md b/zh-cn/application-dev/reference/apis/js-apis-application-abilityMonitor.md
index df6b0968eef4ed2d6026faf4872d04b3890fa49c..64ffa05699b2148d5440938e8c9d6001005cfd12 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-application-abilityMonitor.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-application-abilityMonitor.md
@@ -33,15 +33,17 @@ abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
Ability监听器
+系统能力:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
+
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ |
| abilityName | string | 是 | 是 | 当前AbilityMonitor绑定的ability名称
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| onAbilityCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability被启动初始化时的回调函数
不设置该属性则不能收到该生命周期回调
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| onAbilityForeground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability状态变成前台时的回调函数
不设置该属性则不能收到该生命周期回调
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| onAbilityBackground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability状态变成后台时的回调函数
不设置该属性则不能收到该生命周期回调
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| onAbilityDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability被销毁前的回调函数
不设置该属性则不能收到该生命周期回调
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| onWindowStageCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | window stage被创建时的回调函数
不设置该属性则不能收到该生命周期回调
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| onWindowStageRestore?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | window stage被重载时的回调函数
不设置该属性则不能收到该生命周期回调
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| onWindowStageDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | window stage被销毁前的回调函数
不设置该属性则不能收到该生命周期回调
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
+| onAbilityCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability被启动初始化时的回调函数
不设置该属性则不能收到该生命周期回调 |
+| onAbilityForeground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability状态变成前台时的回调函数
不设置该属性则不能收到该生命周期回调 |
+| onAbilityBackground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability状态变成后台时的回调函数
不设置该属性则不能收到该生命周期回调 |
+| onAbilityDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | ability被销毁前的回调函数
不设置该属性则不能收到该生命周期回调
|
+| onWindowStageCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | window stage被创建时的回调函数
不设置该属性则不能收到该生命周期回调
|
+| onWindowStageRestore?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | window stage被重载时的回调函数
不设置该属性则不能收到该生命周期回调
|
+| onWindowStageDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | 是 | 是 | window stage被销毁前的回调函数
不设置该属性则不能收到该生命周期回调
|
diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md b/zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md
index 91a467c2e41ffbe9e3d062249cf264025bb39894..7705d4bd7c71ddb7ae42fd1ce52e838849a4b8fb 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md
@@ -28,7 +28,7 @@ registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number**
| 参数名 | 类型 | 必填 | 说明 |
| ------------------------ | -------- | ---- | ------------------------------ |
-| [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | callback | 是 | 回调方法,返回注册监听事件的ID。 |
+| callback | [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | 是 | 回调方法,返回注册监听事件的ID。 |
**返回值:**
@@ -98,7 +98,7 @@ unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallb
| 参数名 | 类型 | 必填 | 说明 |
| ------------- | -------- | ---- | -------------------------- |
| callbackId | number | 是 | 注册监听应用内生命周期的ID。 |
-| AsyncCallback | callback | 是 | 回调方法。 |
+| callback | AsyncCallback\ | 是 | 回调方法。 |
**示例:**
@@ -123,7 +123,7 @@ registerEnvironmentCallback(callback: EnvironmentCallback): **number**;
| 参数名 | 类型 | 必填 | 说明 |
| ------------------------ | -------- | ---- | ------------------------------ |
-| [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | callback | 是 | 回调方法,返回注册监听事件的ID。 |
+| callback | [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | 是 | 回调方法,返回注册监听事件的ID。 |
**返回值:**
@@ -175,7 +175,7 @@ unregisterEnvironmentCallback(callbackId: **number**, callback: AsyncCallback<*
| 参数名 | 类型 | 必填 | 说明 |
| ------------- | -------- | ---- | -------------------------- |
| callbackId | number | 是 | 注册监听系统环境变化的ID。 |
-| AsyncCallback | callback | 是 | 回调方法。 |
+| callback | AsyncCallback\ | 是 | 回调方法。 |
**示例:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-context.md b/zh-cn/application-dev/reference/apis/js-apis-application-context.md
index bcb6005cd25490b112d3f50de4382e498851a08b..b8f385ca6ed186b99659199e936c60975e6263d7 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-application-context.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-application-context.md
@@ -7,8 +7,6 @@ Context模块提供开发者运行代码的上下文环境的能力,包括查
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口仅可在Stage模型下使用。
-提供开发者运行代码的上下文环境,包括应用信息、ResourceManager等信息。
-
## 使用说明
通过AbilityContext等继承实现。
diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md b/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md
index ae8f7c42862086343031cddbc6fb0a81ccee88d7..2c9f76234fb7eec46f45e2faf3d09f2bf980b7ae 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md
@@ -30,5 +30,5 @@ Shell命令执行结果
| 名称 | 类型 | 可读 | 可写 | 说明 |
| --------- | ------ | ---- | ---- | ------------------------------------------------------------ |
-| stdResult | string | 是 | 是 | 标准输出内容
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
-| exitCode | number | 是 | 是 | 结果码
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core |
+| stdResult | string | 是 | 是 | 标准输出内容 |
+| exitCode | number | 是 | 是 | 结果码 |
diff --git a/zh-cn/application-dev/reference/apis/js-apis-appmanager.md b/zh-cn/application-dev/reference/apis/js-apis-appmanager.md
index c23fba3ad41639ac832219c4001dc34c8f699395..f4ac20aea83ca20d982eef78c375949a77094f3f 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-appmanager.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-appmanager.md
@@ -210,7 +210,7 @@ getProcessRunningInfos(callback: AsyncCallback\>): vo
registerApplicationStateObserver(observer: ApplicationStateObserver): number;
-注册应用程序状态观测器。
+注册全部应用程序状态观测器。
**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
@@ -244,6 +244,48 @@ registerApplicationStateObserver(observer: ApplicationStateObserver): number;
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
+ ```
+
+## appManager.registerApplicationStateObserver9+
+
+registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array): number;
+
+注册指定应用程序状态观测器。
+
+**需要权限**:ohos.permission.RUNNING_STATE_OBSERVER
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
+
+**系统API**:该接口为系统接口,三方应用不支持调用。
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | -------- | -------- | -------- |
+| observer | ApplicationStateObserver | 否 | 返回观察者的数字代码。 |
+| bundleNameList | Array