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. ![](figures/1.png) **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). + +![image-20220613161049897](figures/en-us_image_0000001655128646.png) + + + + +## 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. + +![](figures/en-us_image_0000001655128939.png) + +![image-20220613160524053](figures/en-us_image_0000001655128998.png) + + +## 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**. + + ![image-20220613220702504](figures/en-us_image_0000001655129232.png) + + 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` + + ![image-20220613165018184](figures/en-us_image_0000001655129264.png) + + 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. + + ![image-20220613161352157](figures/en-us_image_0000001655129041.png) + + 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**. + + ![image-20220613165018184](figures/en-us_image_0000001655129398.png) + + 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. + + ![image-20220613171111405](figures/en-us_image_0000001655129333.png) + + + + c. Check for system APIs. + + ![image-20220613213038104](figures/en-us_image_0000001655129372.png) 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. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 } ``` - ![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png) +![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png) 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 ![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png) 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) + } } } - } - ``` + ``` ![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png) ​ -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 ![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png) -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 ![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png) -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 ![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png) -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 ![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png) -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.| | +![how-distributedobject-works](figures/how-distributedobject-works.png) + + +### 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. - -![](../public_sys-resources/icon-note.gif)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. +![](../public_sys-resources/icon-note.gif)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 -![](figures/spi-controller-device-connection.png "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. - - ->![](../public_sys-resources/icon-note.gif) **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.

-
- ->![](../public_sys-resources/icon-note.gif) **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 -![](figures/using-SPI-process.png "process-of-using-an-spi-device") - -### 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 + + ![image](figures/spi-controller-device-connection.png) + +- 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. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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.| + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 + + ![](figures/using-SPI-process.png) + + +### 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 -![](figures/independent-service-mode.png "SPI-independent-service-mode") + **Figure 1** Independent service mode -## Available APIs + ![image](figures/independent-service-mode.png) + +## **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. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **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.

-
- ->![](../public_sys-resources/icon-note.gif) **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 -![](figures/using-watchdog-process.png "process-of-using-a-watchdog") - -### 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.| + +> ![](../public_sys-resources/icon-note.gif) **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 + +![image](figures/using-watchdog-process.png) + + +### 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 -![](figures/independent-service-mode.png "independent-service-mode-15") +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 + + ![image](figures/independent-service-mode.png "Watchdog 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. + + + > ![](../public_sys-resources/icon-note.gif) **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. ->![](../public_sys-resources/icon-note.gif) **NOTE** +2. Call the clock conversion and statistics APIs. + +>![](../public_sys-resources/icon-note.gif) **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. + +>![](../public_sys-resources/icon-note.gif) **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. ->![](../public_sys-resources/icon-note.gif) **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 -![](figures/task-state-transitions.png "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
+ + ![](figures/task-state-transitions.png "task-state-transitions") + +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. - ->![](../public_sys-resources/icon-note.gif) **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. + +>![](../public_sys-resources/icon-note.gif) **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 + + ![](figures/liteos-m-kernel-dynamic-loading-architecture.png "liteos-m-kernel-dynamic-loading-architecture") -**Figure 1** LiteOS-M kernel dynamic loading architecture -![](figures/liteos-m-kernel-dynamic-loading-architecture.png "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 -![](figures/exported-symbol-table-information.png "exported-symbol-table-information") + **Figure 2** Exported symbol table + + ![](figures/exported-symbol-table-information.png "exported-symbol-table-information") + ### 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 -![](figures/process-of-loading-an-elf-file.png "process-of-loading-an-elf-file") + **Figure 3** Process of loading an ELF file
+ ![](figures/process-of-loading-an-elf-file.png "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 -![](figures/elf-file-linking-process.png "elf-file-linking-process") + **Figure 4** ELF file linking process + + ![](figures/elf-file-linking-process.png "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 ->![](../public_sys-resources/icon-note.gif) **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. +> ![](public_sys-resources/icon-note.gif) **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 ``` ->![](../public_sys-resources/icon-note.gif) **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. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 -![](figures/kernel-architecture.png "kernel-architecture") + ![](figures/kernel-architecture.png "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 -![](figures/kernel-startup-process.png "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
+ ![](figures/kernel-startup-process.png "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. - ->![](../public_sys-resources/icon-note.gif) **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. + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 -![](figures/mapping-between-the-virtual-and-physical-memory-addresses.png "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
+ + ![](figures/mapping-between-the-virtual-and-physical-memory-addresses.png "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. ->![](../public_sys-resources/icon-note.gif) **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. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. ->![](../public_sys-resources/icon-note.gif) **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. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **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); ``` ->![](../public_sys-resources/icon-note.gif) **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. - +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. ->![](../public_sys-resources/icon-note.gif) **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. ->![](../public_sys-resources/icon-note.gif) **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. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + + > ![](public_sys-resources/icon-note.gif) **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") ``` - ->![](../public_sys-resources/icon-caution.gif) **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. - +> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **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. - >![](../public_sys-resources/icon-note.gif) **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) + ``` + ![icon-note.gif](../public_sys-resources/icon-note.gif) 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. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. ->![](../public_sys-resources/icon-note.gif) **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!". - - ->![](../public_sys-resources/icon-notice.gif) **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!". + + > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **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. - - >![](../public_sys-resources/icon-notice.gif) **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. + > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **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 ![](figures/kernel-small-mode-process-4.png) -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. - ``` - - >![](../public_sys-resources/icon-note.gif) **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. + ``` + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **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\)**. - ->![](../public_sys-resources/icon-note.gif) **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**. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 -![](figures/kernel-startup-process-2.png "kernel-startup-process-2") - -**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
+ ![](figures/kernel-startup-process-2.png "kernel-startup-process-2") + + + **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. ->![](../public_sys-resources/icon-note.gif) **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. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. | +>![](../public_sys-resources/icon-note.gif)**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. - - >![](../public_sys-resources/icon-note.gif) **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. + >![](../public_sys-resources/icon-note.gif) **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: > ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **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 + ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + > ![icon-note.gif](public_sys-resources/icon-note.gif) **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}. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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}**. + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **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 } ``` -> ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **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. + > ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **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. - >![](../public_sys-resources/icon-note.gif) **NOTE**
The ACTS build middleware is a static library, which will be linked to the image. + >![](../public_sys-resources/icon-note.gif) **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. - >![](../public_sys-resources/icon-note.gif) **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. + >![](../public_sys-resources/icon-note.gif) **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 - ``` - - ![](figure/en-us_image_0000001119924146.gif) - - - Execute the test cases of a module \(view specific module information in **\\acts\\testcases\\**\). - - ``` - run –l ActsSamgrTest - ``` - - ![](figure/en-us_image_0000001166643927.jpg) - - Wait until the test cases are complete. - + ``` + run acts + ``` + + ![](figure/en-us_image_0000001119924146.gif) + + - Execute the test cases of a module \(view specific module information in **\acts\testcases\**). + + ``` + run –l ActsSamgrTest + ``` + + ![](figure/en-us_image_0000001166643927.jpg) + + 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 @@ ![continuation_dev](figures/continuation-info.png) -迁移实际上是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"}]; ``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 针对复杂类型的数据修改,目前支持对根属性的修改,暂不支持对下级属性的修改。示例如下: ```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 @@ 本模块提供内部包的管理 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** +> > 本模块首批接口从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接口) -本模块提供内部包的管理 +本模块提供分布式包的管理 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** +> > 本模块首批接口从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 | 否 | 表示需要注册监听的bundleName数组。最大值128。 | + +**示例:** + + ```js + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + } + } + var bundleNameList = ['bundleName1', 'bundleName2']; + const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); + console.log('-------- observerCode: ---------', observerCode); + ``` ## appManager.unregisterApplicationStateObserver8+ @@ -393,7 +435,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | bundleName | string | 是 | 应用包名。 | - | accountId | number | 是 | account的Id。 | + | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | **示例:** @@ -427,7 +469,7 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | bundleName | string | 是 | 应用包名。 | - | accountId | number | 是 | account的Id。 | + | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 切断account进程的回调函数。 | **示例:** @@ -694,7 +736,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | | bundleName8+ | 只读 | string | 否 | 包名。 | | uid8+ | 只读 | number | 否 | 用户ID。 | -| state8+ | 只读 | number | 否 | 进程信息。 | +| state8+ | 只读 | number | 否 | 应用状态。 | ## AbilityStateData @@ -708,7 +750,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | bundleName8+ | string | 是 | 否 | 应用包名。 | | abilityName8+ | string | 是 | 否 | Ability名称。 | | uid8+ | number | 是 | 否 | 用户ID。 | -| state8+ | number | 是 | 否 | 应用程序信息。 | +| state8+ | number | 是 | 否 | Ability状态。 | | moduleName9+ | string | 是 | 否 | Ability所属的HAP包的名称。 | | abilityType8+ | string | 是 | 否 | 能力类型、页面或服务等。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 2243e9fd02bd700c8e91001293027337eec10e02..629852dd284f0b709670230b0abbf2beb1c2b6c7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -95,7 +95,7 @@ audio.createAudioRenderer(audioRendererOptions,(err, data) => { if (err) { console.error(`AudioRenderer Created: Error: ${err.message}`); } else { - console.info('AudioRenderer Created: Success: SUCCESS'); + console.info(`AudioRenderer Created: Success: SUCCESS`); let audioRenderer = data; } }); @@ -147,9 +147,9 @@ var audioRendererOptions = { var audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); + console.info(`AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS`); }).catch((err) => { - console.info('AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ' + err.message); + console.info(`AudioFrameworkRenderLog: AudioRenderer Created : ERROR :` + err.message); }); ``` @@ -193,7 +193,7 @@ audio.createAudioCapturer(audioCapturerOptions, (err, data) => { if (err) { console.error(`AudioCapturer Created : Error: ${err.message}`); } else { - console.info('AudioCapturer Created : Success : SUCCESS'); + console.info(`AudioCapturer Created : Success : SUCCESS`); let audioCapturer = data; } }); @@ -244,9 +244,9 @@ var audioCapturerOptions = { var audioCapturer; audio.createAudioCapturer(audioCapturerOptions).then((data) => { audioCapturer = data; - console.info('AudioCapturer Created : Success : Stream Type: SUCCESS'); + console.info(`AudioCapturer Created : Success : Stream Type: SUCCESS`); }).catch((err) => { - console.info('AudioCapturer Created : ERROR : ' + err.message); + console.info(`AudioCapturer Created : ERROR : ` + err.message); }); ``` @@ -619,8 +619,8 @@ audio.createAudioCapturer(audioCapturerOptions).then((data) => { | 名称 | 类型 | 必填 | 说明 | | :---------------- | :------------------------------------------------ | :--- | :----------------- | -| type | [DeviceChangeType](#DeviceChangeType) | 是 | 设备连接状态变化。 | -| deviceDescriptors | [AudioDeviceDescriptors](#AudioDeviceDescriptors) | 是 | 设备信息。 | +| type | [DeviceChangeType](#devicechangetype) | 是 | 设备连接状态变化。 | +| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | 是 | 设备信息。 | ## DeviceChangeType @@ -718,10 +718,10 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l ``` audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { if (err) { - console.error('Failed to set the volume. ${err.message}'); + console.error(`Failed to set the volume. ${err.message}`); return; } - console.log('Callback invoked to indicate a successful volume setting.'); + console.log(`Callback invoked to indicate a successful volume setting.`); }); ``` @@ -752,7 +752,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> ``` audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.log('Promise returned to indicate a successful volume setting.'); + console.log(`Promise returned to indicate a successful volume setting.`); }); ``` @@ -776,10 +776,10 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): v ``` audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to obtain the volume. ${err.message}'); + console.error(`Failed to obtain the volume. ${err.message}`); return; } - console.log('Callback invoked to indicate that the volume is obtained.'); + console.log(`Callback invoked to indicate that the volume is obtained.`); }); ``` @@ -807,7 +807,7 @@ getVolume(volumeType: AudioVolumeType): Promise<number> ``` audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.log('Promise returned to indicate that the volume is obtained.' + value); + console.log(`Promise returned to indicate that the volume is obtained.` + value); }); ``` @@ -831,10 +831,10 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) ``` audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to obtain the minimum volume. ${err.message}'); + console.error(`Failed to obtain the minimum volume. ${err.message}`); return; } - console.log('Callback invoked to indicate that the minimum volume is obtained.' + value); + console.log(`Callback invoked to indicate that the minimum volume is obtained.` + value); }); ``` @@ -862,7 +862,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise<number> ``` audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.log('Promised returned to indicate that the minimum volume is obtained.' + value); + console.log(`Promised returned to indicate that the minimum volume is obtained.` + value); }); ``` @@ -886,10 +886,10 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) ``` audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to obtain the maximum volume. ${err.message}'); + console.error(`Failed to obtain the maximum volume. ${err.message}`); return; } - console.log('Callback invoked to indicate that the maximum volume is obtained.' + value); + console.log(`Callback invoked to indicate that the maximum volume is obtained.` + value); }); ``` @@ -917,7 +917,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise<number> ``` audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.log('Promised returned to indicate that the maximum volume is obtained.'); + console.log(`Promised returned to indicate that the maximum volume is obtained.`); }); ``` @@ -944,10 +944,10 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void ``` audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { - console.error('Failed to mute the stream. ${err.message}'); + console.error(`Failed to mute the stream. ${err.message}`); return; } - console.log('Callback invoked to indicate that the stream is muted.'); + console.log(`Callback invoked to indicate that the stream is muted.`); }); ``` @@ -979,7 +979,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> ``` audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.log('Promise returned to indicate that the stream is muted.'); + console.log(`Promise returned to indicate that the stream is muted.`); }); ``` @@ -1004,10 +1004,10 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): voi ``` audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to obtain the mute status. ${err.message}'); + console.error(`Failed to obtain the mute status. ${err.message}`); return; } - console.log('Callback invoked to indicate that the mute status of the stream is obtained.' + value); + console.log(`Callback invoked to indicate that the mute status of the stream is obtained.` + value); }); ``` @@ -1036,7 +1036,7 @@ isMute(volumeType: AudioVolumeType): Promise<boolean> ``` audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.log('Promise returned to indicate that the mute status of the stream is obtained.' + value); + console.log(`Promise returned to indicate that the mute status of the stream is obtained.` + value); }); ``` @@ -1060,10 +1060,10 @@ isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): v ``` audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to obtain the active status of the stream. ${err.message}'); + console.error(`Failed to obtain the active status of the stream. ${err.message}`); return; } - console.log('Callback invoked to indicate that the active status of the stream is obtained.' + value); + console.log(`Callback invoked to indicate that the active status of the stream is obtained.` + value); }); ``` @@ -1091,7 +1091,7 @@ isActive(volumeType: AudioVolumeType): Promise<boolean> ``` audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.log('Promise returned to indicate that the active status of the stream is obtained.' + value); + console.log(`Promise returned to indicate that the active status of the stream is obtained.` + value); }); ``` @@ -1117,10 +1117,10 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void ``` audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error('Failed to set the ringer mode.​ ${err.message}'); + console.error(`Failed to set the ringer mode.​ ${err.message}`); return; } - console.log('Callback invoked to indicate a successful setting of the ringer mode.'); + console.log(`Callback invoked to indicate a successful setting of the ringer mode.`); }); ``` @@ -1150,7 +1150,7 @@ setRingerMode(mode: AudioRingMode): Promise<void> ``` audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { - console.log('Promise returned to indicate a successful setting of the ringer mode.'); + console.log(`Promise returned to indicate a successful setting of the ringer mode.`); }); ``` @@ -1174,10 +1174,10 @@ getRingerMode(callback: AsyncCallback<AudioRingMode>): void ``` audioManager.getRingerMode((err, value) => { if (err) { - console.error('Failed to obtain the ringer mode.​ ${err.message}'); + console.error(`Failed to obtain the ringer mode.​ ${err.message}`); return; } - console.log('Callback invoked to indicate that the ringer mode is obtained.' + value); + console.log(`Callback invoked to indicate that the ringer mode is obtained.` + value); }); ``` @@ -1200,7 +1200,7 @@ getRingerMode(): Promise<AudioRingMode> ``` audioManager.getRingerMode().then((value) => { - console.log('Promise returned to indicate that the ringer mode is obtained.' + value); + console.log(`Promise returned to indicate that the ringer mode is obtained.` + value); }); ``` @@ -1229,10 +1229,10 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback<void> ``` audioManager.setAudioParameter('key_example', 'value_example', (err) => { if (err) { - console.error('Failed to set the audio parameter. ${err.message}'); + console.error(`Failed to set the audio parameter. ${err.message}`); return; } - console.log('Callback invoked to indicate a successful setting of the audio parameter.'); + console.log(`Callback invoked to indicate a successful setting of the audio parameter.`); }); ``` @@ -1265,7 +1265,7 @@ setAudioParameter(key: string, value: string): Promise<void> ``` audioManager.setAudioParameter('key_example', 'value_example').then(() => { - console.log('Promise returned to indicate a successful setting of the audio parameter.'); + console.log(`Promise returned to indicate a successful setting of the audio parameter.`); }); ``` @@ -1291,10 +1291,10 @@ getAudioParameter(key: string, callback: AsyncCallback<string>): void ``` audioManager.getAudioParameter('key_example', (err, value) => { if (err) { - console.error('Failed to obtain the value of the audio parameter. ${err.message}'); + console.error(`Failed to obtain the value of the audio parameter. ${err.message}`); return; } - console.log('Callback invoked to indicate that the value of the audio parameter is obtained.' + value); + console.log(`Callback invoked to indicate that the value of the audio parameter is obtained.` + value); }); ``` @@ -1324,7 +1324,7 @@ getAudioParameter(key: string): Promise<string> ``` audioManager.getAudioParameter('key_example').then((value) => { - console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value); + console.log(`Promise returned to indicate that the value of the audio parameter is obtained.` + value); }); ``` @@ -1347,10 +1347,10 @@ getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescrip ``` audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { - console.error('Failed to obtain the device list. ${err.message}'); + console.error(`Failed to obtain the device list. ${err.message}`); return; } - console.log('Callback invoked to indicate that the device list is obtained.'); + console.log(`Callback invoked to indicate that the device list is obtained.`); }); ``` @@ -1378,7 +1378,7 @@ getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> ``` audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.log('Promise returned to indicate that the device list is obtained.'); + console.log(`Promise returned to indicate that the device list is obtained.`); }); ``` @@ -1403,10 +1403,10 @@ setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCa ``` audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { if (err) { - console.error('Failed to set the active status of the device. ${err.message}'); + console.error(`Failed to set the active status of the device. ${err.message}`); return; } - console.log('Callback invoked to indicate that the device is set to the active status.'); + console.log(`Callback invoked to indicate that the device is set to the active status.`); }); ``` @@ -1436,7 +1436,7 @@ setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void& ``` audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { - console.log('Promise returned to indicate that the device is set to the active status.'); + console.log(`Promise returned to indicate that the device is set to the active status.`); }); ``` @@ -1460,10 +1460,10 @@ isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean& ``` audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { if (err) { - console.error('Failed to obtain the active status of the device. ${err.message}'); + console.error(`Failed to obtain the active status of the device. ${err.message}`); return; } - console.log('Callback invoked to indicate that the active status of the device is obtained.'); + console.log(`Callback invoked to indicate that the active status of the device is obtained.`); }); ``` @@ -1492,7 +1492,7 @@ isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> ``` audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { - console.log('Promise returned to indicate that the active status of the device is obtained.' + value); + console.log(`Promise returned to indicate that the active status of the device is obtained.` + value); }); ``` @@ -1518,10 +1518,10 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void ``` audioManager.setMicrophoneMute(true, (err) => { if (err) { - console.error('Failed to mute the microphone. ${err.message}'); + console.error(`Failed to mute the microphone. ${err.message}`); return; } - console.log('Callback invoked to indicate that the microphone is muted.'); + console.log(`Callback invoked to indicate that the microphone is muted.`); }); ``` @@ -1551,7 +1551,7 @@ setMicrophoneMute(mute: boolean): Promise<void> ``` audioManager.setMicrophoneMute(true).then(() => { - console.log('Promise returned to indicate that the microphone is muted.'); + console.log(`Promise returned to indicate that the microphone is muted.`); }); ``` @@ -1576,10 +1576,10 @@ isMicrophoneMute(callback: AsyncCallback<boolean>): void ``` audioManager.isMicrophoneMute((err, value) => { if (err) { - console.error('Failed to obtain the mute status of the microphone. ${err.message}'); + console.error(`Failed to obtain the mute status of the microphone. ${err.message}`); return; } - console.log('Callback invoked to indicate that the mute status of the microphone is obtained.' + value); + console.log(`Callback invoked to indicate that the mute status of the microphone is obtained.` + value); }); ``` @@ -1604,7 +1604,7 @@ isMicrophoneMute(): Promise<boolean> ``` audioManager.isMicrophoneMute().then((value) => { - console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value); + console.log(`Promise returned to indicate that the mute status of the microphone is obtained.`, + value); }); ``` @@ -1631,9 +1631,9 @@ on(type: 'volumeChange', callback: Callback\): void ``` audioManager.on('volumeChange', (volumeEvent) => { - console.log('VolumeType of stream: ' + volumeEvent.volumeType); - console.log('Volume level: ' + volumeEvent.volume); - console.log('Whether to updateUI: ' + volumeEvent.updateUi); + console.log(`VolumeType of stream: ` + volumeEvent.volumeType); + console.log(`Volume level: ` + volumeEvent.volume); + console.log(`Whether to updateUI: ` + volumeEvent.updateUi); }); ``` @@ -1658,7 +1658,7 @@ on(type: 'ringerModeChange', callback: Callback\): void ``` audioManager.on('ringerModeChange', (ringerMode) => { - console.log('Updated ringermode: ' + ringerMode); + console.log(`Updated ringermode: ` + ringerMode); }); ``` @@ -1675,16 +1675,16 @@ on(type: 'deviceChange', callback: Callback): void | 参数名 | 类型 | 必填 | 说明 | | :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | | type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | 是 | 获取设备更新详情。 | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | 是 | 获取设备更新详情。 | **示例:** ``` audioManager.on('deviceChange', (deviceChanged) => { - console.info("device change type : " + deviceChanged.type); - console.info("device descriptor size : " + deviceChanged.deviceDescriptors.length); - console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceRole); - console.info("device change descriptor : " + deviceChanged.deviceDescriptors[0].deviceType); + console.info(`device change type : ` + deviceChanged.type); + console.info(`device descriptor size : ` + deviceChanged.deviceDescriptors.length); + console.info(`device change descriptor : ` + deviceChanged.deviceDescriptors[0].deviceRole); + console.info(`device change descriptor : ` + deviceChanged.deviceDescriptors[0].deviceType); }); ``` @@ -1701,13 +1701,13 @@ off(type: 'deviceChange', callback?: Callback): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------- | ---- | ------------------------------------------ | | type | string | 是 | 订阅的事件的类型。支持事件:'deviceChange' | -| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | 否 | 获取设备更新详情。 | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | 否 | 获取设备更新详情。 | **示例:** ``` audioManager.off('deviceChange', (deviceChanged) => { - console.log("Should be no callback."); + console.log(`Should be no callback.`); }); ``` @@ -1737,12 +1737,12 @@ var interAudioInterrupt = { }; audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { if (InterruptAction.actionType === 0) { - console.log("An event to gain the audio focus starts."); - console.log("Focus gain event:" + JSON.stringify(InterruptAction)); + console.log(`An event to gain the audio focus starts.`); + console.log(`Focus gain event:` + JSON.stringify(InterruptAction)); } if (InterruptAction.actionType === 1) { - console.log("An audio interruption event starts."); - console.log("Audio interruption event:" + JSON.stringify(InterruptAction)); + console.log(`An audio interruption event starts.`); + console.log(`Audio interruption event:` + JSON.stringify(InterruptAction)); } }); ``` @@ -1773,8 +1773,8 @@ var interAudioInterrupt = { }; audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { if (InterruptAction.actionType === 0) { - console.log("An event to release the audio focus starts."); - console.log("Focus release event:" + JSON.stringify(InterruptAction)); + console.log(`An event to release the audio focus starts.`); + console.log(`Focus release event:` + JSON.stringify(InterruptAction)); } }); ``` @@ -1801,10 +1801,10 @@ setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void ``` audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { - console.error('Failed to set the audio scene mode.​ ${err.message}'); + console.error(`Failed to set the audio scene mode.​ ${err.message}`); return; } - console.log('Callback invoked to indicate a successful setting of the audio scene mode.'); + console.log(`Callback invoked to indicate a successful setting of the audio scene mode.`); }); ``` @@ -1834,9 +1834,9 @@ setAudioScene\(scene: AudioScene\): Promise ``` audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { - console.log('Promise returned to indicate a successful setting of the audio scene mode.'); + console.log(`Promise returned to indicate a successful setting of the audio scene mode.`); }).catch ((err) => { - console.log('Failed to set the audio scene mode'); + console.log(`Failed to set the audio scene mode`); }); ``` @@ -1859,10 +1859,10 @@ getAudioScene\(callback: AsyncCallback\): void ``` audioManager.getAudioScene((err, value) => { if (err) { - console.error('Failed to obtain the audio scene mode.​ ${err.message}'); + console.error(`Failed to obtain the audio scene mode.​ ${err.message}`); return; } - console.log('Callback invoked to indicate that the audio scene mode is obtained.' + value); + console.log(`Callback invoked to indicate that the audio scene mode is obtained.` + value); }); ``` @@ -1885,9 +1885,9 @@ getAudioScene\(\): Promise ``` audioManager.getAudioScene().then((value) => { - console.log('Promise returned to indicate that the audio scene mode is obtained.' + value); + console.log(`Promise returned to indicate that the audio scene mode is obtained.` + value); }).catch ((err) => { - console.log('Failed to obtain the audio scene mode'); + console.log(`Failed to obtain the audio scene mode`); }); ``` @@ -1912,30 +1912,30 @@ getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeI **示例:** ``` audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { - console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); + console.info(`getCurrentAudioRendererInfoArray **** Get Callback Called ****`); if (err) { - console.log('getCurrentAudioRendererInfoArray :ERROR: '+ err.message); + console.log(`getCurrentAudioRendererInfoArray :ERROR: `+ err.message); resultFlag = false; } else { if (AudioRendererChangeInfoArray != null) { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info('StreamId for' + i + 'is:' + AudioRendererChangeInfo.streamId); - console.info('ClientUid for' + i + 'is:' + AudioRendererChangeInfo.clientUid); - console.info('Content' + i + 'is:' + AudioRendererChangeInfo.rendererInfo.content); - console.info('Stream'+ i + 'is:' + AudioRendererChangeInfo.rendererInfo.usage); - console.info('Flag'+ i +' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info('State for' + i +' is:' + AudioRendererChangeInfo.rendererState); + console.info(`StreamId for` + i + `is:` + AudioRendererChangeInfo.streamId); + console.info(`ClientUid for` + i + `is:` + AudioRendererChangeInfo.clientUid); + console.info(`Content` + i + `is:` + AudioRendererChangeInfo.rendererInfo.content); + console.info(`Stream`+ i + `is:` + AudioRendererChangeInfo.rendererInfo.usage); + console.info(`Flag`+ i + `is:` + AudioRendererChangeInfo.rendererInfo.rendererFlags); + console.info(`State for` + i + `is:` + AudioRendererChangeInfo.rendererState); var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info('Id:' + i +':' + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCount' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); + console.info(`Id:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].id); + console.info(`Type:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); + console.info(`Role:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); + console.info(`Name:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].name); + console.info(`Address:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].address); + console.info(`SampleRates:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); + console.info(`ChannelCount` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); + console.info(`ChannelMask:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); } } } @@ -1960,31 +1960,31 @@ getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> **示例:** ``` await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info('getCurrentAudioRendererInfoArray ######### Get Promise is called ##########'); + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); if (AudioRendererChangeInfoArray != null) { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info('StreamId for ' + i +' is:' + AudioRendererChangeInfo.streamId); - console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid); - console.info('Content ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content); - console.info('Stream' + i +' is:' + AudioRendererChangeInfo.rendererInfo.usage); - console.info('Flag' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState); + console.info(`StreamId for` + i + ` is:` + AudioRendererChangeInfo.streamId); + console.info(`ClientUid for` + i + ` is:` + AudioRendererChangeInfo.clientUid); + console.info(`Content` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.content); + console.info(`Stream` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.usage); + console.info(`Flag` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.rendererFlags); + console.info(`State for` + i + ` is:` + AudioRendererChangeInfo.rendererState); var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info('ChannnelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); + console.info(`Id:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].id); + console.info(`Type:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); + console.info(`Role:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); + console.info(`Name:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].name); + console.info(`Address:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].address); + console.info(`SampleRates:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); + console.info(`ChannelCounts` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); + console.info(`ChannnelMask:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); } } } }).catch((err) => { - console.log('getCurrentAudioRendererInfoArray :ERROR: ' + err.message); + console.log(`getCurrentAudioRendererInfoArray :ERROR: ` + err.message); }); ``` @@ -2005,27 +2005,27 @@ getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeI **示例:** ``` audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { - console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); + console.info(`getCurrentAudioCapturerInfoArray **** Get Callback Called ****`); if (err) { - console.log('getCurrentAudioCapturerInfoArray :ERROR: '+err.message); + console.log(`getCurrentAudioCapturerInfoArray :ERROR: ` + err.message); } else { if (AudioCapturerChangeInfoArray != null) { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId); - console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid); - console.info('Source for '+ i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info('Flag ' + i +'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState); + console.info(`StreamId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); + console.info(`ClientUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); + console.info(`Source for `+ i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); + console.info(`Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); + console.info(`State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(`Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); + console.info(`Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); + console.info(`Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); + console.info(`Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); + console.info(`Address:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); + console.info(`SampleRates:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); + console.info(`ChannelCounts` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); + console.info(`ChannelMask:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); } } } @@ -2050,29 +2050,29 @@ getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> **示例:** ``` await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + console.info(`getCurrentAudioCapturerInfoArray **** Get Promise Called ****`); if (AudioCapturerChangeInfoArray != null) { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId); - console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid); - console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState); + console.info(`StreamId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); + console.info(`ClientUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); + console.info(`Source for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); + console.info(`Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); + console.info(`State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name) - console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(`Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); + console.info(`Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); + console.info(`Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); + console.info(`Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name) + console.info(`Address:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); + console.info(`SampleRates:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); + console.info(`ChannelCounts` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); + console.info(`ChannelMask:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); } } } }).catch((err) => { - console.log('getCurrentAudioCapturerInfoArray :ERROR: ' + err.message); + console.log(`getCurrentAudioCapturerInfoArray :ERROR: ` + err.message); }); ``` @@ -2096,23 +2096,23 @@ on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArr audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info('## RendererChange on is called for ' + i + ' ##'); - console.info('StreamId for ' + i + ' is:' + AudioRendererChangeInfo.streamId); - console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid); - console.info('Content for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content); - console.info('Stream for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.usage); - console.info('Flag ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState); + console.info(`## RendererChange on is called for ` + i + ` ##`); + console.info(`StreamId for ` + i + ` is:` + AudioRendererChangeInfo.streamId); + console.info(`ClientUid for ` + i + ` is:` + AudioRendererChangeInfo.clientUid); + console.info(`Content for ` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.content); + console.info(`Stream for ` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.usage); + console.info(`Flag ` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.rendererFlags); + console.info(`State for ` + i + ` is:` + AudioRendererChangeInfo.rendererState); var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); + console.info(`Id:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].id); + console.info(`Type:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); + console.info(`Role:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); + console.info(`Name:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].name); + console.info(`Address:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].address); + console.info(`SampleRates:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); + console.info(`ChannelCounts` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); + console.info(`ChannelMask:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); } } }); @@ -2135,7 +2135,7 @@ off(type: "audioRendererChange"); **示例:** ``` audioStreamManager.off('audioRendererChange'); -console.info('######### RendererChange Off is called #########'); +console.info(`######### RendererChange Off is called #########`); ``` ### on('audioCapturerChange')9+ @@ -2157,21 +2157,21 @@ on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArr ``` audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(' ## CapChange on is called for element ' + i + ' ##'); - console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId); - console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid); - console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState); + console.info(` ## CapChange on is called for element ' + i + ' ##'); + console.info(`StreamId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); + console.info(`ClientUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); + console.info(`Source for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); + console.info(`Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); + console.info(`State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); - console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(`Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); + console.info(`Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); + console.info(`Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); + console.info(`Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); + console.info(`Address:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); + console.info(`SampleRates:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); + console.info(`ChannelCounts` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); + console.info(`ChannelMask:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); } } }); @@ -2194,7 +2194,7 @@ off(type: "audioCapturerChange"); **示例:** ``` audioStreamManager.off('audioCapturerChange'); -console.info('######### CapturerChange Off is called #########'); +console.info(`######### CapturerChange Off is called #########`); ``` @@ -2227,7 +2227,7 @@ var AudioStreamInfo = { var audioStreamManager = audioManager.getStreamManager(); audioStreamManager.isAudioRendererLowLatencySupported(AudioStreamInfo, (result) => { - console.info('isAudioRendererLowLatencySupported success var = ' + result); + console.info(`isAudioRendererLowLatencySupported success var = ` + result); }); ``` @@ -2265,7 +2265,7 @@ var AudioStreamInfo = { var audioStreamManager = await audioManager.getStreamManager(); var result = audioStreamManager.isAudioRendererLowLatencySupported(AudioStreamInfo); -console.info('isAudioRendererLowLatencySupported success var =' + result); +console.info(`isAudioRendererLowLatencySupported success var =` + result); ``` ## AudioRendererChangeInfo9+ @@ -2299,43 +2299,43 @@ var resultFlag = false; await audioManager.getStreamManager().then(async function (data) { audioStreamManager = data; - console.info(Tag + 'Get AudioStream Manager : Success '); + console.info(Tag + `Get AudioStream Manager : Success `); }).catch((err) => { - console.info(Tag + 'Get AudioStream Manager : ERROR : ' + err.message); + console.info(Tag + `Get AudioStream Manager : ERROR : ` + err.message); }); audioManager.getStreamManager((err, data) => { if (err) { - console.error(Tag + 'Get AudioStream Manager : ERROR : ' + err.message); + console.error(Tag + `Get AudioStream Manager : ERROR : ` + err.message); } else { audioStreamManagerCB = data; - console.info(Tag + 'Get AudioStream Manager : Success '); + console.info(Tag + `Get AudioStream Manager : Success `); } }); audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - console.info(Tag+'## RendererChange on is called for ' + i + ' ##'); - console.info(Tag+'StreamId for ' + i + 'is:' + AudioRendererChangeInfoArray[i].streamId); - console.info(Tag+'ClientUid for ' + i + 'is:' + AudioRendererChangeInfoArray[i].clientUid); - console.info(Tag+'Content for ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererInfo.content); - console.info(Tag+'Stream for ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererInfo.usage); - console.info(Tag+'Flag ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags); - console.info(Tag+'State for ' + i + 'is:' + AudioRendererChangeInfoArray[i].rendererState); + console.info(Tag + `## RendererChange on is called for ` + i + ` ##`); + console.info(Tag + `StreamId for ` + i + `is:` + AudioRendererChangeInfoArray[i].streamId); + console.info(Tag + `ClientUid for ` + i + `is:` + AudioRendererChangeInfoArray[i].clientUid); + console.info(Tag + `Content for ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererInfo.content); + console.info(Tag + `Stream for ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererInfo.usage); + console.info(Tag + `Flag ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags); + console.info(Tag + `State for ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererState); var devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(Tag+'Id:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].id); - console.info(Tag+'Type:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info(Tag+'Role:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info(Tag+'Name:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].name); - console.info(Tag+'Addr:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].address); - console.info(Tag+'SR:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info(Tag+'C' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info(Tag+'CM:' + i + ':' + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(Tag + `Id:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].id); + console.info(Tag + `Type:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType); + console.info(Tag + `Role:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole); + console.info(Tag + `Name:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].name); + console.info(Tag + `Addr:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].address); + console.info(Tag + `SR:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); + console.info(Tag + `C` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); + console.info(Tag + `CM:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks); } if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { resultFlag = true; - console.info(Tag + 'ResultFlag for '+ i +' is:'+ resultFlag); + console.info(Tag + `ResultFlag for ` + i + ` is:` + resultFlag); } } }); @@ -2370,26 +2370,26 @@ var Tag = "AFCapLog : "; var resultFlag = false; audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(Tag + ' ## CapChange on is called for element ' + i + ' ##'); - console.info(Tag + 'StrId for ' + i +'is:' + AudioCapturerChangeInfoArray[i].streamId); - console.info(Tag + 'CUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid); - console.info(Tag + 'Src for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info(Tag + 'Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info(Tag + 'State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState); + console.info(Tag + ` ## CapChange on is called for element ' + i + ' ##'); + console.info(Tag + `StrId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); + console.info(Tag + `CUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); + console.info(Tag + `Src for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); + console.info(Tag + `Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); + console.info(Tag + `State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(Tag + 'Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info(Tag + 'Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info(Tag + 'Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info(Tag + 'Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); - console.info(Tag + 'Addr:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info(Tag + 'SR:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info(Tag + 'C' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info(Tag + 'CM:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(Tag + `Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); + console.info(Tag + `Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); + console.info(Tag + `Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); + console.info(Tag + `Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); + console.info(Tag + `Addr:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); + console.info(Tag + `SR:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); + console.info(Tag + `C` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); + console.info(Tag + `CM:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); } if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { resultFlag = true; - console.info(Tag + 'ResultFlag for element ' + i + ' is: ' + resultFlag); + console.info(Tag + `ResultFlag for element ` + i + ` is: ` + resultFlag); } } }); @@ -2430,12 +2430,12 @@ var deviceRoleValue = null; var deviceTypeValue = null; const promise = audio.getAudioManager().getDevices(1); promise.then(function (value) { - console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); + console.info(`AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG`); value.forEach(displayDeviceProp); if (deviceTypeValue != null && deviceRoleValue != null){ - console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); + console.info(`AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS`); } else { - console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); + console.info(`AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL`); } }); ``` @@ -2476,10 +2476,10 @@ getRendererInfo(callback: AsyncCallback): void ``` audioRenderer.getRendererInfo((err, rendererInfo) => { - console.log('Renderer GetRendererInfo:'); - console.log('Renderer content:' + rendererInfo.content); - console.log('Renderer usage:' + rendererInfo.usage); - console.log('Renderer flags:' + rendererInfo.rendererFlags); + console.log(`Renderer GetRendererInfo:`); + console.log(`Renderer content:` + rendererInfo.content); + console.log(`Renderer usage:` + rendererInfo.usage); + console.log(`Renderer flags:` + rendererInfo.rendererFlags); }); ``` @@ -2502,12 +2502,12 @@ getRendererInfo(): Promise ``` var resultFlag = true; audioRenderer.getRendererInfo().then((rendererInfo) => { - console.log('Renderer GetRendererInfo:'); - console.log('Renderer content:' + rendererInfo.content); - console.log('Renderer usage:' + rendererInfo.usage); - console.log('Renderer flags:' + rendererInfo.rendererFlags); + console.log(`Renderer GetRendererInfo:`); + console.log(`Renderer content:` + rendererInfo.content); + console.log(`Renderer usage:` + rendererInfo.usage); + console.log(`Renderer flags:` + rendererInfo.rendererFlags); }).catch((err) => { - console.log('AudioFrameworkRenderLog: RendererInfo :ERROR: ' + err.message); + console.log(`AudioFrameworkRenderLog: RendererInfo :ERROR: ` + err.message); resultFlag = false; }); ``` @@ -2530,11 +2530,11 @@ getStreamInfo(callback: AsyncCallback): void ``` audioRenderer.getStreamInfo((err, streamInfo) => { - console.log('Renderer GetStreamInfo:'); - console.log('Renderer sampling rate:' + streamInfo.samplingRate); - console.log('Renderer channel:' + streamInfo.channels); - console.log('Renderer format:' + streamInfo.sampleFormat); - console.log('Renderer encoding type:' + streamInfo.encodingType); + console.log(`Renderer GetStreamInfo:`); + console.log(`Renderer sampling rate:` + streamInfo.samplingRate); + console.log(`Renderer channel:` + streamInfo.channels); + console.log(`Renderer format:` + streamInfo.sampleFormat); + console.log(`Renderer encoding type:` + streamInfo.encodingType); }); ``` @@ -2556,13 +2556,13 @@ getStreamInfo(): Promise ``` audioRenderer.getStreamInfo().then((streamInfo) => { - console.log('Renderer GetStreamInfo:'); - console.log('Renderer sampling rate:' + streamInfo.samplingRate); - console.log('Renderer channel:' + streamInfo.channels); - console.log('Renderer format:' + streamInfo.sampleFormat); - console.log('Renderer encoding type:' + streamInfo.encodingType); + console.log(`Renderer GetStreamInfo:`); + console.log(`Renderer sampling rate:` + streamInfo.samplingRate); + console.log(`Renderer channel:` + streamInfo.channels); + console.log(`Renderer format:` + streamInfo.sampleFormat); + console.log(`Renderer encoding type:` + streamInfo.encodingType); }).catch((err) => { - console.log('ERROR: '+err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -2585,9 +2585,9 @@ start(callback: AsyncCallback): void ``` audioRenderer.start((err) => { if (err) { - console.error('Renderer start failed.'); + console.error(`Renderer start failed.`); } else { - console.info('Renderer start success.'); + console.info(`Renderer start success.`); } }); ``` @@ -2610,9 +2610,9 @@ start(): Promise ``` audioRenderer.start().then(() => { - console.log('Renderer started'); + console.log(`Renderer started`); }).catch((err) => { - console.log('ERROR: ' + err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -2635,9 +2635,9 @@ pause(callback: AsyncCallback\): void ``` audioRenderer.pause((err) => { if (err) { - console.error('Renderer pause failed'); + console.error(`Renderer pause failed`); } else { - console.log('Renderer paused.'); + console.log(`Renderer paused.`); } }); ``` @@ -2660,9 +2660,9 @@ pause(): Promise\ ``` audioRenderer.pause().then(() => { - console.log('Renderer paused'); + console.log(`Renderer paused`); }).catch((err) => { - console.log('ERROR: '+err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -2685,9 +2685,9 @@ drain(callback: AsyncCallback\): void ``` audioRenderer.drain((err) => { if (err) { - console.error('Renderer drain failed'); + console.error(`Renderer drain failed`); } else { - console.log('Renderer drained.'); + console.log(`Renderer drained.`); } }); ``` @@ -2710,9 +2710,9 @@ drain(): Promise\ ``` audioRenderer.drain().then(() => { - console.log('Renderer drained successfully'); + console.log(`Renderer drained successfully`); }).catch((err) => { - console.log('ERROR: '+ err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -2735,9 +2735,9 @@ stop(callback: AsyncCallback\): void ``` audioRenderer.stop((err) => { if (err) { - console.error('Renderer stop failed'); + console.error(`Renderer stop failed`); } else { - console.log('Renderer stopped.'); + console.log(`Renderer stopped.`); } }); ``` @@ -2760,9 +2760,9 @@ stop(): Promise\ ``` audioRenderer.stop().then(() => { - console.log('Renderer stopped successfully'); + console.log(`Renderer stopped successfully`); }).catch((err) => { - console.log('ERROR: ' + err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -2785,9 +2785,9 @@ release(callback: AsyncCallback\): void ``` audioRenderer.release((err) => { if (err) { - console.error('Renderer release failed'); + console.error(`Renderer release failed`); } else { - console.log('Renderer released.'); + console.log(`Renderer released.`); } }); ``` @@ -2810,9 +2810,9 @@ release(): Promise\ ``` audioRenderer.release().then(() => { - console.log('Renderer released successfully'); + console.log(`Renderer released successfully`); }).catch((err) => { - console.log('ERROR: '+ err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -2858,18 +2858,18 @@ var audioRendererOptions = { var audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data)=> { audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + console.info(`AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS`); }).catch((err) => { - console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ' + err.message); + console.info(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ` + err.message); }); var bufferSize; audioRenderer.getBufferSize().then((data)=> { - console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS ' + data); + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ` + data); bufferSize = data; }).catch((err) => { - console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: ' + err.message); + console.info.(`AudioFrameworkRenderLog: getBufferSize: ERROR: ` + err.message); }); -console.info('Buffer size:'+bufferSize); +console.info(`Buffer size:` + bufferSize); var context = featureAbility.getContext(); var path = await context.getCacheDir(); var filePath = path + "/StarWars10s-2C-48000-4SW.wav"; @@ -2878,9 +2878,9 @@ let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); audioRenderer.write(buf, (err, writtenbytes) => { if (writtenbytes < 0) { - console.error('write failed.'); + console.error(`write failed.`); } else { - console.log('Actual written bytes: ' + writtenbytes); + console.log(`Actual written bytes: ` + writtenbytes); } }); ``` @@ -2926,18 +2926,18 @@ var audioRendererOptions = { var audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + console.info(`AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS`); }).catch((err) => { - console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ' + err.message); + console.info(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ` + err.message); }); var bufferSize; audioRenderer.getBufferSize().then((data) => { - console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS ' + data); + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ` + data); bufferSize = data; }).catch((err) => { - console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: ' + err.message); + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ` + err.message); }); -console.info('BufferSize: ' + bufferSize); +console.info(`BufferSize: ` + bufferSize); var context = featureAbility.getContext(); var path = await context.getCacheDir(); var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; @@ -2946,12 +2946,12 @@ let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); audioRenderer.write(buf).then((writtenbytes) => { if (writtenbytes < 0) { - console.error('write failed.'); + console.error(`write failed.`); } else { - console.log('Actual written bytes: ' + writtenbytes); + console.log(`Actual written bytes: ` + writtenbytes); } }).catch((err) => { - console.log('ERROR: '+ err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -2973,7 +2973,7 @@ getAudioTime(callback: AsyncCallback\): void ``` audioRenderer.getAudioTime((err, timestamp) => { - console.log('Current timestamp: ' + timestamp); + console.log(`Current timestamp: ` + timestamp); }); ``` @@ -2995,9 +2995,9 @@ getAudioTime(): Promise\ ``` audioRenderer.getAudioTime().then((timestamp) => { - console.log('Current timestamp: ' + timestamp); + console.log(`Current timestamp: ` + timestamp); }).catch((err) => { - console.log('ERROR: '+err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -3020,7 +3020,7 @@ getBufferSize(callback: AsyncCallback\): void ``` var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { if (err) { - console.error('getBufferSize error'); + console.error(`getBufferSize error`); } }); ``` @@ -3071,10 +3071,10 @@ audio.createAudioRenderer(audioRendererOptions).then((data) => { }); var bufferSize; audioRenderer.getBufferSize().then((data) => { - console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS ' + data); + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ` + data); bufferSize = data; }).catch((err) => { - console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: ' + err.message); + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ` + err.message); }); ``` @@ -3098,9 +3098,9 @@ setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void ``` audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { if (err) { - console.error('Failed to set params'); + console.error(`Failed to set params`); } else { - console.log('Callback invoked to indicate a successful render rate setting.'); + console.log(`Callback invoked to indicate a successful render rate setting.`); } }); ``` @@ -3129,9 +3129,9 @@ setRenderRate(rate: AudioRendererRate): Promise\ ``` audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { - console.log('setRenderRate SUCCESS'); + console.log(`setRenderRate SUCCESS`); }).catch((err) => { - console.log('ERROR: '+ err.message); + console.log(`ERROR: ` + err.message); }); ``` @@ -3153,7 +3153,7 @@ getRenderRate(callback: AsyncCallback\): void ``` audioRenderer.getRenderRate((err, renderrate) => { - console.log('getRenderRate: ' + renderrate); + console.log(`getRenderRate: ` + renderrate); }); ``` @@ -3175,9 +3175,9 @@ getRenderRate(): Promise\ ``` audioRenderer.getRenderRate().then((renderRate) => { - console.log('getRenderRate: ' + renderRate); + console.log(`getRenderRate: ` + renderRate); }).catch((err) => { - console.log('ERROR: '+ err.message); + console.log(`ERROR: ` + err.message); }); ``` ### setInterruptMode9+ @@ -3192,7 +3192,7 @@ setInterruptMode(mode: InterruptMode): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------- | ------ | ---------- | -| mode | [InterruptMode](#InterruptMode) | 是 | 焦点模型。 | +| mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。 | **返回值:** @@ -3221,9 +3221,9 @@ var audioRendererOptions = { let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 0; audioRenderer.setInterruptMode(mode).then(data=>{ - console.log("setInterruptMode Success!"); + console.log(`setInterruptMode Success!`); }).catch(err=>{ - console.log("setInterruptMode Fail:" + err.message); + console.log(`setInterruptMode Fail:` + err.message); }); ``` ### setInterruptMode9+ @@ -3238,7 +3238,7 @@ setInterruptMode(mode: InterruptMode, callback: Callback\): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------------------------- | ------ | -------------- | -|mode | [InterruptMode](#InterruptMode) | 是 | 焦点模型。| +|mode | [InterruptMode](#interruptmode9) | 是 | 焦点模型。| |callback | Callback\ | 是 |回调返回执行结果。| **示例:** @@ -3263,9 +3263,9 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 1; audioRenderer.setInterruptMode(mode, (err, data)=>{ if(err){ - console.log("setInterruptMode Fail:" + err.message); + console.log(`setInterruptMode Fail:` + err.message); } - console.log("setInterruptMode Success!"); + console.log(`setInterruptMode Success!`); }); ``` ### on('interrupt')9+ @@ -3292,40 +3292,40 @@ audioRenderer.on('interrupt', async(interruptEvent) => { if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { switch (interruptEvent.hintType) { case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.log('Force paused. Stop writing'); + console.log(`Force paused. Stop writing`); isPlay = false; break; case audio.InterruptHint.INTERRUPT_HINT_STOP: - console.log('Force stopped. Stop writing'); + console.log(`Force stopped. Stop writing`); isPlay = false; break; } } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { switch (interruptEvent.hintType) { case audio.InterruptHint.INTERRUPT_HINT_RESUME: - console.log('Resume force paused renderer or ignore'); + console.log(`Resume force paused renderer or ignore`); await audioRenderer.start().then(async function () { - console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); + console.info(`AudioInterruptMusic: renderInstant started :SUCCESS `); started = true; }).catch((err) => { - console.info('AudioInterruptMusic: renderInstant start :ERROR : ' + err.message); + console.info(`AudioInterruptMusic: renderInstant start :ERROR : ` + err.message); started = false; }); if (started) { isPlay = true; - console.info('AudioInterruptMusic Renderer started : isPlay : ' + isPlay); + console.info(`AudioInterruptMusic Renderer started : isPlay : ` + isPlay); } else { - console.error('AudioInterruptMusic Renderer start failed'); + console.error(`AudioInterruptMusic Renderer start failed`); } break; case audio.InterruptHint.INTERRUPT_HINT_PAUSE: console.log('Choose to pause or ignore'); if (isPlay == true) { isPlay == false; - console.info('AudioInterruptMusic: Media PAUSE : TRUE'); + console.info(`AudioInterruptMusic: Media PAUSE : TRUE`); } else { isPlay = true; - console.info('AudioInterruptMusic: Media PLAY : TRUE'); + console.info(`AudioInterruptMusic: Media PLAY : TRUE`); } break; } @@ -3354,7 +3354,7 @@ on(type: 'markReach', frame: number, callback: (position: number) => {}): void ``` audioRenderer.on('markReach', 1000, (position) => { if (position == 1000) { - console.log('ON Triggered successfully'); + console.log(`ON Triggered successfully`); } }); ``` @@ -3401,7 +3401,7 @@ on(type: "periodReach", frame: number, callback: (position: number) => {}): void ``` audioRenderer.on('periodReach', 1000, (position) => { if (position == 1000) { - console.log('ON Triggered successfully'); + console.log(`ON Triggered successfully`); } }); ``` @@ -3446,10 +3446,10 @@ on(type: 'stateChange', callback: Callback): void ``` audioRenderer.on('stateChange', (state) => { if (state == 1) { - console.log("audio renderer state is: STATE_PREPARED"); + console.log(`audio renderer state is: STATE_PREPARED`); } if (state == 2) { - console.log("audio renderer state is: STATE_RUNNING"); + console.log(`audio renderer state is: STATE_RUNNING`); } }); ``` @@ -3458,7 +3458,7 @@ audioRenderer.on('stateChange', (state) => { on(type: "dataRequest", callback: Callback\): void; -订阅音频数据requeset事件回调。 +订阅音频数据request事件回调。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer @@ -3479,7 +3479,7 @@ const path = '/data/storage/el2/ba se/haps/entry/cache/PinkPanther60-44100-1c.w audioRenderer.on('dataRequest', (audioRendererDataInfo) => { var viewObject = new DataView(audioRendererDataInfo.buffer); rlen += ss.readSync(viewObject.buffer); - console.info('AudioRenderLog: bytes read from file: ' + rlen); + console.info(`AudioRenderLog: bytes read from file: ` + rlen); }) ``` @@ -3520,11 +3520,11 @@ getCapturerInfo(callback: AsyncCallback): void ``` audioCapturer.getCapturerInfo((err, capturerInfo) => { if (err) { - console.error('Failed to get capture info'); + console.error(`Failed to get capture info`); } else { - console.log('Capturer getCapturerInfo:'); - console.log('Capturer source:' + capturerInfo.source); - console.log('Capturer flags:' + capturerInfo.capturerFlags); + console.log(`Capturer getCapturerInfo:`); + console.log(`Capturer source:` + capturerInfo.source); + console.log(`Capturer flags:` + capturerInfo.capturerFlags); } }); ``` @@ -3549,15 +3549,15 @@ getCapturerInfo(): Promise ``` audioCapturer.getCapturerInfo().then((audioParamsGet) => { if (audioParamsGet != undefined) { - console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); - console.info('AudioFrameworkRecLog: Capturer SourceType:' + audioParamsGet.source); - console.info('AudioFrameworkRecLog: Capturer capturerFlags:' + audioParamsGet.capturerFlags); + console.info(`AudioFrameworkRecLog: Capturer CapturerInfo:`); + console.info(`AudioFrameworkRecLog: Capturer SourceType:` + audioParamsGet.source); + console.info(`AudioFrameworkRecLog: Capturer capturerFlags:` + audioParamsGet.capturerFlags); } else { - console.info('AudioFrameworkRecLog: audioParamsGet is : '+ audioParamsGet); - console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect: '); + console.info(`AudioFrameworkRecLog: audioParamsGet is : ` + audioParamsGet); + console.info(`AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect: `); } }).catch((err) => { - console.log('AudioFrameworkRecLog: CapturerInfo :ERROR: '+ err.message); + console.log(`AudioFrameworkRecLog: CapturerInfo :ERROR: ` + err.message); }); ``` @@ -3580,13 +3580,13 @@ getStreamInfo(callback: AsyncCallback): void ``` audioCapturer.getStreamInfo((err, streamInfo) => { if (err) { - console.error('Failed to get stream info'); + console.error(`Failed to get stream info'); } else { - console.log('Capturer GetStreamInfo:'); - console.log('Capturer sampling rate:' + streamInfo.samplingRate); - console.log('Capturer channel:' + streamInfo.channels); - console.log('Capturer format:' + streamInfo.sampleFormat); - console.log('Capturer encoding type:' + streamInfo.encodingType); + console.log(`Capturer GetStreamInfo:`); + console.log(`Capturer sampling rate:` + streamInfo.samplingRate); + console.log(`Capturer channel:` + streamInfo.channels); + console.log(`Capturer format:` + streamInfo.sampleFormat); + console.log(`Capturer encoding type:` + streamInfo.encodingType); } }); ``` @@ -3609,13 +3609,13 @@ getStreamInfo(): Promise ``` audioCapturer.getStreamInfo().then((audioParamsGet) => { - console.info('getStreamInfo:'); - console.info('sampleFormat:' + audioParamsGet.sampleFormat); - console.info('samplingRate:' + audioParamsGet.samplingRate); - console.info('channels:' + audioParamsGet.channels); - console.info('encodingType:' + audioParamsGet.encodingType); + console.info(`getStreamInfo:`); + console.info(`sampleFormat:` + audioParamsGet.sampleFormat); + console.info(`samplingRate:` + audioParamsGet.samplingRate); + console.info(`channels:` + audioParamsGet.channels); + console.info(`encodingType:` + audioParamsGet.encodingType); }).catch((err) => { - console.log('getStreamInfo :ERROR: ' + err.message); + console.log(`getStreamInfo :ERROR: ` + err.message); }); ``` @@ -3638,9 +3638,9 @@ start(callback: AsyncCallback): void ``` audioCapturer.start((err) => { if (err) { - console.error('Capturer start failed.'); + console.error(`Capturer start failed.`); } else { - console.info('Capturer start success.'); + console.info(`Capturer start success.`); } }); ``` @@ -3682,20 +3682,20 @@ var audioCapturer; var stateFlag; audio.createAudioCapturer(audioCapturerOptions).then((data) => { audioCapturer = data; - console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer Created: SUCCESS`); }).catch((err) => { - console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: ' + err.message); + console.info(`AudioFrameworkRecLog: AudioCapturer Created: ERROR: ` + err.message); }); audioCapturer.start().then(() => { - console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - console.info('AudioFrameworkRecLog: AudioCapturer: STATE: ' + audioCapturer.state); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS '); + console.info(`AudioFrameworkRecLog: ---------START---------`); + console.info(`AudioFrameworkRecLog: Capturer started: SUCCESS`); + console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ` + audioCapturer.state); + console.info(`AudioFrameworkRecLog: Capturer started: SUCCESS `); if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); + console.info(`AudioFrameworkRecLog: AudioCapturer is in Running State`); } }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer start :ERROR : ' + err.message); + console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ` + err.message); stateFlag = false; }); ``` @@ -3719,9 +3719,9 @@ stop(callback: AsyncCallback): void ``` audioCapturer.stop((err) => { if (err) { - console.error('Capturer stop failed'); + console.error(`Capturer stop failed`); } else { - console.log('Capturer stopped.'); + console.log(`Capturer stopped.`); } }); ``` @@ -3745,13 +3745,13 @@ stop(): Promise ``` audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); + console.info(`AudioFrameworkRecLog: ---------STOP RECORD---------`); + console.info(`AudioFrameworkRecLog: Capturer stopped: SUCCESS`); if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - console.info('AudioFrameworkRecLog: State is Stopped': '); + console.info(`AudioFrameworkRecLog: State is Stopped: `); } }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+ err.message); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ` + err.message); }); ``` @@ -3774,9 +3774,9 @@ release(callback: AsyncCallback): void ``` audioCapturer.release((err) => { if (err) { - console.error('capturer release failed'); + console.error(`capturer release failed`); } else { - console.log('capturer released.'); + console.log(`capturer released.`); } }); ``` @@ -3801,12 +3801,12 @@ release(): Promise ``` var stateFlag; audioCapturer.release().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); - console.info('AudioFrameworkRecLog: AudioCapturer : STATE : ' + audioCapturer.state); - console.info('AudioFrameworkRecLog: stateFlag : ' + stateFlag); + console.info(`AudioFrameworkRecLog: ---------RELEASE RECORD---------`); + console.info(`AudioFrameworkRecLog: Capturer release : SUCCESS`); + console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ` + audioCapturer.state); + console.info(`AudioFrameworkRecLog: stateFlag : ` + stateFlag); }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop: ERROR: ' + err.message); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ` + err.message); }); ``` @@ -3832,14 +3832,14 @@ read(size: number, isBlockingRead: boolean, callback: AsyncCallback { - console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS ' + data); + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ` + data); bufferSize = data; }).catch((err) => { - console.info('AudioFrameworkRecLog: getBufferSize: EROOR: ' + err.message); + console.info(`AudioFrameworkRecLog: getBufferSize: EROOR: ` + err.message); }); audioCapturer.read(bufferSize, true, async(err, buffer) => { if (!err) { - console.log("Success in reading the buffer data"); + console.log(`Success in reading the buffer data`); } }); ``` @@ -3871,16 +3871,16 @@ read(size: number, isBlockingRead: boolean): Promise ``` var bufferSize; audioCapturer.getBufferSize().then((data) => { - console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS ' + data); + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ` + data); bufferSize = data; }).catch((err) => { - console.info('AudioFrameworkRecLog: getBufferSize: ERROR ' + err.message); + console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ` + err.message); }); -console.info('Buffer size: ' + bufferSize); +console.info(`Buffer size: ` + bufferSize); audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('buffer read successfully'); + console.info(`buffer read successfully`); }).catch((err) => { - console.info('ERROR : ' + err.message); + console.info(`ERROR : ` + err.message); }); ``` @@ -3903,7 +3903,7 @@ getAudioTime(callback: AsyncCallback): void ``` audioCapturer.getAudioTime((err, timestamp) => { - console.log('Current timestamp: ' + timestamp); + console.log(`Current timestamp: ` + timestamp); }); ``` @@ -3926,9 +3926,9 @@ getAudioTime(): Promise ``` audioCapturer.getAudioTime().then((audioTime) => { - console.info('AudioFrameworkRecLog: AudioCapturer getAudioTime : Success' + audioTime ); + console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success` + audioTime ); }).catch((err) => { - console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : ' + err.message); + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ` + err.message); }); ``` @@ -3952,11 +3952,11 @@ getBufferSize(callback: AsyncCallback): void ``` audioCapturer.getBufferSize((err, bufferSize) => { if (!err) { - console.log('BufferSize : ' + bufferSize); + console.log(`BufferSize : ` + bufferSize); audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('Buffer read is ' + buffer ); + console.info(`Buffer read is ` + buffer ); }).catch((err) => { - console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : ' + err.message); + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ` + err.message); }); } }); @@ -3982,10 +3982,10 @@ getBufferSize(): Promise ``` var bufferSize; audioCapturer.getBufferSize().then((data) => { - console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS ' + data); + console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ` + data); bufferSize = data; }).catch((err) => { - console.info('AudioFrameworkRecLog: getBufferSize :ERROR : ' + err.message); + console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ` + err.message); }); ``` @@ -4011,7 +4011,7 @@ on(type: 'markReach', frame: number, callback: (position: number) => {}): void ``` audioCapturer.on('markReach', 1000, (position) => { if (position == 1000) { - console.log('ON Triggered successfully'); + console.log(`ON Triggered successfully`); } }); ``` @@ -4057,7 +4057,7 @@ on(type: "periodReach", frame: number, callback: (position: number) => {}): void ``` audioCapturer.on('periodReach', 1000, (position) => { if (position == 1000) { - console.log('ON Triggered successfully'); + console.log(`ON Triggered successfully`); } }); ``` @@ -4102,10 +4102,10 @@ on(type: 'stateChange', callback: Callback): void ``` audioCapturer.on('stateChange', (state) => { if (state == 1) { - console.log("audio capturer state is: STATE_PREPARED"); + console.log(`audio capturer state is: STATE_PREPARED`); } if (state == 2) { - console.log("audio capturer state is: STATE_RUNNING"); + console.log(`audio capturer state is: STATE_RUNNING`); } }); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md index 707fc62049d2c9e51bfe2c4bf8e0dfd12080bc23..05e0522d4d06bac796b5019314caec9f5d6f6b31 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,9 +1,10 @@ # 蓝牙 +蓝牙模块提供了基础的传统蓝牙能力以及BLE的扫描、广播等功能。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -蓝牙模块提供了基础的传统蓝牙能力以及BLE的扫描、广播等功能。 ## 导入模块 @@ -343,7 +344,7 @@ setBluetoothScanMode(mode: ScanMode, duration: number): boolean | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ---------------------------- | | mode | [ScanMode](#scanmode) | 是 | 蓝牙扫描模式。 | -| duration | number | 是 | 设备可被发现的持续时间,单位为秒;设置为0则持续可发现。 | +| duration | number | 是 | 设备可被发现的持续时间,单位为毫秒;设置为0则持续可发现。 | **返回值:** @@ -1029,7 +1030,7 @@ getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfi | 类型 | 说明 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [A2dpSourceProfile](#A2dpSourceProfile)或[HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile) | 对应的profile的对象实例,当前支持A2dpSourceProfile, HandsFreeAudioGatewayProfile。 | +| [A2dpSourceProfile](#a2dpsourceprofile)或[HandsFreeAudioGatewayProfile](#handsfreeaudiogatewayprofile) | 对应的profile的对象实例,当前支持A2dpSourceProfile, HandsFreeAudioGatewayProfile。 | **示例:** @@ -1055,7 +1056,7 @@ getProfileInst(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayP | 类型 | 说明 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [A2dpSourceProfile](#A2dpSourceProfile)或 [HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile)或[HidHostProfile](#HidHostProfile)或[PanProfile](#PanProfile) | 对应的profile的对象实例,当前支持A2dpSourceProfile/HandsFreeAudioGatewayProfile/HidHostProfile/PanProfile。 | +| [A2dpSourceProfile](#a2dpsourceprofile)或 [HandsFreeAudioGatewayProfile](#handsfreeaudiogatewayprofile)或[HidHostProfile](#hidhostprofile)或[PanProfile](#panprofile) | 对应的profile的对象实例,当前支持A2dpSourceProfile/HandsFreeAudioGatewayProfile/HidHostProfile/PanProfile。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-buffer.md b/zh-cn/application-dev/reference/apis/js-apis-buffer.md new file mode 100644 index 0000000000000000000000000000000000000000..e538e236f79a915e13cb1a30dd7b9bc9495ed3ad --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-buffer.md @@ -0,0 +1,2444 @@ +# Buffer + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +Buffer对象用于表示固定长度的字节序列,是专门存放二进制数据的缓存区。 + +**推荐使用场景:** 可用于处理大量二进制数据,处理图片、文件接收上传、网络协议等等 + +## 导入模块 + +```ts +import buffer from '@ohos.buffer'; +``` + +## Buffer + +### alloc + +alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer + +创建`size`个字节长度的Buffer实例,并初始化。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| size | number | 是 | 指定的Buffer实例长度,单位:字节。 | +| fill | string \| Buffer \| number | 否 | 预填充的值,默认值: 0 | +| encoding | BufferEncoding | 否 | 编码方式(当`fill`为string时,才有意义)。 默认值: 'utf-8' | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 带初始化的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.alloc(5); +let buf2 = buffer.alloc(5, 'a'); +let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +``` + +### allocUninitializedFromPool + +allocUninitializedFromPool(size: number): Buffer + +创建指定大小的未被初始化Buffer实例。内存从缓冲池分配。 +创建的Buffer的内容未知,需要使用fill()函数来初始化Buffer实例。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| size | number | 是 | 指定的Buffer实例长度,单位:字节。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 未初始化的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(10); +buf.fill(0); +``` + +### allocUninitialized + +allocUninitialized(size: number): Buffer + +创建指定大小的未被初始化Buffer实例。内存不从缓冲池分配。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| size | number | 是 |指定的Buffer实例长度,单位:字节。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 未初始化的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitialized(10); +buf.fill(0); +``` + +### byteLength + +byteLength(string: string | Buffer | TypeArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number + +根据不同的编码方法,返回字符串的字节数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| string | string \| Buffer \| TypeArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | 是 | 指定字符串。 | +| encoding | BufferEncoding | 否 | 编码方式。 默认值: 'utf-8' | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回字符串的字节数 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let str = '\u00bd + \u00bc = \u00be'; +console.log('${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8')} bytes'); +// 打印: ½ + ¼ = ¾: 9 characters, 12 bytes +``` + +### compare + +compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): number + +返回比较buf1和buf2的结果, 通常用于对Buffer实例的数组进行排序。 + + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| buf1 | Buffer \| Uint8Array | 是 | 待比较数组。 | +| buf2 | Buffer \| Uint8Array | 是 | 待比较数组。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 如果buf1与buf2相同,则返回0
如果排序时buf1位于buf2之后,则返回1
如果排序时buf1位于buf2之前,则返回-1。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('1234'); +let buf2 = buffer.from('0123'); + +console.log(buf1.compare(buf2)); +// 打印 1 +``` + +### concat + +concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer + +将`list`中的实例内容复制`totalLength`字节长度到新的Buffer实例中并返回。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| list | Buffer[] \| Uint8Array[] | 是 | 实例数组。 | +| totalLength | number | 否 | 需要融合的总字节长度。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 返回新Buffer的实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from("1234"); +let buf2 = buffer.from("abcd"); +let buf = buffer.concat([buf1, buf2]); +console.log(buf); // +``` + +### from + +from(array: number[]): Buffer + +根据指定数组创建新的Buffer实例。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| array | number[] | 是 | 指定数组。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 新的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let arrayList = new ArrayList(); + +let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); +console.log(buf); +// 打印: +``` + +### from + +from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer + +创建指定长度的与`arrayBuffer`共享内存的Buffer实例 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| arrayBuffer | ArrayBuffer \| SharedArrayBuffer | 是 | 实例对象。 | +| byteOffset | number | 否 | 字节偏移量,默认值: 0。 | +| length | number | 否 | 字节长度, 默认值: arrayBuffer.byteLength - byteOffset。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 返回一个共享内存的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let ab = new ArrayBuffer(10); +let buf = buffer.from(ab, 0, 2); +``` + +### from + +from(data: Buffer | Uint8Array): Buffer + +创建并复制`data`数据到新的Buffer实例并返回。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| data | Buffer \| Uint8Array | 是 | 实例数据。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 新的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('buffer'); +let buf2 = buffer.from(buf1); +``` + +### from + +from(object: Object, offsetOrEncoding: number | string, length: number): Buffer + +根据指定的`object`类型数据,创建新的Buffer实例。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| object | Object | 是 | 支持Symbol.toPrimitive或valueOf()的对象 | +| offsetOrEncoding | number \| string | 否 | 字节偏移量或编码。 | +| length | number | 否 | 字节长度。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 新的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from(new String('this is a test')); +``` + +### from + +from(string: string, encoding?: BufferEncoding): Buffer + +根据指定编码格式的字符串,创建新的Buffer实例。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| string | string | 是 | 字符串 | +| encoding | BufferEncoding | 否 | 编码格式。 默认值: 'utf-8'。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 新的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('this is a test'); +let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); + +console.log(buf1.toString()); // 打印: this is a test +console.log(buf2.toString()); +``` + + +### isBuffer + +isBuffer(obj: Object): boolean + +判断`obj`是否为Buffer。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| obj | Object | 是 | 判断对象 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 如果obj是Buffer,则返回true,否则返回false。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +buffer.isBuffer(buffer.alloc(10)); // true +buffer.isBuffer(buffer.from('foo')); // true +buffer.isBuffer('a string'); // false +buffer.isBuffer([]); // false +buffer.isBuffer(new Uint8Array(1024)); // false +``` + +### isEncoding + +isEncoding(encoding: string): boolean + +判断`encoding`是否为支持的编码格式。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| encoding | string | 是 | 编码格式。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | true或者false。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +console.log(Buffer.isEncoding('utf-8')); // 打印: true +console.log(Buffer.isEncoding('hex')); // 打印: true +console.log(Buffer.isEncoding('utf/8')); // 打印: false +console.log(Buffer.isEncoding('')); // 打印: false +``` + +### compare + +compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 + +`this`实例对象与`target`实例对象进行比较,返回buf在排序中的顺序,-1:前排序,0:与buf相同,1:后排序。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| target | Buffer \| Uint8Array | 是 | 要比较的实例对象。 | +| targetStart | number | 否 | `target`实例中开始的偏移量。 默认值: 0。 | +| targetEnd | number | 否 | `target`实例中结束的偏移量(不包括本身)。 默认值: target.lengt。 | +| sourceStart | number | 否 | `this`实例中开始的偏移量。 默认值: 0。 | +| sourceEnd | number | 否 | `this`实例中结束的偏移量(不包括本身)。 默认值: buf.length。 | + +| 类型 | 说明 | +| -------- | -------- | +| number | 比较结果。-1:前排序,0:与buf相同,1:后排序。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); +let buf2 = buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + +console.log(buf1.compare(buf2, 5, 9, 0, 4)); // 打印: 0 +console.log(buf1.compare(buf2, 0, 6, 4)); // 打印: -1 +console.log(buf1.compare(buf2, 5, 6, 5)); // 打印: 1 +``` + +### copy + +copy(target: Buffer| Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number + +将`this`实例中指定位置的数据复制到`target`的指定位置上,并返回复制的字节总长度。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| target | Buffer \| Uint8Array | 是 | 要复制到的Buffer或Uint8Array实例。 | +| targetStart | number | 否 | `target`实例中开始写入的偏移量。 默认值: 0。 | +| sourceStart | number | 否 | `this`实例中开始复制的偏移量。 默认值: 0。 | +| sourceEnd | number | 否 | `this`实例中结束复制的偏移量(不包括)。 默认值: buf.length。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 复制的字节总长度。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); +let buf2 = buffer.allocUninitializedFromPool(26).fill('!'); + +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} + +buf1.copy(buf2, 8, 16, 20); +console.log(buf2.toString('ascii', 0, 25)); +// 打印: !!!!!!!!qrst!!!!!!!!!!!!! +``` + +### entries + +entries(): IterableIterator<[number, number]> + +返回一个包含key和value的迭代器。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('buffer'); +for (let pair of buf.entries()) { + console.log(pair); +} +``` + +### equals + +equals(otherBuffer: Buffer | Uint8Array): boolean + +比较`this`实例和otherBuffer实例是否相等。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| otherBuffer | Buffer \| Uint8Array | 是 | 比较的目标对象。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 相等则返回true,否则返回false。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('ABC'); +let buf2 = buffer.from('414243', 'hex'); +let buf3 = buffer.from('ABCD'); + +console.log(buf1.equals(buf2)); // 打印: true +console.log(buf1.equals(buf3)); // 打印: false + +``` + +### fill + +fill(value: string | Buffer | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): Buffer + +用`value`填充`this`实例指定位置的数据,默认为循环填充,并返回填充后的Buffer实例。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | string \| Buffer \| Uint8Array \| number | 是 | 用于填充的值。 | +| offset | number | 否 | 起始偏移量。 默认值: 0。 | +| end | number | 否 | 结束偏移量(不包括在内)。 默认值: buf.length。 | +| encoding | BufferEncoding | 否 | 字符编码格式(`value`为string才有意义)。 默认值: 'utf-8'。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 填充后的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let b = buffer.allocUninitializedFromPool(50).fill('h'); +console.log(b.toString()); +``` + + +### includes + +includes(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): boolean + +检查Buffer对象是否包含`value`值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | 是 | 要搜索的内容。 | +| byteOffset | number | 否 | 字节偏移量。 如果为负数,则从末尾开始计算偏移量。 默认值: 0。 | +| encoding | BufferEncoding | 否 | 字符编码格式。 默认值: 'utf-8'。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 存在为true,否则为false。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this is a buffer'); +console.log(buf.includes('this')); // 打印: true +console.log(buf.includes('be')); // 打印: false +``` + +### indexOf + +indexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number + +查找`this`实例中第一次出现`value`的索引,如果不包含`value`,则为-1 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | 是 | 要搜索的内容。 | +| byteOffset | number | 否 | 字节偏移量。 如果为负数,则从末尾开始计算偏移量。 默认值: 0。 | +| encoding | BufferEncoding | 否 | 字符编码格式。 默认值: 'utf-8'。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 第一次出现位置。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this is a buffer'); +console.log(buf.indexOf('this')); // 打印: 0 +console.log(buf.indexOf('is')); // 打印: 2 +``` + +### keys + +keys(): IterableIterator<number> + +返回一个包含key值的迭代器 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<number> | 迭代器。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('buffer'); +for (const key of buf.keys()) { + console.log(key); +} +``` + +### lastIndexOf + +lastIndexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number + +返回`this`实例中最后一次出现`value`的索引,如果对象不包含,则为-1。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | 是 | 要搜索的内容。 | +| byteOffset | number | 否 | 字节偏移量。 如果为负数,则从末尾开始计算偏移量。 默认值: 0。 | +| encoding | BufferEncoding | 否 | 字符编码格式。 默认值: 'utf-8'。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 最后一次出现`value`值的索引。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this buffer is a buffer'); +console.log(buf.lastIndexOf('this')); // 打印: 0 +console.log(buf.lastIndexOf('buffer')); // 打印: 17 +``` + + +### readBigInt64BE + +readBigInt64BE(offset: number): number + +从指定的`offset`处读取有符号的大端序64位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigInt64BE(0)); +``` + +### readBigInt64LE + +readBigInt64LE(offset: number): number + +从指定的`offset`处读取无符号的小端序64位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigInt64LE(0)); +``` + +### readBigUInt64BE + +readBigUInt64BE(offset: number): number + +从指定的`offset`处读取无符号的大端序64位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigUInt64BE(0)); +``` + +### readBigUInt64LE + +readBigUInt64LE(offset: number): number + +从指定的`offset`处读取无符号的小端序64位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigUInt64LE(0)); +``` + +### readDoubleBE + +readDoubleBE(offset: number): number + +从指定`offset`处读取64位大端序双精度值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readDoubleBE(0)); +``` + +### readDoubleLE + +readDoubleLE(offset: number): number + +从指定`offset`处读取64位小端序双精度值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readDoubleLE(0)); +``` + +### readFloatBE + +readFloatBE(offset: number): number + +从指定`offset`处读取32位大端序浮点数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readFloatBE(0)); +``` + +### readFloatLE + +readFloatLE(offset: number): number + +从指定`offset`处读取32位小端序浮点数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readFloatLE(0)); +``` + +### readInt8 + +readInt8(offset: number): number + +从指定的`offset`处读取有符号的8位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([-1, 5]); +console.log(buf.readInt8(0)); // 打印: -1 +console.log(buf.readInt8(1)); // 打印: 5 +``` + +### readInt16BE + +readInt16BE(offset: number): number + +从指定的`offset`处读取有符号的大端序16位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = Buffer.from([0, 5]); +console.log(buf.readInt16BE(0)); // 打印: 5 +``` + +### readInt16LE + +readInt16LE(offset: number): number + +从指定的`offset`处读取有符号的小端序16位整数 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = Buffer.from([0, 5]); +console.log(buf.readInt16BE(0)); // 打印: 1280 +``` + +### readInt32BE + +readInt32BE(offset: number): number + +从指定的`offset`处读取有符号的大端序32位整数 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 0, 0, 5]); +console.log(buf.readInt32BE(0)); // 打印: 5 +``` + +### readInt32LE + +readInt32LE(offset: number): number + +从指定的`offset`处读取有符号的小端序32位整数 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 是 | 偏移量。默认值: 0。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 0, 0, 5]); +console.log(buf.readInt32LE(0)); // 打印: 83886080 +``` + +### readIntBE + +readIntBE(offset: number, byteLength: number): number + +从指定的`offset`处的buf读取byteLength个字节,并将结果解释为支持最高48位精度的大端序、二进制补码有符号值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 读取的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = Buffer.from("ab"); +let num = buf.readIntBE(0, 1); +console.log(num); // 97 +``` + + +### readIntLE + +readIntLE(offset: number, byteLength: number): number + +从指定的`offset`处的buf读取`byteLength`个字节,并将结果解释为支持最高48位精度的小端序、二进制补码有符号值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 读取的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readIntLE(0, 6).toString(16)); +``` + +### readUInt8 + +readUInt8(offset: number): number + +从`offset`处读取8位无符号整型数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, -2]); +console.log(buf.readUInt8(0)); +console.log(buf.readUInt8(1)); +``` + +### readUInt16BE + +readUInt16BE(offset: number): number + +从指定的`offset`处的buf读取无符号的大端序16位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56]); +console.log(buf.readUInt16BE(0).toString(16)); +console.log(buf.readUInt16BE(1).toString(16)); +``` + +### readUInt16LE + +readUInt16LE(offset: number): number + +从指定的`offset`处的buf读取无符号的小端序16位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56]); +console.log(buf.readUInt16LE(0).toString(16)); +console.log(buf.readUInt16LE(1).toString(16)); +``` + +### readUInt32BE + +readUInt32BE(offset: number): number + +从指定的`offset`处的buf读取无符号的大端序32位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); +console.log(buf.readUInt32BE(0).toString(16)); +``` + +### readUInt32LE + +readUInt32LE(offset: number): number + +从指定的`offset`处的buf读取无符号的小端序32位整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); +console.log(buf.readUInt32LE(0).toString(16)); +``` + +### readUIntBE + +readUIntBE(offset: number, byteLength: number): number + +从指定的`offset`处的buf读取`byteLength`个字节,并将结果解释为支持最高48位精度的无符号大端序整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 要读取的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readUIntBE(0, 6).toString(16)); +``` + +### readUIntLE + +readUIntLE(offset: number, byteLength: number): number + +从指定的`offset`处的buf读取`byteLength`个字节,并将结果解释为支持最高48位精度的无符号小端序整数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 要读取的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 读取出的内容。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readUIntLE(0, 6).toString(16)); +``` + +### subarray + +subarray(start?: number, end?: number): Buffer + +截取指定位置的`this`实例并返回。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| start | number | 否 | 截取开始位置。 默认值: 0。 | +| end | number | 否 | 截取结束位置(不包括在内)。 默认值: buf.length。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 新的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); + +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} +const buf2 = buf1.subarray(0, 3); +console.log(buf2.toString('ascii', 0, buf2.length)); +// 打印: abc +``` + +### swap16 + +swap16(): Buffer + +将`this`实例解释为无符号的16位整数数组,并就地交换字节顺序。 + +**系统能力:** SystemCapability.Utils.Lang + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 交换之后的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1); // 打印: + +buf1.swap16(); +console.log(buf1); // 打印: +``` + +### swap32 + +swap32(): Buffer + +将`this`实例解释为无符号的32位整数数组,并就地交换字节顺序 + +**系统能力:** SystemCapability.Utils.Lang + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 交换之后的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1); // 打印: + +buf1.swap32(); +console.log(buf1); // 打印: +``` + +### swap64 + +swap64(): Buffer + +将`this`实例解释为无符号的64位整数数组,并就地交换字节顺序 + +**系统能力:** SystemCapability.Utils.Lang + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 交换之后的Buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1); // 打印: +buf1.swap64(); +console.log(buf1); // 打印: +``` + +### toJSON + +toJSON(): Object + +将buf转为JSON并返回。 + +**系统能力:** SystemCapability.Utils.Lang + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Object | JSON对象。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); +let buf2 = buffer.from(buf1.toJSON()) +let json = JSON.stringify(buf2); +console.log(json); +// 打印: {"type":"Buffer","data":[1,2,3,4,5]} +``` + +### toString + +toString(encoding?: string, start?: number, end?: number): string + +将`this`实例中指定位置数据转成指定编码格式字符串并返回。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| encoding | string | 否 | 字符编码格式。 默认值: 'utf-8'。 | +| start | number | 否 | 开始位置。 默认值: 0。 | +| end | number | 否 | 结束位置。 默认值: buf.length。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string | 字符串。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} +console.log(buf1.toString('utf-8')); +// 打印: abcdefghijklmnopqrstuvwxyz +``` + +### values + +values(): IterableIterator<number> + +返回一个包含value的迭代器。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<number> | 迭代器。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('buffer'); +for (const value of buf.values()) { + console.log(value); +} +``` + +### write + +write(str: string, offset?: number, length?: number, encoding?: string): number + +从buf的offset偏移写入指定编码的字符串str,写入的字节长度为length + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| str | string | 是 | 要写入Buffer的字符串。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| length | number | 否 | 最大字节长度。 默认值: (buf.length - offset)。| +| encoding | BufferEncoding | 否 | 字符编码。 默认值: 'utf8'。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(256); +let len = buf.write('\u00bd + \u00bc = \u00be', 0); +console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); +// 打印: 12 bytes: ½ + ¼ = ¾ + +let buffer = Buffer.alloc(10); +let length = buffer.write('abcd', 8); +``` + +### writeBigInt64BE + +writeBigInt64BE(value: number, offset?: number): number + +从buf的offset偏移写入大端序的64位BigInt型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigInt64BE(0x0102030405060708n, 0); +``` + +### writeBigInt64LE + +writeBigInt64LE(value : number, offset? : number): number + +从buf的offset偏移写入小端序的64位BigInt型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigInt64LE(0x0102030405060708n, 0); +``` + +### writeBigUInt64BE + +writeBigUInt64BE(value : number, offset? : number): number + +从buf的offset偏移写入大端序的64位BigUInt型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigUInt64BE(0xdecafafecacefaden, 0); +``` + +### writeBigUInt64LE + +writeBigUInt64LE(value : number, offset? : number): number + +从buf的offset偏移写入小端序的64位BigUInt型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigUInt64LE(0xdecafafecacefaden, 0); +``` + +### writeDoubleBE + +writeDoubleBE(value : number, offset? : number): number + +从buf的offset偏移写入大端序的64位有符号双浮点型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeDoubleBE(123.456, 0); +``` + +### writeDoubleLE + +writeDoubleLE(value : number, offset? : number): number + +从buf的offset偏移写入小端序的64位有符号双浮点型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeDoubleLE(123.456, 0); +``` + +### writeFloatBE + +writeFloatBE(value : number, offset? : number): number + +从buf的offset偏移写入大端序的32位有符号浮点型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeFloatBE(0xcafebabe, 0); +``` + + +### writeFloatLE + +writeFloatLE(value : number, offset? : number): number + +从buf的offset偏移写入小端序的32位有符号浮点型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeFloatLE(0xcafebabe, 0); +``` + +### writeInt8 + +writeInt8(value : number, offset? : number): number + +从buf的offset偏移写入8位有符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt8(2, 0); +buf.writeInt8(-2, 1); +``` + + +### writeInt16BE + +writeInt16BE(value : number, offset? : number): number + +从buf的offset偏移写入大端序的16位有符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt16BE(0x0102, 0); +``` + + +### writeInt16LE + +writeInt16LE(value : number, offset : number): number + +从buf的offset偏移写入小端序的16位有符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt16LE(0x0304, 0); +``` + +### writeInt32BE + +writeInt32BE(value : number, offset : number): number + +从buf的offset偏移写入大端序的32位有符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeInt32BE(0x01020304, 0); +``` + + +### writeInt32LE + +writeInt32LE(value : number, offset : number): number + +从buf的offset偏移写入小端序的32位有符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeInt32LE(0x05060708, 0); +``` + +### writeIntBE + +writeIntBE(value : number, offset : number, byteLength : number): number + +从buf的offset偏移写入大端序的有符号value数据,value字节长度为byteLength + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 要写入的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeIntBE(0x1234567890ab, 0, 6); +``` + + +### writeIntLE + +writeIntLE(value : number, offset : number, byteLength : number): number + +从buf的offset偏移写入小端序的有符号value数据,value字节长度为byteLength + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 要写入的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeIntLE(0x1234567890ab, 0, 6); +``` + +### writeUInt8 + +writeUInt8(value : number, offset : number): number + +从buf的offset偏移写入8位无符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt8(0x3, 0); +buf.writeUInt8(0x4, 1); +buf.writeUInt8(0x23, 2); +buf.writeUInt8(0x42, 3); +``` + +### writeUInt16BE + +writeUInt16BE(value : number, offset : number): number + +从buf的offset偏移写入大端序的16位无符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt16BE(0xdead, 0); +buf.writeUInt16BE(0xbeef, 2); +``` + +### writeUInt16LE + +writeUInt16LE(value : number, offset : number): number + +从buf的offset偏移写入小端序的16位无符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt16LE(0xdead, 0); +buf.writeUInt16LE(0xbeef, 2); +``` + +### writeUInt32BE + +writeUInt32BE(value : number, offset : number): number + +从buf的offset偏移写入大端序的32位无符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数据。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt32BE(0xfeedface, 0); +``` + +### writeUInt32LE + +writeUInt32LE(value : number, offset : number): number + +从buf的offset偏移写入小端序的32位无符号整型数据value + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数字。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt32LE(0xfeedface, 0); +``` + +### writeUIntBE + +writeUIntBE(value : number, offset : number, byteLength : number): number + +从buf的offset偏移写入大端序的无符号value数据,value字节长度为byteLength + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数据。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 要写入的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeUIntBE(0x1234567890ab, 0, 6); +``` + +### writeUIntLE + +writeUIntLE(value : number, offset : number, byteLength : number): number + +从buf的offset偏移写入小端序的无符号value数据,value字节长度为byteLength + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 写入 buf 的数据。 | +| offset | number | 否 | 偏移量。 默认值: 0。 | +| byteLength | number | 否 | 要写入的字节数。 | + + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 写入的字节数。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeUIntLE(0x1234567890ab, 0, 6); +``` + +### transcode + +transcode(source : Buffer | Uint8Array, fromEnc : string, toEnc : string): Buffer + +将给定的Buffer或Uint8Array实例从一种字符编码重新编码为另一种 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| source | Buffer \| Uint8Array | 是 | 实例对象。 | +| fromEnc | string | 是 | 当前编码。 | +| toEnc | string | 是 | 目标编码。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Buffer | 根据当前编码转换成目标编码,并返回一个新的buffer实例。 | + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(50); +let newBuf = buf.transcode(buffer.from('€'), 'utf8', 'ascii'); +console.log(newBuf.toString('ascii')); +``` + +## Blob + +### 属性 + +**系统能力:** SystemCapability.Utils.Lang + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| size | number | 是 | 否 | Blob实例的总字节大小。 | +| type | string | 是 | 否 | Blob实例的内容类型。 | + +### constructor + +constructor(sources: string[] | ArrayBuffer[] | TypedArray[] | DataView[] | Blob[] , options: Object) + +Blob的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| sources | string[] \| ArrayBuffer[] \| TypedArray[] \| DataView[] \| Blob[] | 是 | Blob实例的数据源。 | +| options | Object | 否 | options:
- endings:'transparent'或'native'
- type:Blob内容类型 | + + +**示例:** + +```ts +import buffer from '@ohos.buffer'; + +let blob1 = new buffer.Blob(['a', 'b', 'c']); +let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); +``` + +### encode + +arrayBuffer(): Promise<ArrayBuffer> + +将Blob中的数据放入到ArrayBuffer中,并返回一个Promise。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** +| 类型 | 说明 | +| -------- | -------- | +| Promise<ArrayBuffer> | 返回包含Blob数据的ArrayBuffer的Promise。 | + +**示例:** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let pro = blob.arrayBuffer(); + pro.then(val => { + console.log(val) + }); + ``` +### slice + +slice(start?: number, end?: number, type?: string): Blob + +创建并返回一个复制原blob对象中start到end位置数据的新blob实例对象。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| start | number | 否 | 起始位置。 | +| end | number | 否 | 结束位置。 | +| type | string | 否 | 内容类型。 | + +**返回值:** +| 类型 | 说明 | +| -------- | -------- | +| Blob | 新的Blob实例对象。 | + +**示例:** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let blob2 = blob.slice(0, 2); + let blob3 = blob.slice(0, 2, "MIME"); + ``` + + ### text + +text(): Promise<string> + +返回一个Promise,该Promise中的值为UTF8编码类型的文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** +| 类型 | 说明 | +| -------- | -------- | +| Promise<string> | 包含以UTF8编码的文本的Promise。 | + +**示例:** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let pro = blob.text(); + pro.then(val => { + console.log(val) + }); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index ee49cd6790b2f25bf684f335c9bcdb203000eb48..f92370a7861bdb78dbcd0df1ae92e6eab04d1f38 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -24,7 +24,7 @@ | appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | 应用程序的配置信息 | | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | 是 | 否 | Ability的配置信息
通过传入GET_BUNDLE_WITH_ABILITIES获取 | | reqPermissions | Array\ | 是 | 否 | 应用运行时需向系统申请的权限集合
通过传入GET_BUNDLE_WITH_REQUESTED_PERMISSION获取 | -| reqPermissionDetails | Array\<[ReqPermissionDetail](#ReqPermissionDetail)> | 是 | 否 | 应用运行时需向系统申请的权限集合的详细信息
通过传入GET_BUNDLE_WITH_REQUESTED_PERMISSION获取 | +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | 是 | 否 | 应用运行时需向系统申请的权限集合的详细信息
通过传入GET_BUNDLE_WITH_REQUESTED_PERMISSION获取 | | vendor | string | 是 | 否 | 应用包的供应商 | | versionCode | number | 是 | 否 | 应用包的版本号 | | versionName | string | 是 | 否 | 应用包的版本文本描述信息 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index 71a3d1077b9c3a64ebcb40095eeb518baf508994..2a1eb5a9b7e34e472b584258e8014939910c785d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -2,18 +2,19 @@ -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** +> > 本模块首批接口从API version 7 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -配置文件中定义的权限详细信息 +配置文件中定义的快捷方式信息。 ## ShortcutWant -获取有关快捷方式将启动的功能和目标的信息 +快捷方式所指向的目标信息。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework @@ -25,7 +26,7 @@ ## ShortcutInfo -获取有关快捷方式将启动的功能和目标的信息 +快捷方式属性信息。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework diff --git a/zh-cn/application-dev/reference/apis/js-apis-camera.md b/zh-cn/application-dev/reference/apis/js-apis-camera.md index 3a2b408ffd04e192004645ca344a28c973edd663..610a016686600e2073147458dda2598c5e556fa6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -20,9 +20,9 @@ getCameraManager(context: Context, callback: AsyncCallback): voi **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------- | ---- | ---------------------------------- | -| context | Context | 是 | 应用上下文。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | ---------------------------- | +| context | Context | 是 | 应用上下文。 | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | 是 | 回调函数,用于获取相机管理器实例。 | **示例:** @@ -53,8 +53,8 @@ getCameraManager(context: Context): Promise **返回值:** -| 类型 | 说明 | -| ----------------------------------------- | ----------------------------------------- | +| 类型 | 说明 | +| ----------------------------------------- | ----------------------------------- | | Promise<[CameraManager](#cameramanager)\> | 使用Promise的方式获取一个相机管理器实例。 | **示例:** @@ -73,84 +73,78 @@ camera.getCameraManager(context).then((cameraManager) => { | 名称 | 值 | 说明 | | ------------------------- | ---- | ------------ | -| CAMERA_STATUS_APPEAR | 0 | 相机存在。 | -| CAMERA_STATUS_DISAPPEAR | 1 | 相机不存在。 | -| CAMERA_STATUS_AVAILABLE | 2 | 相机就绪。 | -| CAMERA_STATUS_UNAVAILABLE | 3 | 相机未就绪。 | +| CAMERA_STATUS_APPEAR | 0 | 新的相机出现。 | +| CAMERA_STATUS_DISAPPEAR | 1 | 相机被移除。 | +| CAMERA_STATUS_AVAILABLE | 2 | 相机可用。 | +| CAMERA_STATUS_UNAVAILABLE | 3 | 相机不可用。 | +## Profile -## CameraPosition - -枚举,相机方向。 +相机配置信息项。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| --------------------------- | ---- | ---------------- | -| CAMERA_POSITION_UNSPECIFIED | 0 | 未指定方向相机。 | -| CAMERA_POSITION_BACK | 1 | 后置相机。 | -| CAMERA_POSITION_FRONT | 2 | 前置相机。 | +| 名称 | 类型 | 只读 | 说明 | +| -------- | ----------------------------- |---- | ------------- | +| format | [CameraFormat](#cameraformat) | 是 | 输出格式。 | +| size | [Size](#size) | 是 | 分辨率。 | -## CameraType +## FrameRateRange -枚举,相机类型。 + 帧率范围。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ----------------------- | ---- | ---------------- | -| CAMERA_TYPE_UNSPECIFIED | 0 | 未指定相机类型。 | -| CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。 | -| CAMERA_TYPE_ULTRA_WIDE | 2 | 超级广角相机。 | -| CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。 | -| CAMERA_TYPE_TRUE_DEPTH | 4 | 深度相机。 | - +| 名称 | 类型 | 只读 | 说明 | +| ------------------------- | ------ | ---- | ------------------- | +| min | number | 是 | 最小速率,单位fps | +| max | number | 是 | 最大速率,单位fps | -## ConnectionType +## VideoProfile -枚举,相机连接类型。 +视频配置信息项。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ---------------------------- | ---- | ------------- | -| CAMERA_CONNECTION_BUILT_IN | 0 | 内置相机。 | -| CAMERA_CONNECTION_USB_PLUGIN | 1 | 外置USB相机。 | -| CAMERA_CONNECTION_REMOTE | 2 | 分布式相机。 | +| 名称 | 类型 | 只读 | 说明 | +| ------------------------- | ----------------------------------------- | --- |------------ | +| frameRateRanges | [FrameRateRange](#frameraterange) | 是 | 帧率。 | -## Size +## CameraOutputCapability -用于表示相机预览、照片、视频支持的尺寸大小。 +相机输出能力项。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ------ | ------ | ---- | ---- | ------------ | -| height | string | 是 | 是 | 图像的高度。 | -| width | number | 是 | 是 | 图像的宽度。 | +| 名称 | 类型 | 只读 | 说明 | +| ----------------------------- | -------------------------------------------------- | --- |------------------- | +| previewProfiles | Array<[Profile](#profile)\> | 是 | 支持的预览配置信息。 | +| photoProfiles | Array<[Profile](#profile)\> | 是 | 支持的拍照配置信息。 | +| videoProfiles | Array<[VideoProfile](#videoprofile)\> | 是 | 支持的录像配置信息。 | +| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | 支持的metadata流类型信息。| ## CameraManager 相机管理器类,使用前需要通过getCameraManager获取相机管理实例。 -### getCameras +### getSupportedCameras -getCameras(callback: AsyncCallback\>): void +getSupportedCameras(callback: AsyncCallback\>): void -异步获取设备支持的相机列表,通过注册回调函数获取结果。 +获取支持指定的相机设备对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback\> | 是 | 使用callback方式获取支持的相机列表。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback\> | 是 | 使用callback方式获取支持的相机列表。 | **示例:** ```js -cameraManager.getCameras((err, cameras) => { +cameraManager.getSupportedCameras((err, cameras) => { if (err) { console.error('Failed to get the cameras. ${err.message}'); return; @@ -159,866 +153,1025 @@ cameraManager.getCameras((err, cameras) => { }) ``` -### getCameras +### getSupportedCameras -getCameras(): Promise\> +getSupportedCameras(): Promise\> -异步获取设备支持的相机列表,通过Promise获取结果。 +获取支持指定的相机设备对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| ----------------------------------- | ----------------------------- | -| Promise\> | 使用promise获取支持相机列表。 | +| 类型 | 说明 | +| ----------------------------------------------- | ------------------------- | +| Promise\> | 使用promise获取支持相机列表。 | **示例:** ```js -cameraManager.getCameras().then((cameraArray) => { +cameraManager.getSupportedCameras().then((cameraArray) => { console.log('Promise returned with an array of supported cameras: ' + cameraArray.length); }) ``` -### createCameraInput - -createCameraInput(cameraId: string, callback: AsyncCallback): void +### getSupportedOutputCapability -使用相机ID异步创建CameraInput实例,通过注册回调函数获取结果。 +getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback): void -**需要权限:** ohos.permission.CAMERA +查询相机设备在模式下支持的输出能力,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| cameraId | string | 是 | 指定相机ID。 | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------------------- | -- | -------------------------- | +| camera | [CameraDevice](#cameraDevice) | 是 | CameraDevice对象。 | +| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | 是 | 使用callback方式获取相机输出能力。 | **示例:** ```js -cameraManager.createCameraInput(cameraId, (err, cameraInput) => { +cameraManager.getSupportedOutputCapability(cameraDevice, (err, cameras) => { if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); + console.error('Failed to get the cameras. ${err.message}'); return; } - console.log('Callback returned with the CameraInput instance.'); + console.log('Callback returned with an array of supported outputCapability: ' + cameras.length); }) ``` -### createCameraInput - -createCameraInput(cameraId: string): Promise +### getSupportedOutputCapability -使用相机ID异步创建CameraInput实例,通过Promise获取结果。 +getSupportedOutputCapability(camera:CameraDevice): Promise -**需要权限:** ohos.permission.CAMERA +查询相机设备在模式下支持的输出能力,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------ | -| cameraId | string | 是 | 指定相机ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------- | ---- | ---------- | +| camera | [CameraDevice](#cameraDevice) | 是 | CameraDevice对象。| **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ---------------------------------------- | -| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | +| 类型 | 说明 | +| -------------------------------------------------------------- | ----------------------------- | +| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | 使用Promise的方式获取结果,返回相机输出能力。 | + **示例:** ```js -cameraManager.createCameraInput(cameraId).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance'); +cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapability) => { + console.log('Promise returned with an array of supported outputCapability: ' + cameraArray.length); }) ``` -### createCameraInput - -createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void +### isCameraMuted -使用相机位置和相机类型异步创建CameraInput实例,通过注册回调函数获取结果。 +isCameraMuted(callback: AsyncCallback): void -**需要权限:** ohos.permission.CAMERA +查询相机是否被禁用,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| position | [CameraPosition](#cameraposition) | 是 | 相机位置。 | -| type | [CameraType](#cameratype) | 是 | 相机类型。 | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback | 是 | 回调函数,回调返回true即相机被禁用,否则为false。 | **示例:** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { +cameraManager.isCameraMuted((err, status) => { if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); + console.error('Failed to get the cameraMuted status. ${err.message}'); return; } - console.log('Callback returned with the CameraInput instance'); + console.log('Callback returned with cameraMuted status'); }) ``` -### createCameraInput - -createCameraInput(position: CameraPosition, type: CameraType): Promise +### isCameraMuted -使用相机位置和相机类型异步创建CameraInput实例,通过Promise获取结果。 +isCameraMuted(): Promise -**需要权限:** ohos.permission.CAMERA +查询相机是否被禁用,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | --------------------------------- | ---- | ---------- | -| position | [CameraPosition](#cameraposition) | 是 | 相机位置。 | -| type | [CameraType](#cameratype) | 是 | 相机类型。 | - **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ---------------------------------------- | -| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | +| 类型 | 说明 | +| ------------------------------------ | --------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回相机是否禁用的结果。 | + **示例:** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance.'); +cameraManager.isCameraMuted().then((status) => { + console.log('Promise returned with the status whether camera is muted.'); }) ``` -### on('cameraStatus') +### isCameraMuteSupported -on(type: 'cameraStatus', callback: AsyncCallback): void +isCameraMuteSupported(callback: AsyncCallback): void + +查询是否支持相机禁用,通过注册回调函数获取结果。 -监听相机的状态变化,通过注册回调函数获取相机的状态变化。 +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------------- | -| type | string | 是 | 监听事件,固定为'cameraStatus',即相机状态变化事件。 | -| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取相机状态变化信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback | 是 | 使用callback方式获取是否支持相机禁用的结果。 | **示例:** ```js -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { +cameraManager.isCameraMuteSupported((err, status) => { if (err) { - console.error('Failed to get cameraStatus callback. ${err.message}'); + console.error('Failed to get the cameraMuteSupported. ${err.message}'); return; } - console.log('camera : ' + cameraStatusInfo.camera.cameraId); - console.log('status: ' + cameraStatusInfo.status); + console.log('Callback returned with the status whether cameraMuteSupported.'); }) ``` -## Camera +### isCameraMuteSupported -调用[camera.getCameraManager](#cameragetcameramanager)后,将返回Camera实例,包括相机ID、位置、类型、连接类型等相机相关的元数据。 +isCameraMuteSupported(): Promise -**系统能力:** SystemCapability.Multimedia.Camera.Core。 +查询是否支持相机禁用,通过Promise获取结果。 -| 名称 | 类型 | 只读 | 说明 | -| -------------- | --------------------------------- | ---- | -------------- | -| cameraId | string | 是 | 相机ID。 | -| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。 | -| cameraType | [CameraType](#cameratype) | 是 | 相机类型。 | -| connectionType | [ConnectionType](#connectiontype) | 是 | 相机连接类型。 | +此接口为系统接口。 -**示例:** +**需要权限:** ohos.permission.CAMERA -```js -async function getCameraInfo("cameraId") { - var cameraManager = await camera.getCameraManager(context); - var cameras = await cameraManager.getCameras(); - var cameraObj = cameras[0]; - var cameraId = cameraObj.cameraId; - var cameraPosition = cameraObj.cameraPosition; - var cameraType = cameraObj.cameraType; - var connectionType = cameraObj.connectionType; -} -``` +**系统能力:** SystemCapability.Multimedia.Camera.Core -## CameraStatusInfo +**返回值:** -相机管理器回调返回的接口实例,表示相机状态信息。 +| 类型 | 说明 | +| --------------------- | ----------------------------- | +| Promise | 使用Promise的方式获取结果,返回是否支持相机禁用的结果。 | -**系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 类型 | 说明 | -| ------ | ----------------------------- | ---------- | -| camera | [Camera](#camera) | 相机信息。 | -| status | [CameraStatus](#camerastatus) | 相机状态。 | +**示例:** +```js +cameraManager.isCameraMuteSupported().then((status) => { + console.log('Promise returned with the status whether cameraMuteSupported.'); +}) +``` -## CameraInput +### muteCamera -相机输入类。在使用该类的方法前,需要先构建一个CameraInput实例。 +muteCamera(mute:boolean, callback: AsyncCallback): void -### getCameraId +禁用相机,通过注册回调函数获取结果。 -getCameraId(callback: AsyncCallback\): void +此接口为系统接口。 -异步获取该CameraInput实例的相机ID,通过注册回调函数获取结果。 +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback | 是 | 回调函数,用于获取相机ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------------------ | +| mute | boolean | 是 | 是否禁用相机。 | +| callback | AsyncCallback | 是 | 使用callback方式获取相机禁用的结果。 | **示例:** ```js -cameraInput.getCameraId((err, cameraId) => { +cameraManager.muteCamera(isMuted, (err) => { if (err) { - console.error('Failed to get the camera ID. ${err.message}'); + console.error('Failed to mute the camera. ${err.message}'); return; } - console.log('Callback returned with the camera ID: ' + cameraId); + console.log('Callback returned with the muteCamera.'); }) ``` -### getCameraId +### muteCamera + +muteCamera(mute:boolean): Promise -getCameraId(): Promise +禁用相机,通过Promise获取结果。 -异步获取该CameraInput实例的相机ID,通过Promise获取结果。 +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------ | +| mute | boolean | 是 | 是否禁用相机。 | + **返回值:** -| 类型 | 说明 | -| ---------------- | ----------------------------- | -| Promise | 使用Promise的方式获取相机ID。 | +| 类型 | 说明 | +| ----------------------------------- | ----------------------------- | +| Promise | 使用Promise的方式获取结果,返回是否禁用相机的结果。 | + **示例:** -```js -cameraInput.getCameraId().then((cameraId) => { - console.log('Promise returned with the camera ID:' + cameraId); +```js +cameraManager.muteCamera(isMuted).then(() => { + console.log('Promise returned muteCamera.'); }) ``` +### createCameraInput -### hasFlash +createCameraInput(camera: CameraDevice, callback: AsyncCallback): void -hasFlash(callback: AsyncCallback): void +使用CameraDevice对象异步创建CameraInput实例,通过注册回调函数获取结果。 -判断设备是否支持闪光灯,通过注册回调函数获取结果。 +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback | 是 | 回调函数,返回true表示设备支持闪光灯。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | --------------------------------- | +| camera | [CameraDevice](#cameraDevice) | 是 | CameraDevice对象。 | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | **示例:** ```js -cameraInput.hasFlash((err, status) => { +cameraManager.createCameraInput(camera, (err, cameraInput) => { if (err) { - console.error('Failed to check whether the device has flash light. ${err.message}'); + console.error('Failed to create the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with flash light support status: ' + status); + console.log('Callback returned with the CameraInput instance.'); }) ``` -### hasFlash +### createCameraInput -hasFlash(): Promise +createCameraInput(camera: CameraDevice): Promise + +使用CameraDevice对象异步创建CameraInput实例,通过Promise获取结果。 -判断设备是否支持闪光灯,通过Promise获取结果。 +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------- | ---- | ---------- | +| camera | [CameraDevice](#cameraDevice) | 是 | CameraDevice对象。 | + **返回值:** -| 类型 | 说明 | -| ----------------- | ------------------------------------------------------- | -| Promise | 使用Promise的方式获取结果,返回true表示设备支持闪光灯。 | +| 类型 | 说明 | +| ------------------------------------- | ------------------------------------ | +| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | **示例:** ```js -cameraInput.hasFlash().then((status) => { - console.log('Promise returned with the flash light support status:' + status); +cameraManager.createCameraInput(camera).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` -### isFlashModeSupported +### createCameraInput -isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void +createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void + +根据相机位置和类型创建CameraInput实例,通过注册回调函数获取结果。 -判断设备是否支持指定闪光灯模式,通过注册回调函数获取结果。 +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------------------------------------- | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | -| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | --------------------------------- | +| position | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| type | [CameraType](#cameratype) | 是 | 相机类型。 | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 | **示例:** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { - console.error('Failed to check whether the flash mode is supported. ${err.message}'); + console.error('Failed to create the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with the flash mode support status: ' + status); + console.log('Callback returned with the CameraInput instance'); }) ``` -### isFlashModeSupported +### createCameraInput -isFlashModeSupported(flashMode: FlashMode): Promise +createCameraInput(position: CameraPosition, type:CameraType ): Promise + +根据相机位置和类型创建CameraInput实例,通过Promise获取结果。 -判断设备是否支持指定闪光灯模式,通过Promise获取结果。 +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------- | ---- | ------------ | +| position | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| type | [CameraType](#cameratype) | 是 | 相机类型。 | **返回值:** -| 类型 | 说明 | -| ----------------- | ------------------------------------------------------------ | -| Promise | 使用Promise的方式获取结果,返回true表示设备支持该闪光灯模式。 | +| 类型 | 说明 | +| ------------------------------------- | ------------------------------------ | +| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | **示例:** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { - console.log('Promise returned with flash mode support status.' + status); +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` -### setFlashMode - -setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void - -设置闪光灯模式,通过注册回调函数获取结果。 +### createPreviewOutput -进行设置之前,需要先检查: +createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 -2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 +创建预览输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ------------------------ | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | ------------------------------- | +| profile | [Profile](#profile) | 是 | 支持的预览配置信息。 | +| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)或者[ImageReceiver](js-apis-image.md#imagereceiver9)组件获取的SurfaceID。| +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。| **示例:** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { +cameraManager.createPreviewOutput(profile, surfaceId, (err, previewoutput) => { if (err) { - console.error('Failed to set the flash mode ${err.message}'); + console.error('Failed to gcreate previewOutput. ${err.message}'); return; } - console.log('Callback returned with the successful execution of setFlashMode.'); + console.log('Callback returned with previewOutput created.'); }) ``` -### setFlashMode - -setFlashMode(flashMode: FlashMode): Promise - -设置闪光灯模式,通过Promise获取结果。 +### createPreviewOutput -进行设置之前,需要先检查: +createPreviewOutput(profile: Profile, surfaceId: string): Promise -1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 -2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 +创建预览输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------| ---- | ----------------- | +| profile | [Profile](#profile) | 是 | 支持的预览配置信息。 | +| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)或者[ImageReceiver](js-apis-image.md#imagereceiver9)组件获取的SurfaceID。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ---------------------------------------- | ---------------------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取PreviewOutput的实例。 | **示例:** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFlashMode.'); +cameraManager.createPreviewOutput(profile, survaceId).then((previewoutput) => { + console.log('Promise returned with previewOutput created.'); }) ``` -### getFlashMode +### createDeferredPreviewOutput -getFlashMode(callback: AsyncCallback): void +createDeferredPreviewOutput(profile: Profile, callback: AsyncCallback): void -获取当前设备的闪光灯模式,通过注册回调函数获取结果。 +尚未获取surfaceID时创建预览输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<[FlashMode](#flashmode)\> | 是 | 回调函数,用于获取当前设备的闪光灯模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | --------------------------------- | +| profile | [Profile](#profile) | 是 | 支持的预览配置信息。 | +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。 | **示例:** ```js -cameraInput.getFlashMode((err, flashMode) => { +cameraManager.createDeferredPreviewOutput(profile, (err, previewoutput) => { if (err) { - console.error('Failed to get the flash mode ${err.message}'); + console.error('Failed to create deferredPreviewOutput. ${err.message}'); return; } - console.log('Callback returned with current flash mode: ' + flashMode); + console.log('Callback returned with deferredPreviewOutput created.'); }) ``` -### getFlashMode +### createDeferredPreviewOutput -getFlashMode(): Promise +createDeferredPreviewOutput(profile: Profile): Promise -获取当前设备的闪光灯模式,通过Promise获取结果。 +尚未获取surfaceID时创建预览输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------| ---- | ---------- | +| profile | [Profile](#profile) | 是 | 支持的预览配置信息。 | + **返回值:** -| 类型 | 说明 | -| --------------------------------- | --------------------------------------- | -| Promise<[FlashMode](#flashmode)\> | 使用Promise的方式获取当前的闪光灯模式。 | +| 类型 | 说明 | +| ----------------------------------------- | --------------------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取PreviewOutput的实例。 | **示例:** ```js -cameraInput.getFlashMode().then((flashMode) => { - console.log('Promise returned with current flash mode : ' + flashMode); +cameraManager.createDeferredPreviewOutput(profile).then((previewoutput) => { + console.log('Promise returned with DefeerredPreviewOutput created.'); }) ``` -### isFocusModeSupported +### createPhotoOutput -isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void +createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -判断设备是否支持指定的焦距模式,通过注册回调函数获取结果。 +创建拍照输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | -| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| profile | [Profile](#profile) | 是 | 支持的拍照配置信息。 | +| surfaceId| string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的SurfaceID。| +| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | 是 | 回调函数,用于获取PhotoOutput实例。 | **示例:** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { +cameraManager.createPhotoOutput(profile, surfaceId, (err, photooutput) => { if (err) { - console.error('Failed to check whether the focus mode is supported. ${err.message}'); + console.error('Failed to create photoOutput. ${err.message}'); return; } - console.log('Callback returned with the focus mode support status: ' + status); + console.log('Callback returned with photoOutput created.'); }) ``` -### isFocusModeSupported +### createPhotoOutput -isFocusModeSupported(afMode: FocusMode): Promise +createPhotoOutput(profile: Profile, surfaceId: string): Promise -判断设备是否支持指定的焦距模式,通过Promise获取结果。 +创建拍照输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------| ---- | ----------- | +| profile | [Profile](#profile) | 是 | 支持的拍照配置信息。 | +| surfaceId| string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的SurfaceID。| **返回值:** -| 类型 | 说明 | -| ----------------- | ----------------------------------------------------------- | -| Promise | 使用Promise的方式获取结果,返回true表示设备支持该焦距模式。 | +| 类型 | 说明 | +| ------------------------------------- | -------------------------------------- | +| Promise<[PhotoOutput](#photooutput)\> | 使用Promise的方式获取PhotoOutput的实例。 | **示例:** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { - console.log('Promise returned with focus mode support status.' + status); +cameraManager.createPhotoOutput(profile, surfaceId).then((photooutput) => { + console.log('Promise returned with photoOutput created.'); }) ``` -### setFocusMode - -setFocusMode(afMode: FocusMode, callback: AsyncCallback): void +### createVideoOutput -设置焦距模式,通过注册回调函数获取结果。 +createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void -进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 +创建录像输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | ------------------------ | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ------------------------------ | +| profile | [VideoProfile](#videoprofile) | 是 | 支持的录像配置信息。 | +| surfaceId| string | 是 | 从[VideoRecorder](js-apis-media.md#videorecorder9)获取的SurfaceID。| +| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 | **示例:** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { +cameraManager.createVideoOutput(profile, surfaceId, (err, videooutput) => { if (err) { - console.error('Failed to set the focus mode ${err.message}'); + console.error('Failed to create videoOutput. ${err.message}'); return; } - console.log('Callback returned with the successful execution of setFocusMode.'); + console.log('Callback returned with an array of supported outputCapability: ' + cameras.length); }) ``` -### setFocusMode - -setFocusMode(afMode: FocusMode): Promise +### createVideoOutput -设置焦距模式,通过Promise获取结果。 +createVideoOutput(profile: VideoProfile, surfaceId: string): Promise -进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 +创建录像输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------| ---- | ---------- | +| profile | [VideoProfile](#videoprofile) | 是 | 支持的录像配置信息。 | +| surfaceId| string | 是 | 从[VideoRecorder](js-apis-media.md#videorecorder9)获取的SurfaceID。| **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ------------------------------------- | -------------------------------------- | +| Promise<[VideoOutput](#videooutput)\> | 使用Promise的方式获取videoOutput的实例。 | **示例:** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFocusMode.'); +cameraManager.createVideoOutput(profile, surfaceId).then((videooutput) => { + console.log('Promise returned with videoOutput created.'); }) ``` -### getFocusMode +### createMetadataOutput -getFocusMode(callback: AsyncCallback): void +createMetadataOutput(metadataObjectTypes: Array, callback: AsyncCallback): void -获取当前设备的焦距模式,通过注册回调函数获取结果。 +创建metadata流输出对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback<[FocusMode](#focusmode)\> | 是 | 回调函数,用于获取当前设备的焦距模式。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------------- | -------------------------------------------------- | --- | ---------------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型。 | +| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | 是 | 回调函数,用于获取MetadataOutput实例。 | **示例:** ```js -cameraInput.getFocusMode((err, afMode) => { +cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataoutput) => { if (err) { - console.error('Failed to get the focus mode ${err.message}'); + console.error('Failed to create metadataOutput. ${err.message}'); return; } - console.log('Callback returned with current focus mode: ' + afMode); + console.log('Callback returned with metadataOutput created.'); }) ``` -### getFocusMode +### createMetadataOutput -getFocusMode(): Promise +createMetadataOutput(metadataObjectTypes: Array): Promise -获取当前设备的焦距模式,通过Promise获取结果。 +创建metadata流输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------------------- | -------------------------------------------------- | --- | -------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型。 | + **返回值:** -| 类型 | 说明 | -| ------------------- | ------------------------------------- | -| Promise | 使用Promise的方式获取当前的焦距模式。 | +| 类型 | 说明 | +| ------------------------------------------ | ----------------------------------------- | +| Promise<[MetadataOutput](#metadataoutput)\> | 使用Promise的方式获取MetadataOutput的实例。 | **示例:** ```js -cameraInput.getFocusMode().then((afMode) => { - console.log('Promise returned with current focus mode : ' + afMode); +cameraManager.createMetadataOutput(metadataObjectTypes).then((metadataoutput) => { + console.log('Promise returned with metadataOutput created.'); }) ``` -### getZoomRatioRange +### createCaptureSession -getZoomRatioRange\(callback: AsyncCallback\>\): void +createCaptureSession(callback: AsyncCallback): void -获取可变焦距比范围,通过注册回调函数获取结果。 +创建CaptureSession实例,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------ | ---- | ------------------------ | -| callback | AsyncCallback\> | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------------------- | ----------------------------------------- | ----------- | ---------------------------- | +| callback | AsyncCallback<[CaptureSession](#capturesession)\> | 是 | 回调函数,用于获取拍照会话实例。 | **示例:** ```js -cameraInput.getZoomRatioRange((err, zoomRatioRange) => { +cameraManager.createCaptureSession((err, capturesession) => { if (err) { - console.error('Failed to get the zoom ratio range. ${err.message}'); + console.error('Failed to create captureSession. ${err.message}'); return; } - console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length); + console.log('Callback returned with captureSession created.'); }) ``` -### getZoomRatioRange +### createCaptureSession -getZoomRatioRange\(\): Promise\> +createCaptureSession(): Promise -获取可变焦距比范围,通过Promise获取结果。 +创建CaptureSession实例,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| ------------------------ | ------------------------------------------- | -| Promise\> | 使用Promise的方式获取当前的可变焦距比范围。 | +| 类型 | 说明 | +| ------------------------------------------- | ---------------------------------------- | +| Promise<[CaptureSession](#capturesession)\> | 使用Promise的方式获取CaptureSession的实例。 | **示例:** ```js -cameraInput.getZoomRatioRange().then((zoomRatioRange) => { - console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); +cameraManager.createCaptureSession().then((capturesession) => { + console.log('Promise returned with captureSession created.'); }) ``` -### setZoomRatio +### on('cameraStatus') -setZoomRatio(zoomRatio: number, callback: AsyncCallback): void +on(type: 'cameraStatus', callback: AsyncCallback): void -设置可变焦距比,通过注册回调函数获取结果。 +镜头状态回调,通过注册回调函数获取相机的状态变化。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | -------------------- | ---- | ------------------------ | -| zoomRatio | number | 是 | 可变焦距比。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | --------- | +| type | string | 是 | 监听事件,固定为'cameraStatus',即镜头状态变化事件。 | +| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取镜头状态变化信息。 | **示例:** ```js -cameraInput.setZoomRatio(1, (err) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { if (err) { - console.error('Failed to set the zoom ratio value ${err.message}'); + console.error('Failed to get cameraStatus callback. ${err.message}'); return; } - console.log('Callback returned with the successful execution of setZoomRatio.'); + console.log('camera : ' + cameraStatusInfo.camera.cameraId); + console.log('status: ' + cameraStatusInfo.status); }) ``` -### setZoomRatio +### on('cameraMute') -setZoomRatio(zoomRatio: number): Promise +on(type: 'cameraMute', callback: AsyncCallback): void -设置可变焦距比,通过Promise获取结果。 +监听相机禁用的状态变化,通过注册回调函数获取相机的状态变化。 + +此接口为系统接口。 + +**需要权限:** ohos.permission.CAMERA **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ------------ | -| zoomRatio | number | 是 | 可变焦距比。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ------------------------------- | +| type | string | 是 | 监听事件,固定为'cameraMute',即相机状禁用态变化事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取相机是否禁用。 | -**返回值:** +**示例:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +```js +cameraManager.on('cameraMute', (err, status) => { + if (err) { + console.error('Failed to get cameraMute callback. ${err.message}'); + return; + } + console.log('status: ' + status); +}) +``` + +## CameraStatusInfo + +相机管理器回调返回的接口实例,表示相机状态信息。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 类型 | 说明 | +| ------ | ----------------------------- | ---------- | +| camera | [CameraDevice](#CameraDevice) | 相机信息。 | +| status | [CameraStatus](#camerastatus) | 相机状态。 | + +## CameraPosition + +枚举,相机位置。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| --------------------------- | ---- | -------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | 相机位置未指定。 | +| CAMERA_POSITION_BACK | 1 | 后置相机。 | +| CAMERA_POSITION_FRONT | 2 | 前置相机。 | + +## CameraType + +枚举,相机类型。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ----------------------- | ---- | -------------- | +| CAMERA_TYPE_UNSPECIFIED | 0 | 相机类型未指定。 | +| CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。 | +| CAMERA_TYPE_ULTRA_WIDE | 2 | 超广角相机。 | +| CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。 | +| CAMERA_TYPE_TRUE_DEPTH | 4 | 带景深信息的相机。 | + +## ConnectionType + +枚举,相机连接类型。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ---------------------------- | ---- | ------------- | +| CAMERA_CONNECTION_BUILT_IN | 0 | 内置相机。 | +| CAMERA_CONNECTION_USB_PLUGIN | 1 | USB连接的相机。 | +| CAMERA_CONNECTION_REMOTE | 2 | 远程连接的相机。 | + +## CameraDevice + +相机设备信息。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core。 + +| 名称 | 类型 | 只读 | 说明 | +| -------------- | --------------------------------- | ---- | ---------- | +| cameraId | string | 是 | CameraDevice对象| +| cameraPosition | [CameraPosition](#cameraposition) | 是 | 相机位置。 | +| cameraType | [CameraType](#cameratype) | 是 | 相机类型。 | +| connectionType | [ConnectionType](#connectiontype) | 是 | 相机连接类型。 | **示例:** ```js -cameraInput.setZoomRatio(1).then(() => { - console.log('Promise returned with the successful execution of setZoomRatio.'); -}) +async function getCameraInfo("cameraId") { + var cameraManager = await camera.getCameraManager(context); + var cameras = await cameraManager.getSupportedCameras(); + var cameraObj = cameras[0]; + var cameraId = cameraObj.cameraId; + var cameraPosition = cameraObj.cameraPosition; + var cameraType = cameraObj.cameraType; + var connectionType = cameraObj.connectionType; +} ``` -### getZoomRatio +## Size -getZoomRatio(callback: AsyncCallback): void +枚举,输出能力查询。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ------------ | +| height | number | 是 | 是 | 图像尺寸高(像素)。 | +| width | number | 是 | 是 | 图像尺寸宽(像素)。 | + +## Point + +枚举,点坐标用于对焦、曝光配置。 -获取当前的可变焦距比,通过注册回调函数获取结果。 +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------ | +| x | number | 是 | 点的x坐标。 | +| y | number | 是 | 点的y坐标。 | + +## CameraFormat + +枚举,输出格式。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 默认值 | 说明 | +| ----------------------- | --------- | ------------ | +| CAMERA_FORMAT_YUV_420_SP| 1003 | YUV 420 SP格式的图片。 | +| CAMERA_FORMAT_JPEG | 2000 | JPEG格式的图片。 | + +## CameraInput + +会话中[CaptureSession](#capturesession)使用的相机信息。 + +### open + +open\(callback: AsyncCallback\): void + +打开相机,通过注册回调函数获取状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -cameraInput.getZoomRatio((err, zoomRatio) => { +cameraInput.open((err) => { if (err) { - console.error('Failed to get the zoom ratio ${err.message}'); + console.error('Failed to open the camera. ${err.message}'); return; } - console.log('Callback returned with current zoom ratio: ' + zoomRatio); + console.log('Callback returned with camera opened.'); }) ``` -### getZoomRatio +### open -getZoomRatio(): Promise +open(): Promise -获取当前的可变焦距比,通过Promise获取结果。 +打开相机,通过Promise获取相机的状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| ---------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -cameraInput.getZoomRatio().then((zoomRatio) => { - console.log('Promise returned with current zoom ratio : ' + zoomRatio); +cameraInput.open().then(() => { + console.log('Promise returned with camera opened.'); }) ``` -### release +### close -release\(callback: AsyncCallback\): void +close\(callback: AsyncCallback\): void -释放相机实例,通过注册回调函数获取结果。 +关闭相机,通过注册回调函数获取状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -cameraInput.release((err) => { +cameraInput.close((err) => { if (err) { - console.error('Failed to release the CameraInput instance ${err.message}'); + console.error('Failed to close the cameras. ${err.message}'); return; } - console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); -}); + console.log('Callback returned with camera closed.'); +}) ``` -### release +### close -release(): Promise +close(): Promise -释放相机实例,通过Promise获取结果。 +关闭相机,通过Promise获取状态。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -cameraInput.release().then(() => { - console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); +cameraInput.close().then(() => { + console.log('Promise returned with camera closed.'); }) ``` -### on('focusStateChange') +### release -on(type: 'focusStateChange', callback: AsyncCallback): void +release\(callback: AsyncCallback\): void -监听焦距的状态变化,通过注册回调函数获取结果。 +释放资源,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------- | :--- | :------------------------------------------------------- | -| type | string | 是 | 监听事件,固定为'focusStateChange',即焦距状态变化事件。 | -| callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -cameraInput.on('focusStateChange', (focusState) => { - console.log('Focus state : ' + focusState); +cameraInput.release((err) => { + if (err) { + console.error('Failed to release the CameraInput instance ${err.message}'); + return; + } + console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); +}); +``` + +### release + +release(): Promise + +释放资源,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +cameraInput.release().then(() => { + console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); }) ``` @@ -1032,10 +1185,10 @@ on(type: 'error', callback: ErrorCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------------------- | :--- | :----------------------------------------------- | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------- | ---- | ------------------------------------------- | | type | string | 是 | 监听事件,固定为'error',即CameraInput错误事件。 | -| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | 是 | 回调函数,用于获取结果。 | +| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1045,24 +1198,29 @@ cameraInput.on('error', (cameraInputError) => { }) ``` -## CameraInputErrorCode +## CameraInputErrorCode -枚举,CameraInput的错误码。 +枚举,[CameraInput](#camerainput)错误类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +| 名称 | 值 | 说明 | +| ------------------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_NO_PERMISSION | 0 | 没有权限。 | +| ERROR_DEVICE_PREEMPTED | 1 | 相机被抢占。 | +| ERROR_DEVICE_DISCONNECTED | 2 | 相机断开连接。 | +| ERROR_DEVICE_IN_USE | 3 | 相机正在使用。 | +| ERROR_DRIVER_ERROR | 4 | 驱动错误。 | -## CameraInputError +## CameraInputError -CameraInput错误对象。 +[CameraInput](#camerainput)错误码。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------------- | -------------------------- | +| 名称 | 类型 | 说明 | +| ---- | --------------------------------------------- | --------------------- | | code | [CameraInputErrorCode](#camerainputerrorcode) | CameraInput中的错误码。 | @@ -1072,96 +1230,78 @@ CameraInput错误对象。 **系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 值 | 说明 | -| ---------------------- | ---- | ------------ | +| 名称 | 值 | 说明 | +| ---------------------- | ---- | ---------- | | FLASH_MODE_CLOSE | 0 | 闪光灯关闭。 | -| FLASH_MODE_OPEN | 1 | 闪光灯开启。 | +| FLASH_MODE_OPEN | 1 | 闪光灯打开。 | | FLASH_MODE_AUTO | 2 | 自动闪光灯。 | | FLASH_MODE_ALWAYS_OPEN | 3 | 闪光灯常亮。 | -## FocusMode +## ExposureMode -枚举,焦距模式。 +枚举,曝光模式。 **系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 值 | 说明 | -| -------------------------- | ---- | ------------------ | -| FOCUS_MODE_MANUAL | 0 | 手动变焦模式。 | -| FOCUS_MODE_CONTINUOUS_AUTO | 1 | 连续自动变焦模式。 | -| FOCUS_MODE_AUTO | 2 | 自动变焦模式。 | -| FOCUS_MODE_LOCKED | 3 | 定焦模式。 | +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | ----------- | +| EXPOSURE_MODE_LOCKED | 0 | 锁定曝光模式。 | +| EXPOSURE_MODE_AUTO | 1 | 自动曝光模式。 | +| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | 连续自动曝光。 | -## FocusState +## FocusMode -枚举,焦距状态。 +枚举,焦距模式。 **系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 值 | 说明 | -| --------------------- | ---- | ------------ | -| FOCUS_STATE_SCAN | 0 | 扫描状态。 | -| FOCUS_STATE_FOCUSED | 1 | 相机已对焦。 | -| FOCUS_STATE_UNFOCUSED | 2 | 相机未对焦。 | - -## camera.createCaptureSession - -createCaptureSession\(context: Context, callback: AsyncCallback\): void - -获取CaptureSession实例,通过注册回调函数获取结果。 +| 名称 | 值 | 说明 | +| -------------------------- | ---- | ------------ | +| FOCUS_MODE_MANUAL | 0 | 手动对焦。 | +| FOCUS_MODE_CONTINUOUS_AUTO | 1 | 连续自动对焦。 | +| FOCUS_MODE_AUTO | 2 | 自动变焦。 | +| FOCUS_MODE_LOCKED | 3 | 对焦锁定。 | -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------- | ---- | -------------------------------------- | -| context | Context | 是 | 应用上下文。 | -| callback | AsyncCallback<[CaptureSession](#capturesession)\> | 是 | 回调函数,用于获取CaptureSession实例。 | - -**示例:** +## FocusState -```js -camera.createCaptureSession((context), (err, captureSession) => { - if (err) { - console.error('Failed to create the CaptureSession instance. ${err.message}'); - return; - } - console.log('Callback returned with the CaptureSession instance.' + captureSession); -}); -``` +枚举,焦距状态。 -## camera.createCaptureSession +**系统能力:** SystemCapability.Multimedia.Camera.Core。 -createCaptureSession(context: Context\): Promise; +| 名称 | 值 | 说明 | +| --------------------- | ---- | --------- | +| FOCUS_STATE_SCAN | 0 | 触发对焦。 | +| FOCUS_STATE_FOCUSED | 1 | 对焦成功。 | +| FOCUS_STATE_UNFOCUSED | 2 | 未完成对焦。 | -获取CaptureSession实例,通过Promise获取结果。 +## ExposureState -**系统能力:** SystemCapability.Multimedia.Camera.Core +枚举,曝光状态。 -**参数:** +**系统能力:** SystemCapability.Multimedia.Camera.Core。 -| 名称 | 类型 | 必填 | 说明 | -| ------- | ------- | ---- | ------------ | -| context | Context | 是 | 应用上下文。 | +| 名称 | 值 | 说明 | +| ------------------------- | ---- | -------- | +| EXPOSURE_STATE_SCAN | 0 | 曝光中。 | +| EXPOSURE_STATE_CONVERGED | 1 | 曝光收敛。 | -**返回值:** +## VideoStabilizationMode -| 类型 | 说明 | -| ------------------------------------------- | ----------------------------------------- | -| Promise<[CaptureSession](#capturesession)\> | 使用Promise的方式获取CaptureSession实例。 | +枚举,视频防抖模式。 -**示例:** +**系统能力:** SystemCapability.Multimedia.Camera.Core。 -```js -camera.createCaptureSession(context).then((captureSession) => { - console.log('Promise returned with the CaptureSession instance'); -}) -``` +| 名称 | 值 | 说明 | +| --------- | ---- | ------------ | +| OFF | 0 | 关闭视频防抖功能。 | +| LOW | 1 | 使用基础防抖算法。 | +| MIDDLE | 2 | 使用防抖效果一般的防抖算法,防抖效果优于LOW类型。 | +| HIGH | 3 | 使用防抖效果最好的防抖算法,防抖效果优于MIDDLE类型。 | +| AUTO | 4 | 自动进行选择。 | ## CaptureSession -拍照会话类。 +拍照会话类,保存一次相机运行所需要的所有资源[CameraInput](#camerainput)、[CameraOutput](#cameraoutput),并向相机设备申请完成相机功能(录像,拍照)。 ### beginConfig @@ -1173,8 +1313,8 @@ beginConfig\(callback: AsyncCallback\): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1199,8 +1339,8 @@ beginConfig\(\): Promise **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | @@ -1216,14 +1356,14 @@ captureSession.beginConfig().then(() => { commitConfig\(callback: AsyncCallback\): void -提交会话配置,通过注册回调函数获取结果。 +提交配置信息,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1242,14 +1382,14 @@ captureSession.commitConfig((err) => { commitConfig\(\): Promise -提交会话配置,通过Promise获取结果。 +提交配置信息,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1260,546 +1400,529 @@ captureSession.commitConfig().then(() => { }) ``` -### addInput +### canAddInput -addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void +canAddInput(cameraInput: CameraInput, callback: AsyncCallback): void -在当前会话中,添加一个CameraInput实例,通过注册回调函数获取结果。 +判断是否可以添加[CameraInput](#camerainput)到会话中,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.addInput(cameraInput, (err) => { +captureSession.canAddInput(cameraInput, (err, status) => { if (err) { - console.error('Failed to add the CameraInput instance. ${err.message}'); + console.error('Can not add cameraInput. ${err.message}'); return; } - console.log('Callback invoked to indicate that the CameraInput instance is added.'); -}); + console.log('Callback returned with cameraInput can added.'); +}) ``` -### addInput +### canAddInput -addInput\(cameraInput: CameraInput\): Promise +canAddInput(cameraInput: CameraInput): Promise -在当前会话中,添加一个CameraInput实例,通过Promise获取结果。 +判断是否可以添加[CameraInput](#camerainput)到会话中,通过注Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | -------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.addInput(cameraInput).then(() => { - console.log('Promise used to indicate that the CameraInput instance is added.'); +captureSession.canAddInput(cameraInput).then(() => { + console.log('Promise returned with cameraInput can added.'); }) ``` -### addOutput +### addInput -addOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -在当前会话中,添加一个PreviewOutput实例,通过注册回调函数获取结果。 +把[CameraInput](#camerainput)加入到会话,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的PreviewOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.addOutput(previewOutput, (err) => { +captureSession.addInput(cameraInput, (err) => { if (err) { - console.error('Failed to add the PreviewOutput instance ${err.message}'); + console.error('Failed to add the CameraInput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); + console.log('Callback invoked to indicate that the CameraInput instance is added.'); }); ``` -### addOutput +### addInput -addOutput\(previewOutput: PreviewOutput\): Promise +addInput\(cameraInput: CameraInput\): Promise -在当前会话中,添加一个PreviewOutput实例,通过Promise获取结果。 +把[CameraInput](#camerainput)加入到会话,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的PreviewOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.addOutput(previewOutput).then(() => { - console.log('Promise used to indicate that the PreviewOutput instance is added.'); +captureSession.addInput(cameraInput).then(() => { + console.log('Promise used to indicate that the CameraInput instance is added.'); }) ``` -### addOutput +### removeInput -addOutput\(photoOutput: PhotoOutput, callback: AsyncCallback\): void +removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -在当前会话中,添加一个PhotoOutput实例,通过注册回调函数获取结果。 +移除[CameraInput](#camerainput),通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.addOutput(photoOutput, (err) => { +captureSession.removeInput(cameraInput, (err) => { if (err) { - console.error('Failed to add the PhotoOutput instance ${err.message}'); + console.error('Failed to remove the CameraInput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); + console.log('Callback invoked to indicate that the cameraInput instance is removed.'); }); ``` -### addOutput +### removeInput -addOutput\(photoOutput: PhotoOutput\): Promise +removeInput\(cameraInput: CameraInput\): Promise -在当前会话中,添加一个PhotoOutput实例,通过Promise获取结果。 +移除[CameraInput](#camerainput),通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要添加的PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise\ | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.addOutput(photoOutput).then(() => { - console.log('Promise used to indicate that the PhotoOutput instance is added.'); +captureSession.removeInput(cameraInput).then(() => { + console.log('Promise returned to indicate that the cameraInput instance is removed.'); }) ``` -### addOutput +### canAddOutput -addOutput\(videoOutput: VideoOutput, callback: AsyncCallback\): void +canAddOutput(cameraOutput: CameraOutput, callback: AsyncCallback\): void -在当前会话中,添加一个VideoOutput实例,通过注册回调函数获取结果。 +查询是否可以添加[CameraOutput](#cameraoutput)到会话中,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | 是 | 需要添加的CameraOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.addOutput(videoOutput, (err) => { +captureSession.canAddOutput(cameraOutput, (err, status) => { if (err) { - console.error('Failed to add the VideoOutput instance ${err.message}'); + console.error('Can not add cameraOutput. ${err.message}'); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is added.'); -}); + console.log('Callback returned with cameraOutput can added.'); +}) ``` -### addOutput +### canAddOutput -addOutput\(videoOutput: VideoOutput\): Promise +canAddOutput(cameraOutput: CameraOutput): Promise -在当前会话中,添加一个VideoOutput实例,通过Promise获取结果。 +查询是否可以添加[CameraOutput](#cameraoutput)到会话中,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要添加的VideoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | 是 | 需要添加的CameraOutput实例。 | + **返回值:** -| 类型 | 说明 | +| 类型 | 说明 | | -------------- | --------------------------- | -| Promise\ | 使用Promise的方式获取结果。 | +| Promise | 使用Promise的方式获取结果。 | + **示例:** ```js -captureSession.addOutput(videoOutput).then(() => { - console.log('Promise used to indicate that the VideoOutput instance is added.'); +captureSession.canAddOutput(cameraOutput).then(() => { + console.log('Promise returned with cameraOutput can added.'); }) ``` -### removeInput +### addOutput -removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void +addOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -在当前会话中,移除一个CameraInput实例,通过注册回调函数获取结果。 +把[CameraOutput](#cameraoutput)加入到会话,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------ | +| cameraOutput | [CameraOutput](#cameraOutput) | 是 | 需要添加的CameraOutput实例。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.removeInput(cameraInput, (err) => { +captureSession.addOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to remove the CameraInput instance. ${err.message}'); + console.error('Failed to add output. ${err.message}'); return; } - console.log('Callback invoked to indicate that the cameraInput instance is removed.'); -}); + console.log('Callback returned with output added.'); +}) ``` -### removeInput +### addOutput -removeInput\(cameraInput: CameraInput\): Promise +addOutput\(cameraOutput: CameraOutput\): Promise -在当前会话中,移除一个CameraInput实例,通过Promise获取结果。 +把[CameraOutput](#cameraoutput)加入到会话,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | 是 | 需要添加的CameraOutput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise\ | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.removeInput(cameraInput).then(() => { - console.log('Promise returned to indicate that the cameraInput instance is removed.'); +captureSession.addOutput(cameraOutput).then(() => { + console.log('Promise returned with cameraOutput added.'); }) ``` ### removeOutput -removeOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +removeOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -在当前会话中,移除一个PreviewOutput实例,通过注册回调函数获取结果。 +从会话中移除[CameraOutput](#cameraoutput),通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的PreviewOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------ | +| cameraOutput | [CameraOutput](#cameraOutput) | 是 | 需要移除的CameraOutput实例。 | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.removeOutput(previewOutput, (err) => { +captureSession.removeOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to remove the PreviewOutput instance. ${err.message}'); + console.error('Failed to remove the CameraOutput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is removed.'); + console.log('Callback invoked to indicate that the CameraOutput instance is removed.'); }); ``` ### removeOutput -removeOutput(previewOutput: PreviewOutput): Promise +removeOutput(cameraOutput: CameraOutput): Promise -在当前会话中,移除一个PreviewOutput实例,通过Promise获取结果。 +从会话中移除[CameraOutput](#cameraoutput),通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的PreviewOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | 是 | 需要移除的CameraOutput实例。 | **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.removeOutput(previewOutput).then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is removed.'); +captureSession.removeOutput(cameraOutput).then(() => { + console.log('Promise returned to indicate that the CameraOutput instance is removed.'); }) ``` -### removeOutput +### start -removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback): void +start\(callback: AsyncCallback\): void -在当前会话中,移除一个PhotoOutput实例,通过注册回调函数获取结果。 +开始会话工作,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要移除的PhotoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.removeOutput(photoOutput, (err) => { +captureSession.start((err) => { if (err) { - console.error('Failed to remove the PhotoOutput instance. ${err.message}'); + console.error('Failed to start the session ${err.message}'); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); + console.log('Callback invoked to indicate the session start success.'); }); ``` -### removeOutput +### start -removeOutput(photoOutput: PhotoOutput): Promise +start\(\): Promise -在当前会话中,移除一个PhotoOutput实例,通过Promise获取结果。 +开始会话工作,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | 是 | 需要移除的PhotoOutput实例。 | - - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | - **示例:** ```js -captureSession.removeOutput(photoOutput).then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is removed.'); +captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); }) ``` -### removeOutput +### stop -removeOutput(videoOutput: VideoOutput, callback: AsyncCallback): void +stop\(callback: AsyncCallback\): void -在当前会话中,移除一个VideoOutput实例,通过注册回调函数获取结果。 +停止会话工作,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要移除的VideoOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.removeOutput(videoOutput, (err) => { +captureSession.stop((err) => { if (err) { - console.error('Failed to remove the VideoOutput instance. ${err.message}'); + console.error('Failed to stop the session ${err.message}'); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is removed.'); + console.log('Callback invoked to indicate the session stop success.'); }); ``` -### removeOutput +### stop -removeOutput(videoOutput: VideoOutput): Promise +stop(): Promise -在当前会话中,移除一个VideoOutput实例,通过Promise获取结果。 +停止会话工作,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | 是 | 需要移除的VideoOutput实例。 | - - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | - **示例:** ```js -captureSession.removeOutput(videoOutput).then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is removed.'); +captureSession.stop().then(() => { + console.log('Promise returned to indicate the session stop success.'); }) ``` -### start +### lockForControl -start\(callback: AsyncCallback\): void +lockForControl(callback: AsyncCallback): void -启动拍照会话,通过注册回调函数获取结果。 +请求以独占方式控制设备的硬件属性[CameraInput](#camerainput),需要调用[unlockForControl](#unlockforcontrol),通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.start((err) => { +captureSession.lockForControl((err) => { if (err) { - console.error('Failed to start the session ${err.message}'); + console.error('Failed to lock. ${err.message}'); return; } - console.log('Callback invoked to indicate the session start success.'); -}); + console.log('Locked.'); +}) ``` -### start +### lockForControl -start\(\): Promise +lockForControl(): Promise -启动拍照会话,通过Promise获取结果。 +请求以独占方式控制设备的硬件属性[CameraInput](#camerainput),需要调用[unlockForControl](#unlockforcontrol),通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); +captureSession.lockForControl().then(() => { + console.log('Locked.'); }) ``` -### stop +### unlockForControl -stop\(callback: AsyncCallback\): void +unlockForControl(callback: AsyncCallback): void -停止拍照会话,通过注册回调函数获取结果。 +控制生效,并放弃对设备配置的排他控制,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -captureSession.stop((err) => { +captureSession.unlockForControl((err) => { if (err) { - console.error('Failed to stop the session ${err.message}'); + console.error('Failed to unlock. ${err.message}'); return; } - console.log('Callback invoked to indicate the session stop success.'); -}); + console.log('Unlocked.'); +}) ``` -### stop +### unlockForControl -stop(): Promise +unlockForControl(): Promise -停止拍照会话,通过Promise获取结果。 +控制生效,并放弃对设备配置的排他控制,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -captureSession.stop().then(() => { - console.log('Promise returned to indicate the session stop success.'); +captureSession.unlockForControl().then(() => { + console.log('Unlocked.'); }) ``` @@ -1807,14 +1930,14 @@ captureSession.stop().then(() => { release\(callback: AsyncCallback\): void -释放CaptureSession实例,通过注册回调函数获取结果。 +释放会话资源,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1833,14 +1956,14 @@ captureSession.release((err) => { release(): Promise -释放CaptureSession实例,通过Promise获取结果。 +释放会话资源,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | **示例:** @@ -1851,433 +1974,2065 @@ captureSession.release().then(() => { }) ``` -### on('error') +### hasFlash -on(type: 'error', callback: ErrorCallback): void +hasFlash(callback: AsyncCallback): void -监听拍照会话的错误事件,通过注册回调函数获取结果。 +检测是否有闪光灯,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即拍照会话错误事件。 | -| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------- | +| callback | AsyncCallback | 是 | 回调函数,返回true表示设备支持闪光灯。 | **示例:** ```js -captureSession.on('error', (captureSessionError) => { - console.log('Capture session error code: ' + captureSessionError.code); +cameraInput.hasFlash((err, status) => { + if (err) { + console.error('Failed to check whether the device has flash light. ${err.message}'); + return; + } + console.log('Callback returned with flash light support status: ' + status); }) ``` -## CaptureSessionErrorCode +### hasFlash -枚举,拍照会话的错误码。 +hasFlash(): Promise -**系统能力:** SystemCapability.Multimedia.Camera.Core +检测是否有闪光灯,通过Promise获取结果。 -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +**系统能力:** SystemCapability.Multimedia.Camera.Core -## CaptureSessionError +**返回值:** -拍照会话错误对象。 +| 类型 | 说明 | +| ----------------- | ----------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持闪光灯。 | -**系统能力:** SystemCapability.Multimedia.Camera.Core +**示例:** -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------------- | -------------------------- | -| code | [CaptureSessionError](#capturesessionerror) | CaptureSession中的错误码。 | +```js +cameraInput.hasFlash().then((status) => { + console.log('Promise returned with the flash light support status:' + status); +}) +``` -## camera.createPreviewOutput +### isFlashModeSupported -createPreviewOutput(surfaceId: string, callback: AsyncCallback): void +isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void -获取PreviewOutput实例,通过注册回调函数获取结果。 +检测闪光灯模式是否支持,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ----------------------------------------------- | ---- | ------------------------------------- | -| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | --------------------------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该闪光灯模式。 | **示例:** ```js -camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { if (err) { - console.error('Failed to create the PreviewOutput instance. ${err.message}'); + console.error('Failed to check whether the flash mode is supported. ${err.message}'); return; } - console.log('Callback returned with previewOutput instance'); -}); + console.log('Callback returned with the flash mode support status: ' + status); +}) ``` -## camera.createPreviewOutput +### isFlashModeSupported -createPreviewOutput(surfaceId: string): Promise\ +isFlashModeSupported(flashMode: FlashMode): Promise -获取PreviewOutput实例,通过Promise获取结果。 +检测闪光灯模式是否支持,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ---------------------------------- | -| surfaceId | string | 是 | 从XComponent组件获取的Surface ID。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | **返回值:** -| 类型 | 说明 | -| ----------------------------------------- | --------------------------- | -| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ----------------- | ---------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持该闪光灯模式。 | **示例:** ```js -camera.createPreviewOutput("surfaceId").then((previewOutput) => { - console.log('Promise returned with the PreviewOutput instance'); +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { + console.log('Promise returned with flash mode support status.' + status); }) ``` -## PreviewOutput +### setFlashMode -预览输出类。 +setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void -### release +设置闪光灯模式,通过注册回调函数获取结果。 -release(callback: AsyncCallback): void +进行设置之前,需要先检查: -释放PreviewOutput实例,通过注册回调函数获取结果。 +1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 +2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | --------------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -previewOutput.release((err) => { +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { if (err) { - console.error('Failed to release the PreviewOutput instance ${err.message}'); + console.error('Failed to set the flash mode ${err.message}'); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); -}); + console.log('Callback returned with the successful execution of setFlashMode.'); +}) ``` -### release +### setFlashMode -release(): Promise +setFlashMode(flashMode: FlashMode): Promise + +设置闪光灯模式,通过Promise获取结果。 + +进行设置之前,需要先检查: -释放PreviewOutput实例,通过Promise获取结果。 +1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)。 +2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)。 **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ------------- | +| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | + **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ------------------------ | | Promise | 使用Promise的方式获取结果。 | - **示例:** ```js -previewOutput.release().then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFlashMode.'); }) ``` -### on('frameStart') +### getFlashMode -on(type: 'frameStart', callback: AsyncCallback): void +getFlashMode(callback: AsyncCallback): void -监听预览帧启动,通过注册回调函数获取结果。 +获取当前设备的闪光灯模式,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameStart',即帧启动事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | --------------------------------- | +| callback | AsyncCallback<[FlashMode](#flashmode)\> | 是 | 回调函数,用于获取当前设备的闪光灯模式。 | **示例:** ```js -previewOutput.on('frameStart', () => { - console.log('Preview frame started'); +cameraInput.getFlashMode((err, flashMode) => { + if (err) { + console.error('Failed to get the flash mode ${err.message}'); + return; + } + console.log('Callback returned with current flash mode: ' + flashMode); }) ``` -### on('frameEnd') +### getFlashMode -on(type: 'frameEnd', callback: AsyncCallback): void +getFlashMode(): Promise -监听预览帧结束,通过注册回调函数获取结果。 +获取当前设备的闪光灯模式,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** +**返回值:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameEnd',即帧结束事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 类型 | 说明 | +| --------------------------------- | --------------------------------- | +| Promise<[FlashMode](#flashmode)\> | 使用Promise的方式获取当前的闪光灯模式。 | **示例:** ```js -previewOutput.on('frameEnd', () => { - console.log('Preview frame ended'); +cameraInput.getFlashMode().then((flashMode) => { + console.log('Promise returned with current flash mode : ' + flashMode); }) ``` -### on('error') +### isExposureModeSupported -on(type: 'error', callback: ErrorCallback): void +isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void; -监听预览输出的错误事件,通过注册回调函数获取结果。 +检测曝光模式是否支持,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :----------------------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即预览输出错误事件。 | -| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------------- | +| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取是否支持曝光模式。 | **示例:** ```js -previewOutput.on('error', (previewOutputError) => { - console.log('Preview output error code: ' + previewOutputError.code); +cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { + if (err) { + console.log('Failed to check exposure mode supported ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of isExposureModeSupported'); }) ``` -## PreviewOutputErrorCode +### isExposureModeSupported -枚举,预览输出的错误码。 +isExposureModeSupported(aeMode: ExposureMode): Promise + +检测曝光模式是否支持,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +**参数:** -## PreviewOutputError +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------------- | +| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 | -预览输出错误对象。 +**返回值:** -**系统能力:** SystemCapability.Multimedia.Camera.Core +| 名称 | 说明 | +| ----------------- |--------------------------------- | +| Promise | 使用Promise的方式获取支持的曝光模式。 | -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------------------- | ---------------------- | -| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | PreviewOutput中的错误码。 | +**示例:** -## camera.createPhotoOutput +```js +cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log('Promise returned with exposure mode supported : ' + isSupported); +}) +``` + +### getExposureMode -createPhotoOutput(surfaceId: string, callback: AsyncCallback): void +getExposureMode(callback: AsyncCallback): void -获取PhotoOutput实例,通过注册回调函数获取结果。 +获取当前曝光模式,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| surfaceId | string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的Surface ID。 | -| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | 是 | 回调函数,用于获取PhotoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ---------------------------------------- | +| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | 是 | 回调函数,用于获取当前曝光模式。 | **示例:** ```js -camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { +cameraInput.getExposureMode((err, exposureMode) => { if (err) { - console.error('Failed to create the PhotoOutput instance. ${err.message}'); - return; + console.log('Failed to get the exposure mode ${err.message}'); + return ; } - console.log('Callback returned with the PhotoOutput instance.'); -}); + console.log('Callback returned with current exposure mode:' + exposureMode); +}) ``` -## camera.createPhotoOutput +### getExposureMode -createPhotoOutput(surfaceId: string): Promise +getExposureMode(): Promise -获取PhotoOutput实例,通过Promise获取结果。 +获取当前曝光模式,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | --------------------------------- | -| surfaceId | string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的Surface ID。 | - **返回值:** -| 类型 | 说明 | -| ------------------------------------- | -------------------------------------- | -| Promise<[PhotoOutput](#photooutput)\> | 使用Promise的方式获取PhotoOutput实例。 | +| 名称 | 说明 | +| --------------------------------------- |------------------------------- | +| Promise<[ExposureMode](#exposuremode)\> | 使用Promise的方式获取当前曝光模式。 | **示例:** ```js -camera.createPhotoOutput("surfaceId").then((photoOutput) => { - console.log('Promise returned with PhotoOutput instance'); +cameraInput.getExposureMode().then((exposureMode) => { + console.log('Promise returned with current exposure mode : ' + exposureMode); }) ``` -## ImageRotation -枚举,图片旋转角度。 +### setExposureMode + +setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void + +设置曝光模式,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------ | ---- | --------------- | +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------- | +| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取设置结果。 | + +**示例:** + +```js +cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { + if (err) { + console.log('Failed to set the exposure mode ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of setExposureMode'); +}) +``` + +### setExposureMode + +setExposureMode(aeMode: ExposureMode): Promise + +设置曝光模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 名称 | 说明 | +| ----------------- |---------------------------- | +| Promise | 使用Promise的方式获取设置结果。 | + +**示例:** + +```js +cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => { + console.log('Promise returned with the successful execution of setExposureMode.'); +}) +``` + +### getMeteringPoint + +getMeteringPoint(callback: AsyncCallback): void + +查询曝光区域中心点,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ------------------------ | +| callback | AsyncCallback<[Point](#point)\>| 是 | 回调函数,用于获取当前曝光点。 | + +**示例:** + +```js +cameraInput.getMeteringPoint((err, exposurePoint) => { + if (err) { + console.log('Failed to get the current exposure point ${err.message}'); + return ; + } + console.log('Callback returned with current exposure point:' + exposurePoint); +}) +``` + +### getMeteringPoint + +getMeteringPoint(): Promise + +查询曝光区域中心点,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 名称 | 说明 | +| ------------------------- |----------------------------- | +| Promise<[Point](#point)\> | 使用Promise的方式获取当前曝光点。 | + +**示例:** + +```js +cameraInput.getMeteringPoint().then((exposurePoint) => { + console.log('Promise returned with current exposure point : ' + exposurePoint); +}) +``` + +### setMeteringPoint + +setMeteringPoint(point: Point, callback: AsyncCallback): void + +设置曝光区域中心点,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------------- | -------------------------------| ---- | ------------------- | +| exposurePoint | [Point](#point) | 是 | 曝光点。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +var Point1 = {x: 1, y: 1}; + +cameraInput.setMeteringPoint(Point1,(err) => { + if (err) { + console.log('Failed to set the exposure point ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of setMeteringPoint'); +}) +``` + +### setMeteringPoint + +setMeteringPoint(point: Point): Promise + +设置曝光区域中心点,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------------- | -------------------------------| ---- | ------------------- | +| exposurePoint | [Point](#point) | 是 | 曝光点。 | + +**返回值:** + +| 名称 | 说明 | +| ----------------- |------------------------ | +| Promise | 使用Promise的方式返回结果。 | + +**示例:** + +```js +var Point2 = {x: 2, y: 2}; + +cameraInput.setMeteringPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setMeteringPoint'); +}) +``` + +### getExposureBiasRange + +getExposureBiasRange(callback: AsyncCallback\>): void + +查询曝光补偿范围,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ----------------------------- | +| callback | AsyncCallback\> | 是 | 回调函数,用于获取补偿范围的数组。 | + +**示例:** + +```js +cameraInput.getExposureBiasRange((err, biasRangeArray) => { + if (err) { + console.log('Failed to get the array of compenstation range ${err.message}'); + return ; + } + console.log('Callback returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); +}) +``` + +### getExposureBiasRange + +getExposureBiasRange(): Promise\> + +查询曝光补偿范围,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 名称 | 说明 | +| ----------------- |-------------------------------------- | +| Promise\> | 使用Promise的方式获取曝光补偿范围。 | + +**示例:** + +```js +cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log('Promise returned with exposure mode supported : ' + isSupported); +}) +``` + +### setExposureBias + +setExposureBias(exposureBias: number, callback: AsyncCallback): void + +设置曝光补偿,通过注册回调函数获取结果。 + +进行设置之前,建议先通过方法[getExposureBiasRange](#getexposurebiasrange)查询支持的范围。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------| ---- | ------------------- | +| exposureBias | number | 是 | 曝光补偿。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +cameraInput.setExposureBias(-4,(err) => { + if (err) { + console.log('Failed to set the exposure bias ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of setExposureBias'); +}) +``` + +### setExposureBias + +setExposureBias(exposureBias: number): Promise + +设置曝光补偿,通过Promise获取结果。 + +进行设置之前,建议先通过方法[getExposureBiasRange](#getexposurebiasrange)查询支持的范围。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------------- | --------- | ---- | --------- | +| exposureBias | number | 是 | 曝光补偿。 | + +**返回值:** + +| 名称 | 说明 | +| ----------------- |------------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +cameraInput.setExposureBias(-4).then(() => { + console.log('Promise returned with the successful execution of setExposureBias.'); +}) +``` + +### getExposureValue + +getExposureValue(callback: AsyncCallback): void + +查询当前曝光值,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------| ---- | --------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取曝光值。 | + +**示例:** + +```js +cameraInput.getExposureValue((err, exposureValue) => { + if (err) { + console.log('Failed to get the exposure value ${err.message}'); + return ; + } + console.log('Callback returned with the exposure value: ' + exposureValue); +}) +``` + +### getExposureValue + +getExposureValue(): Promise + +查询当前曝光值,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 名称 | 说明 | +| ----------------- |-------------------------- | +| Promise | 使用Promise的方式获取曝光值。 | + +**示例:** + +```js +cameraInput.getExposureValue().then((exposureValue) => { + console.log('Promise returned with exposure value: ' + exposureValue); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void + +检测对焦模式是否支持,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回true表示支持该焦距模式。 | + +**示例:** + +```js +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { + if (err) { + console.error('Failed to check whether the focus mode is supported. ${err.message}'); + return; + } + console.log('Callback returned with the focus mode support status: ' + status); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode): Promise + +检测对焦模式是否支持,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------- | --------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回true表示设备支持该焦距模式。 | + +**示例:** + +```js +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { + console.log('Promise returned with focus mode support status.' + status); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode, callback: AsyncCallback): void + +设置对焦模式,通过注册回调函数获取结果。 + +进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { + if (err) { + console.error('Failed to set the focus mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setFocusMode.'); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode): Promise + +设置对焦模式,通过Promise获取结果。 + +进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ------------- | +| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFocusMode.'); +}) +``` + +### getFocusMode + +getFocusMode(callback: AsyncCallback): void + +获取当前的对焦模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<[FocusMode](#focusmode)\> | 是 | 回调函数,用于获取当前设备的焦距模式。 | + +**示例:** + +```js +cameraInput.getFocusMode((err, afMode) => { + if (err) { + console.error('Failed to get the focus mode ${err.message}'); + return; + } + console.log('Callback returned with current focus mode: ' + afMode); +}) +``` + +### getFocusMode + +getFocusMode(): Promise + +获取当前的对焦模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| Promise | 使用Promise的方式获取当前的焦距模式。 | + +**示例:** + +```js +cameraInput.getFocusMode().then((afMode) => { + console.log('Promise returned with current focus mode : ' + afMode); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point, callback: AsyncCallback): void + +设置焦点,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------- | +| point | [Point](#Point) | 是 | 焦点。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +var Point1 = {x: 1, y: 1}; + +cameraInput.setFocusPoint(Point1, (err) => { + if (err) { + console.error('Failed to set the focus point ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setFocusPoint.'); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point): Promise + +设置焦点,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +var Point2 = {x: 2, y: 2}; + +cameraInput.setFocusPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setFocusPoint.'); +}) +``` + +### getFocusPoint + +getFocusPoint(callback: AsyncCallback): void + +查询焦点,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ----------------------- | +| callback | AsyncCallback<[Point](#point)\> | 是 | 回调函数,用于获取当前焦点。 | + +**示例:** + +```js +cameraInput.getFocusPoint((err, point) => { + if (err) { + console.error('Failed to get the current focus point ${err.message}'); + return; + } + console.log('Callback returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocusPoint + +getFocusPoint(): Promise + +查询焦点,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| --------------- | --------------------------- | +| Promise | 使用Promise的方式获取当前焦点。 | + +**示例:** + +```js +cameraInput.getFocusPoint().then((point) => { + console.log('Promise returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocalLength + +getFocalLength(callback: AsyncCallback): void + +查询焦距值,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取当前焦距。 | + +**示例:** + +```js +cameraInput.getFocalLength((err, focalLength) => { + if (err) { + console.error('Failed to get the current focal length ${err.message}'); + return; + } + console.log('Callback returned with the current focal length: ' + focalLength); +}) +``` + +### getFocalLength + +getFocalLength(): Promise + +查询焦距值,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------- | +| Promise | 使用Promise的方式获取焦距。 | + +**示例:** + +```js +cameraInput.getFocalLength().then((focalLength) => { + console.log('Promise returned with the current focal length: ' + focalLength); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(callback: AsyncCallback\>\): void + +获取支持的变焦范围,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------ | ---- | ------------------- | +| callback | AsyncCallback\> | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +cameraInput.getZoomRatioRange((err, zoomRatioRange) => { + if (err) { + console.error('Failed to get the zoom ratio range. ${err.message}'); + return; + } + console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(\): Promise\> + +获取支持的变焦范围,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------------ | --------------------------- | +| Promise\> | 使用Promise的方式获取变焦范围。 | + +**示例:** + +```js +cameraInput.getZoomRatioRange().then((zoomRatioRange) => { + console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number, callback: AsyncCallback): void + +设置变焦比,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| --------- | -------------------- | ---- | ------------------- | +| zoomRatio | number | 是 | 可变焦距比。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +cameraInput.setZoomRatio(1, (err) => { + if (err) { + console.error('Failed to set the zoom ratio value ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setZoomRatio.'); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number): Promise + +设置变焦比,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------- | +| zoomRatio | number | 是 | 可变焦距比。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +cameraInput.setZoomRatio(1).then(() => { + console.log('Promise returned with the successful execution of setZoomRatio.'); +}) +``` + +### getZoomRatio + +getZoomRatio(callback: AsyncCallback): void + +获取当前的变焦比,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +cameraInput.getZoomRatio((err, zoomRatio) => { + if (err) { + console.error('Failed to get the zoom ratio ${err.message}'); + return; + } + console.log('Callback returned with current zoom ratio: ' + zoomRatio); +}) +``` + +### getZoomRatio + +getZoomRatio(): Promise + +获取当前的变焦比,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +cameraInput.getZoomRatio().then((zoomRatio) => { + console.log('Promise returned with current zoom ratio : ' + zoomRatio); +}) +``` + +### isVideoStablizationModeSupported + +isVideoStablizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void + +查询是否支持指定的视频防抖模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | ------------------------------ | +| vsMode | [VideoStabilizationMode](#videostabilizationMode) | 是 | 视频防抖模式。 | +| callback | AsyncCallback | 是 | 回调函数,返回视频防抖模式是否支持。 | + +**示例:** + +```js +captureSession.isVideoStablizationModeSupported(camera.VideoStabilizationMode.OFF, (err, isSupported) => { + if (err) { + console.error('Failed to check whether video stabilization mode supported. ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of isVideoStabilizationModeSupported: ' + status); +}) +``` + +### isVideoStablizationModeSupported + +isVideoStablizationModeSupported(vsMode: VideoStabilizationMode): Promise + +查询是否支持指定的视频防抖模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ----------------- | --------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回视频防抖模式是否支持。 | + +**示例:** + +```js +captureSession.isVideoStablizationModeSupported(camera.VideoStabilizationMode.OFF).then((isSupported) => { + console.log('Promise returned with video stabilization mode supported: ' + isSupported); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(callback: AsyncCallback): void + +查询当前正在使用的视频防抖模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback | 是 | 回调函数,返回视频防抖是否正在使用。 | + +**示例:** + +```js +captureSession.getActiveVideoStabilizationMode((err, vsMode) => { + if (err) { + console.error('Failed to get active video stabilization mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of getActiveVideoStabilizationMode.'); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(): Promise + +查询当前正在使用的视频防抖模式,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------------------------- | ------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回视频防抖当前是否正在使用。 | + +**示例:** + +```js +captureSession.getActiveVideoStabilizationMode().then((vsMode) => { + console.log('Promise returned with the current video stabilization mode: ' + vsMode); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void + +设置视频防抖模式,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | --------------------- | +| mode | [VideoStabilizationMode](#videostabilizationmode) | 是 | 需要设置的视频防抖模式。 | +| callback | AsyncCallback | 是 | 回调函数。 | + +**示例:** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF, (err) => { + if (err) { + console.error('Failed to set the video stabilization mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode): Promise + +设置视频防抖,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回设置的视频防抖模式的结果。 | + +**示例:** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF).then(() => { + console.log('Promise returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### on('focusStateChange') + +on(type: 'focusStateChange', callback: AsyncCallback): void + +监听焦距的状态变化,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------ | +| type | string | 是 | 监听事件,固定为'focusStateChange',即焦距状态变化事件。 | +| callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 | + +**示例:** + +```js +cameraInput.on('focusStateChange', (focusState) => { + console.log('Focus state : ' + focusState); +}) +``` + +### on('exposureStateChange') + +on(type: 'exposureStateChange', callback: AsyncCallback): void + +监听曝光的状态变化,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ---------------------------------------------- | +| type | string | 是 | 监听事件,固定为'exposureStateChange',即曝光状态变化事件。| +| callback | AsyncCallback<[ExposureState](#exposureState)\> | 是 | 回调函数,用于获取曝光状态。 | + +**示例:** + +```js +cameraInput.on('exposureStateChange', (exposureState) => { + console.log('Exposuer state : ' + exposureState); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +监听拍照会话的错误事件,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------ | +| type | string | 是 | 监听事件,固定为'error',即拍照会话错误事件。 | +| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | 是 | 回调函数,用于获取错误信息。 | + +**示例:** + +```js +captureSession.on('error', (captureSessionError) => { + console.log('Capture session error code: ' + captureSessionError.code); +}) +``` + +## CaptureSessionErrorCode + +枚举,会话错误类型。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_INSUFFICIENT_RESOURCES | 0 | 资源不足。 | +| ERROR_TIMEOUT | 1 | 超时。 | + +## CaptureSessionError + +会话错误码。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------------- | -------------------------- | +| code | [CaptureSessionError](#capturesessionerror) | CaptureSession中的错误码。 | + +## CameraOutput + +会话中[CaptureSession](#capturesession)使用的输出信息,output的基类。 + +### release + +release(callback: AsyncCallback): void + +释放输出资源,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.release((err) => { + if (err) { + console.error('Failed to release the PreviewOutput instance ${err.message}'); + return; + } + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); +``` + +### release + +release(): Promise + +释放输出资源,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +previewOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +}) +``` + +## PreviewOutput + +预览输出类。继承[CameraOutput](#cameraOutput) + +### addDeferredSurface + +addDeferredSurface(surfaceId: string, callback: AsyncCallback): void + +在previewOutput生成之后添加surface,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------------------------------------------------------- | +| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)组件获取的SurfaceID。| +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.addDeferredSurface('surfaceId', (err) => { + if (err) { + console.error('Failed to add deferredSurface. ${err.message}'); + return; + } + console.log('Callback returned with deferredSurface added.'); +}) +``` + +### addDeferredSurface + +addDeferredSurface(surfaceId: string): Promise + +在previewOutput生成之后添加surface,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -----------| ---- | ------------------------------------------------------------------------------ | +| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)组件获取的SurfaceID。| + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +previewOutput.addDeferredSurface('surfaceId').then(() => { + console.log('Promise returned with deferredSurface added.'); +}) +``` + +### start + +start(callback: AsyncCallback): void + +开始输出预览流,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.start((err) => { + if (err) { + console.error('Failed to start the previewOutput. ${err.message}'); + return; + } + console.log('Callback returned with previewOutput started.'); +}) +``` + +### start + +start(): Promise + +开始输出预览流,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ----------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +previewOutput.start().then(() => { + console.log('Promise returned with previewOutput started.'); +}) +``` + +### stop + +stop(callback: AsyncCallback): void + +停止输出预览流,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.stop((err) => { + if (err) { + console.error('Failed to stop the previewOutput. ${err.message}'); + return; + } + console.log('Callback returned with previewOutput stoped.'); +}) +``` + +### stop + +stop(): Promise + +停止输出预览流,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** + +```js +previewOutput.stop().then(() => { + console.log('Callback returned with previewOutput stoped.'); +}) +``` + +### on('frameStart') + +on(type: 'frameStart', callback: AsyncCallback): void + +监听预览帧启动,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | --------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',即帧启动事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.on('frameStart', () => { + console.log('Preview frame started'); +}) +``` + +### on('frameEnd') + +on(type: 'frameEnd', callback: AsyncCallback): void + +监听预览帧结束,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameEnd',即帧结束事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +previewOutput.on('frameEnd', () => { + console.log('Preview frame ended'); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +监听预览输出的错误事件,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------------- | ---- | ------------------------ | +| type | string | 是 | 监听事件,固定为'error',即预览输出错误事件。| +| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | 是 | 回调函数,用于获取错误信息。 | + +**示例:** + +```js +previewOutput.on('error', (previewOutputError) => { + console.log('Preview output error code: ' + previewOutputError.code); +}) +``` + +## PreviewOutputErrorCode + +枚举,预览输出错误类型。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | + +## PreviewOutputError + +预览输出错误码。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------------------- | ---------------------- | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | PreviewOutput中的错误码。 | + +## ImageRotation + +枚举,图片旋转角度。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| ------------ | ---- | ------------- | | ROTATION_0 | 0 | 图片旋转0度。 | | ROTATION_90 | 90 | 图片旋转90度。 | | ROTATION_180 | 180 | 图片旋转180度。 | | ROTATION_270 | 270 | 图片旋转270度。 | -## QualityLevel +## Location + +图片地理位置信息。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 必填 |说明 | +| ------------ | ------ | --- |------------ | +| latitude | number | 是 |纬度(度)。 | +| longitude | number | 是 |经度(度)。 | +| altitude | number | 是 |海拔(米)。 | + +## QualityLevel + +枚举,图片质量。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 值 | 说明 | +| -------------------- | ---- | ------------ | +| QUALITY_LEVEL_HIGH | 0 | 图片质量高。 | +| QUALITY_LEVEL_MEDIUM | 1 | 图片质量中等。 | +| QUALITY_LEVEL_LOW | 2 | 图片质量差。 | + + +## PhotoCaptureSetting + +拍摄照片的设置。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 必填 | 默认值 | 说明 | +| -------- | ------------------------------- | ---- | ----------------- | -----------------| +| quality | [QualityLevel](#qualitylevel) | 否 | QUALITY_LEVEL_HIGH| 图片质量。 | +| rotation | [ImageRotation](#imagerotation) | 否 | ROTATION_0 | 图片旋转角度。 | +| location | [Location](#location) | 否 | (0,0,0) | 图片地理位置信息。 | +| mirror | boolean | 否 | false |镜像使能开关(默认关)。 | + +## PhotoOutput + +拍照会话中使用的输出信息。 + +### getDefaultCaptureSetting + +getDefaultCaptureSetting(callback: AsyncCallback): void + +获取默认拍照参数,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | -------------------- | +| callback | AsyncCallback<[PhotoCaptureSetting](#photocapturesetting)\> | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +photoOutput.getDefaultCaptureSetting((err, photocapturesetting) => { + if (err) { + console.error('Failed to get the defaultCaptureSetting. ${err.message}'); + return; + } + console.log('Callback returned with an array of defaultCaptureSetting.'); +}) +``` + +### getDefaultCaptureSetting + +getDefaultCaptureSetting(): Promise + +获取默认拍照参数,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------- | ----------------------- | +| Promise<[PhotoCaptureSetting](#photocapturesetting)\> | 使用Promise的方式获取结果。 | + +**示例:** + +```js +photoOutput.getDefaultCaptureSetting().then((photocapturesetting) => { + console.log('Callback returned with an array of defaultCaptureSetting.'); +}) +``` + +### capture + +capture(callback: AsyncCallback): void + +以默认设置触发一次拍照,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +photoOutput.capture((err) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.log('Callback invoked to indicate the photo capture request success.'); +}); +``` + +### capture + +capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void + +以指定参数触发一次拍照,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | -------------------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | + +**示例:** + +```js +let settings:PhotoCaptureSetting = { + quality = 1, + rotation = 0 +} +photoOutput.capture(settings, (err) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.log('Callback invoked to indicate the photo capture request success.'); +}); +``` + +### capture + +capture(setting?: PhotoCaptureSetting): Promise + +以指定参数触发一次拍照,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------------- | ---- | -------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | 否 | 拍照设置。 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | + + +**示例:** + +```js +photoOutput.capture().then(() => { + console.log('Promise returned to indicate that photo capture request success.'); +}) +``` + +### isMirrorSupported + +isMirrorSupported(callback: AsyncCallback): void + +查询是否支持镜像拍照,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback | 是 | 回调函数,返回是否支持镜像拍照。 | + +**示例:** + +```js +captureSession.isMirrorSupported((err, isSupported) => { + if (err) { + console.error('Failed to check mirror is supported ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of isMirrorSupported.'); +}) +``` + +### isMirrorSupported + +isMirrorSupported(): Promise + +查询是否支持镜像拍照,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ------------------------------------------- | +| Promise | 使用Promise的方式获取结果,返回是否支持自拍结果。 | + +**示例:** + +```js +captureSession.isMirrorSupported().then((isSupported) => { + console.log('Promise returned with mirror supported: ' + isSupported); +}) +``` + +### on('captureStart') + +on(type: 'captureStart', callback: AsyncCallback): void + +监听拍照开始,通过注册回调函数获取Capture ID。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 监听事件,固定为'captureStart',即拍照启动事件。 | +| callback | AsyncCallback | 是 | 使用callback的方式获取Capture ID。 | + +**示例:** + +```js +photoOutput.on('captureStart', (err, captureId) => { + console.log('photo capture stated, captureId : ' + captureId); +}) +``` + +### on('frameShutter') + +on(type: 'frameShutter', callback: AsyncCallback): void + +监听拍照帧输出捕获,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | --- | ------------------------------------ | +| type | string | 是 | 监听事件,固定为'frameShutter',即帧刷新事件。 | +| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | 是 | 回调函数,用于获取相关信息。 | + +**示例:** + +```js +photoOutput.on('frameShutter', (err, frameShutterInfo) => { + console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); + console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); +}) +``` + +### on('captureEnd') + +on(type: 'captureEnd', callback: AsyncCallback): void + +监听拍照结束,通过注册回调函数获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------- | ---- | ---------------------------------------- | +| type | string | 是 | 监听事件,固定为'captureEnd',即拍照停止事件。 | +| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | 是 | 回调函数,用于获取相关信息。 | + +**示例:** + +```js +photoOutput.on('captureEnd', (err, captureEndInfo) => { + console.log('photo capture end, captureId : ' + captureEndInfo.captureId); + console.log('frameCount : ' + captureEndInfo.frameCount); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void -枚举,图片质量。 +监听拍照输出发生错误,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| -------------------- | ---- | -------------- | -| QUALITY_LEVEL_HIGH | 0 | 图片质量高。 | -| QUALITY_LEVEL_MEDIUM | 1 | 图片质量中等。 | -| QUALITY_LEVEL_LOW | 2 | 图片质量差。 | +**参数:** +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ----------------------------------- | +| type | string | 是 | 监听事件,固定为'error',即拍照错误事件。 | +| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | -## PhotoCaptureSetting +**示例:** -拍摄照片的设置。 +```js +photoOutput.on('error', (err, photoOutputError) => { + console.log('Photo output error code: ' + photoOutputError.code); +}) +``` + +## FrameShutterInfo + +拍照帧输出信息。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------- | ---- | -------------- | -| quality | [QualityLevel](#qualitylevel) | 否 | 图片质量。 | -| rotation | [ImageRotation](#imagerotation) | 否 | 图片旋转角度。 | +| 名称 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------- | +| captureId | number | 是 | 拍照的ID。 | +| timestamp | number | 是 | 快门时间戳。 | +## CaptureEndInfo -## PhotoOutput +拍照停止信息。 -照片输出类。 +**系统能力:** SystemCapability.Multimedia.Camera.Core -### capture +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ---------| +| captureId | number | 是 | 拍照的ID。 | +| frameCount | number | 是 | 帧数。 | -capture(callback: AsyncCallback): void +## PhotoOutputErrorCode -拍照,通过注册回调函数获取结果。 +枚举,拍照输出错误类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | --------------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_DRIVER_ERROR | 0 | 驱动或者硬件错误。 | +| ERROR_INSUFFICIENT_RESOURCES | 1 | 资源不足。 | +| ERROR_TIMEOUT | 2 | 超时。 | -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +## PhotoOutputError -**示例:** +拍照输出错误码。 -```js -photoOutput.capture((err) => { - if (err) { - console.error('Failed to capture the photo ${err.message}'); - return; - } - console.log('Callback invoked to indicate the photo capture request success.'); -}); -``` +**系统能力:** SystemCapability.Multimedia.Camera.Core -### capture +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | PhotoOutput中的错误码。 | -capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void +## VideoOutput + +录像会话中使用的输出信息。 + +### start -根据拍照设置拍照,通过注册回调函数获取结果。 +start(callback: AsyncCallback): void + +启动录制,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------- | ---- | ------------------------ | -| setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -let settings:PhotoCaptureSetting = { - quality = 1, - rotation = 0 -} -photoOutput.capture(settings, (err) => { +videoOutput.start((err) => { if (err) { - console.error('Failed to capture the photo ${err.message}'); + console.error('Failed to start the video output ${err.message}'); return; } - console.log('Callback invoked to indicate the photo capture request success.'); + console.log('Callback invoked to indicate the video output start success.'); }); ``` -### capture +### start -capture(setting?: PhotoCaptureSetting): Promise +start(): Promise -根据拍照设置拍照,通过Promise获取结果。 +启动录制,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------- | ------------------------------------------- | ---- | ---------- | -| setting | [PhotoCaptureSetting](#photocapturesetting) | 否 | 拍照设置。 | - **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | **示例:** ```js -photoOutput.capture().then(() => { - console.log('Promise returned to indicate that photo capture request success.'); +videoOutput.start().then(() => { + console.log('Promise returned to indicate that start method execution success.'); }) ``` -### release +### stop -release(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -释放PhotoOutput实例,通过注册回调函数获取结果。 +结束录制,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core @@ -2290,465 +4045,465 @@ release(callback: AsyncCallback): void **示例:** ```js -photoOutput.release((err) => { +videoOutput.stop((err) => { if (err) { - console.error('Failed to release the PhotoOutput instance ${err.message}'); + console.error('Failed to stop the video output ${err.message}'); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); + console.log('Callback invoked to indicate the video output stop success.'); }); ``` -### release +### stop -release(): Promise +stop(): Promise -释放PhotoOutput实例,通过Promise获取结果。 +结束录制,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | +| 类型 | 说明 | +| -------------- | ----------------------- | | Promise | 使用Promise的方式获取结果。 | - **示例:** ```js -photoOutput.release().then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is released successfully.'); +videoOutput.stop().then(() => { + console.log('Promise returned to indicate that stop method execution success.'); }) -``` +``` -### on('captureStart') +### on('frameStart') -on(type: 'captureStart', callback: AsyncCallback): void +on(type: 'frameStart', callback: AsyncCallback): void -监听拍照启动,通过注册回调函数获取Capture ID。 +监听录像开始,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :--------------------- | :--- | :----------------------------------------------- | -| type | string | 是 | 监听事件,固定为'captureStart',即拍照启动事件。 | -| callback | AsyncCallback | 是 | 使用callback的方式获取Capture ID。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ----------------------------------------- | +| type | string | 是 | 监听事件,固定为'frameStart',即视频帧开启事件。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -photoOutput.on('captureStart', (err, captureId) => { - console.log('photo capture stated, captureId : ' + captureId); +videoOutput.on('frameStart', () => { + console.log('Video frame started'); }) ``` -### on('frameShutter') +### on('frameEnd') -on(type: 'frameShutter', callback: AsyncCallback): void +on(type: 'frameEnd', callback: AsyncCallback): void -监听快门,通过注册回调函数获取结果。 +监听录像结束,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameShutter',即帧刷新事件。 | -| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | 是 | 回调函数,用于获取相关信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------- | ---- | ------------------------------------------ | +| type | string | 是 | 监听事件,固定为'frameEnd',即视频帧结束事件 。 | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -photoOutput.on('frameShutter', (err, frameShutterInfo) => { - console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); - console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); +videoOutput.on('frameEnd', () => { + console.log('Video frame ended'); }) ``` -### on('captureEnd') +### on('error') -on(type: 'captureEnd', callback: AsyncCallback): void +on(type: 'error', callback: ErrorCallback): void -监听拍照停止,通过注册回调函数获取结果。 +监听录像输出发生错误,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------------------------------------ | :--- | :--------------------------------------------- | -| type | string | 是 | 监听事件,固定为'captureEnd',即拍照停止事件。 | -| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | 是 | 回调函数,用于获取相关信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------ | ---- | -------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',即视频输出错误事件。 | +| callback | Callback<[VideoOutputError](#videooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | **示例:** ```js -photoOutput.on('captureEnd', (err, captureEndInfo) => { - console.log('photo capture end, captureId : ' + captureEndInfo.captureId); - console.log('frameCount : ' + captureEndInfo.frameCount); +videoOutput.on('error', (VideoOutputError) => { + console.log('Video output error code: ' + VideoOutputError.code); }) ``` -### on('error') - -on(type: 'error', callback: ErrorCallback): void +## VideoOutputErrorCode -监听拍照的错误事件,通过注册回调函数获取结果。 +枚举,录像输出错误类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| :------- | :---------------------------------------------------- | :--- | :---------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即拍照错误事件。 | -| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | - -**示例:** - -```js -photoOutput.on('error', (err, photoOutputError) => { - console.log('Photo output error code: ' + photoOutputError.code); -}) -``` +| 名称 | 值 | 说明 | +| --------------------- | ---- | ------------ | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_DRIVER_ERROR | 0 | 驱动或者硬件错误。| -## FrameShutterInfo +## VideoOutputError -快门事件信息。 +录像输出错误码。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ----------------------------- | -| captureId | number | 是 | CaptureId,本次拍摄动作的ID。 | -| timestamp | number | 是 | 时间戳。 | +| 名称 | 类型 | 说明 | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | VideoOutput中的错误码。 | -## CaptureEndInfo +## MetadataObjectType -拍照停止信息。 +枚举,metadata流。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | ----------------------------- | -| captureId | number | 是 | CaptureId,本次拍摄动作的ID。 | -| frameCount | number | 是 | 帧计数。 | +| 名称 | 值 | 说明 | +| ------------------------- | ---- | ----------------- | +| FACE_DETECTION | 0 | metadata对象类型。 | -## PhotoOutputErrorCode +## Rect -枚举,拍照输出的错误码。 +矩形定义。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | - -## PhotoOutputError +| 名称 | 类型 | 说明 | +| -------- | ------ | -------------------- | +| topLeftX | number | 矩形区域左上角x坐标。 | +| topLeftY | number | 矩形区域左上角y坐标。 | +| width | number | 矩形宽。 | +| height | number | 矩形高。 | -拍照输出错误对象。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core +## MetadataObject -| 名称 | 类型 | 说明 | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | PhotoOutput中的错误码。 | +相机元能力信息,[CameraInput](#camerainput)相机信息中的数据来源。 -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string, callback: AsyncCallback): void +getType(callback: AsyncCallback): void -获取VideoOutput实例,通过注册回调函数获取结果。 +查询metadata对象类型,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | -| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------------- | --- | -------------------- | +| callback | AsyncCallback<[MetadataObjectType](#metadataObjectType)\> | 是 | 回调函数,用于获取结果。 | **示例:** ```js -camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { +metadataObject.getType((err, metadataObjectType) => { if (err) { - console.error('Failed to create the VideoOutput instance. ${err.message}'); + console.error('Failed to get type. ${err.message}'); return; } - console.log('Callback returned with the VideoOutput instance'); -}); + console.log('Callback returned with an array of metadataObjectType.'); +}) ``` -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string): Promise +getType(): Promise -获取VideoOutput实例,通过Promise获取结果。 +查询metadata对象类型,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | --------------------------------- | -| surfaceId | string | 是 | 从VideoRecorder获取的Surface ID。 | - **返回值:** -| 类型 | 说明 | -| ------------------------------------- | -------------------------------------- | -| Promise<[VideoOutput](#videooutput)\> | 使用Promise的方式获取VideoOutput实例。 | +| 类型 | 说明 | +| --------------------------------------------------- | --------------------------- | +| Promise<[MetadataObjectType](#metadataObjectType)\> | 使用Promise的方式获取结果。 | **示例:** ```js -camera.createVideoOutput("surfaceId" -).then((videoOutput) => { - console.log('Promise returned with the VideoOutput instance'); +metadataObject.getType().then((metadataObjectType) => { + console.log('Callback returned with an array of metadataObjectType.'); }) ``` -## VideoOutput - -视频输出类。 +### getTimestamp -### start - -start(callback: AsyncCallback): void +getTimestamp(callback: AsyncCallback): void -开始拍摄视频,通过注册回调函数获取结果。 +查询metadata时间戳,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.start((err) => { +metadataObject.getTimestamp((err) => { if (err) { - console.error('Failed to start the video output ${err.message}'); + console.error('Failed to get timestamp. ${err.message}'); return; } - console.log('Callback invoked to indicate the video output start success.'); -}); + console.log('Callback returned with timestamp getted.'); +}) ``` -### start +### getTimestamp -start(): Promise +getTimestamp(): Promise -开始拍摄视频,通过Promise获取结果。 +查询metadata时间戳,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - +| 类型 | 说明 | +| ---------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that start method execution success.'); +metadataObject.getTimestamp().then(() => { + console.log('Callback returned with timestamp getted.'); }) ``` -### stop +### getBoundingBox -stop(callback: AsyncCallback): void +getBoundingBox(callback: AsyncCallback): void -停止拍摄视频,通过注册回调函数获取结果。 +查询metadata的边界框,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[Rect](#rect)\> | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.stop((err) => { +metadataObject.getBoundingBox((err, rect) => { if (err) { - console.error('Failed to stop the video output ${err.message}'); + console.error('Failed to get boundingBox. ${err.message}'); return; } - console.log('Callback invoked to indicate the video output stop success.'); -}); + console.log('Callback returned with boundingBox getted.'); +}) ``` -### stop +### getBoundingBox -stop(): Promise +getBoundingBox(): Promise -停止拍摄视频,通过Promise获取结果。 +查询metadata的边界框,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | +| 类型 | 说明 | +| ---------------------- | --------------------------- | +| Promise<[Rect](#rect)\> | 使用Promise的方式获取结果。 | **示例:** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that stop method execution success.'); +metadataObject.getBoundingBox().then((rect) => { + console.log('Callback returned with boundingBox getted.'); }) ``` -### release +## MetadataFaceObject -release(callback: AsyncCallback): void +metadata的人脸对象。继承[MetadataObject](#metadataObject) -释放VideoOutput实例,通过注册回调函数获取结果。 +## MetadataOutput + +metadata流。继承[CameraOutput](#cameraoutput) + +### start + +start(callback: AsyncCallback): void + +开始输出metadata,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.release((err) => { +metadataOutput.start((err) => { if (err) { - console.error('Failed to release the VideoOutput instance ${err.message}'); + console.error('Failed to start metadataOutput. ${err.message}'); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); -}); + console.log('Callback returned with metadataOutput started.'); +}) ``` -### release +### start -release(): Promise +start(): Promise -释放VideoOutput实例,通过Promise获取结果。 +开始输出metadata,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **返回值:** -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - +| 类型 | 说明 | +| ---------------------- | ------------------------ | +| Promise | 使用Promise的方式获取结果。 | **示例:** ```js -videoOutput.release().then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is released successfully.'); +metadataOutput.start().then(() => { + console.log('Callback returned with metadataOutput started.'); }) ``` -### on('frameStart') +### stop -on(type: 'frameStart', callback: AsyncCallback): void +stop(callback: AsyncCallback): void -监听视频帧开启,通过注册回调函数获取结果。 +停止输出metadata,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :----------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameStart',即视频帧开启事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------- | ---- | ------------------- | +| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | **示例:** ```js -videoOutput.on('frameStart', () => { - console.log('Video frame started'); +metadataOutput.stop((err) => { + if (err) { + console.error('Failed to stop the metadataOutput. ${err.message}'); + return; + } + console.log('Callback returned with metadataOutput stoped.'); }) ``` -### on('frameEnd') +### stop -on(type: 'frameEnd', callback: AsyncCallback): void +stop(): Promise + +停止输出metadata,通过Promise获取结果。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | --------------------------- | +| Promise | 使用Promise的方式获取结果。 | + +**示例:** -监听视频帧结束,通过注册回调函数获取结果。 +```js +metadataOutput.stop().then(() => { + console.log('Callback returned with metadataOutput stoped.'); +}) +``` + +### on('metadataObjectsAvailable') + +on(type: 'metadataObjectsAvailable', callback: AsyncCallback\>): void + +监听检测到的metadata对象,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :------------------- | :--- | :--------------------------------------------- | -| type | string | 是 | 监听事件,固定为'frameEnd',即视频帧结束事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- - | ---- | ------------------------------------ | +| type | string | 是 | 监听事件,固定为'metadataObjectsAvailable',即metadata对象。 | +| callback | Callback\> | 是 | 回调函数,用于获取错误信息。 | **示例:** ```js -videoOutput.on('frameEnd', () => { - console.log('Video frame ended'); +metadataOutput.on('metadataObjectsAvailable', (metadataObject) => { + console.log('metadata output error code: ' + metadataObject.code); }) ``` ### on('error') -on(type: 'error', callback: ErrorCallback): void +on(tuype: 'error', callback: ErrorCallback): void -监听视频输出的错误事件,通过注册回调函数获取结果。 +监听metadata流的错误,通过注册回调函数获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core **参数:** -| 名称 | 类型 | 必填 | 说明 | -| :------- | :----------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | 是 | 监听事件,固定为'error',即视频输出错误事件。 | -| callback | Callback<[VideoOutputError](#videooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | +| 名称 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------ | ---- | --------------------------------------- | +| type | string | 是 | 监听事件,固定为'error',即metadata流的错误。 | +| callback | Callback<[MetadataOutputError](#metadataOutputError)\> | 是 | 回调函数,用于获取错误信息。 | **示例:** ```js -videoOutput.on('error', (VideoOutputError) => { - console.log('Video output error code: ' + VideoOutputError.code); +metadataOutput.on('error', (metadataOutputError) => { + console.log('Metadata output error code: ' + metadataOutputError.code); }) ``` -## VideoOutputErrorCode +## MetadataOutputErrorCode -枚举,视频输出的错误码。 +枚举,metadata输出错误类型。 **系统能力:** SystemCapability.Multimedia.Camera.Core -| 名称 | 值 | 说明 | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | 未知错误。 | +| 名称 | 值 | 说明 | +| ------------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | 未知错误。 | +| ERROR_INSUFFICIENT_RESOURCES | 0 | 资源不足。 | -## VideoOutputError +## MetadataOutputError -视频输出错误对象。 +metadata输出错误码。 **系统能力:** SystemCapability.Multimedia.Camera.Core | 名称 | 类型 | 说明 | | ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | VideoOutput中的错误码。 | \ No newline at end of file +| code | [MetadataOutputErrorCode](#MetadataOutputErrorCode) | MetadataOutput中的错误码。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md b/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md index bbf897d68d49ceea7d709c536e7bbd55600e0567..96d1d56624bb13cb4d835f0ad54399b0181874b5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md @@ -27,11 +27,11 @@ isSupported(feature: number): boolean | -------- | -------- | | boolean | true:支持该类型卡模拟, false:不支持该类型卡模拟。 | -## HceService +## HceService8+ 管理HCE卡模拟。在调用HceService的接口前,需要先通过new cardEmulation.HceService()创建实例。 -### startHCE +### startHCE8+ startHCE(aidList: string[]): boolean @@ -47,7 +47,7 @@ startHCE(aidList: string[]): boolean | ------- | -------- | ---- | ----------------------- | | aidList | string[] | 是 | 注册进行卡模拟的aid列表 | -### stopHCE +### stopHCE8+ stopHCE(): boolean @@ -57,7 +57,7 @@ stopHCE(): boolean **系统能力:** SystemCapability.Communication.NFC.Core -### on +### on8+ on(type: "hceCmd", callback: AsyncCallback): void; @@ -74,7 +74,7 @@ on(type: "hceCmd", callback: AsyncCallback): void; | type | string | 是 | 固定填"hceCmd"字符串 | | callback | AsyncCallback | 是 | 订阅的事件回调,入参是符合APDU协议的数据数组 | -### sendResponse +### sendResponse8+ sendResponse(responseApdu: number[]): void; diff --git a/zh-cn/application-dev/reference/apis/js-apis-contact.md b/zh-cn/application-dev/reference/apis/js-apis-contact.md index fa9d389a4a908ffc790de9dab1c2fa570b0f9eb1..5fb26d1d89e1f091fcf4b059ced545927cf905e0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-contact.md +++ b/zh-cn/application-dev/reference/apis/js-apis-contact.md @@ -1492,7 +1492,7 @@ queryKey(id: number, holder?: Holder): Promise<string> 使用JSON格式创建联系人数据: -```json +```js let myContact = { phoneNumbers: [{ phoneNumber: "138xxxxxxxx" @@ -1538,7 +1538,7 @@ myContact.phoneNumbers = [phoneNumber]; 使用JSON格式创建数据: -```json +```js let contactAttributes = { attributes: [ contact.Attribute.ATTR_EMAIL, @@ -1585,7 +1585,7 @@ contactAttributes.attributes = ["ATTR_EMAIL"]; 使用JSON格式创建数据: -```json +```js let attributes = [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME, contact.Attribute.ATTR_PHONE]; ``` @@ -1621,7 +1621,7 @@ let attributes = [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME, con 使用JSON格式创建数据: -```json +```js let email = { email: "xxx@email.com", displayName: "displayName" @@ -1654,7 +1654,7 @@ email.email = "xxx@email.com"; 使用JSON格式创建数据: -```json +```js let holder = { holderId: 0 }; @@ -1698,7 +1698,7 @@ holder.holderId = 0; 使用JSON格式创建数据: -```json +```js let event = { eventDate: "xxxxxx" }; @@ -1728,7 +1728,7 @@ event.eventDate = "xxxxxx"; 使用JSON格式创建数据: -```json +```js let group = { groupId: 1, title: "title" @@ -1777,7 +1777,7 @@ group.title = "title"; 使用JSON格式创建数据: -```json +```js let imAddress = { imAddress: "imAddress", labelName: "labelName" @@ -1816,7 +1816,7 @@ imAddress.imAddress = "imAddress"; 使用JSON格式创建数据: -```json +```js let name = { familyName: "familyName", fullName: "fullName" @@ -1847,7 +1847,7 @@ name.fullName = "fullName"; 使用JSON格式创建数据: -```json +```js let nickName = { nickName: "nickName" }; @@ -1876,7 +1876,7 @@ nickName.nickName = "nickName"; 使用JSON格式创建数据: -```json +```js let note = { noteContent: "noteContent" }; @@ -1906,7 +1906,7 @@ note.noteContent = "noteContent"; 使用JSON格式创建数据: -```json +```js let organization = { name: "name", title: "title" @@ -1969,7 +1969,7 @@ organization.title = "title"; 使用JSON格式创建数据: -```json +```js let phoneNumber = { phoneNumber: "138xxxxxxxx", labelId: contact.PhoneNumber.NUM_HOME @@ -1999,7 +1999,7 @@ phoneNumber.phoneNumber = "138xxxxxxxx"; 使用JSON格式创建数据: -```json +```js let portrait = { uri: "uri" }; @@ -2050,7 +2050,7 @@ portrait.uri = "uri"; 使用JSON格式创建数据: -```json +```js let postalAddress = { city: "city" }; @@ -2105,7 +2105,7 @@ postalAddress.city = "city"; 使用JSON格式创建数据: -```json +```js let relation = { relationName: "relationName", labelId: contact.Relation.RELATION_ASSISTANT @@ -2150,7 +2150,7 @@ relation.labelId = contact.Relation.RELATION_ASSISTANT; 使用JSON格式创建数据: -```json +```js var sipAddress = { sipAddress: "sipAddress" }; @@ -2179,7 +2179,7 @@ sipAddress.sipAddress = "sipAddress"; 使用JSON格式创建数据: -```json +```js let website = { website: "website" }; diff --git a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md index cbdaec93ae9d5aafc915071a696c5cf9a0ec1d80..bc7145c55e268f1da2a710f6d0f239132cb33ef8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md +++ b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @@ -1,13 +1,14 @@ # ContinuationExtraParams -本模块提供流转管理入口中互联面板所需的过滤参数。 +本模块提供流转管理入口中设备选择模块所需的过滤参数。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** +> > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## ContinuationExtraParams -表示流转管理入口中互联面板所需的过滤参数。 +表示流转管理入口中设备选择模块所需的过滤参数。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.DistributedAbilityManager diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md index ac3e4d5e4c5da4f553e8979f5c972e7338a60308..95217303a70e1311be154fbfd5222bd87d188a99 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @@ -1424,7 +1424,7 @@ query(predicates: RdbPredicates, columns?: Array<string>):Promise<Resul **返回值**: | 类型 | 说明 | | -------- | -------- | -| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | **示例:** ```js @@ -1549,7 +1549,7 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> **返回值**: | 类型 | 说明 | | -------- | -------- | -| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | **示例:** ```js @@ -1638,13 +1638,7 @@ const valueBucket = { "salary": 100.5, "blobType": new Uint8Array([1, 2, 3]), } -rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Insert failed, err: " + err) - return - } - console.log("Insert successfully: " + ret) -}) +await rdbStore.insert("test", valueBucket) rdbStore.commit() ``` @@ -1667,13 +1661,7 @@ const valueBucket = { "blobType": new Uint8Array([1, 2, 3]), } -rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Insert failed, err: " + err) - return - } - console.log("Insert successfully: " + ret) -}) +await rdbStore.insert("test", valueBucket) rdbStore.commit() ``` @@ -1697,13 +1685,7 @@ try { "salary": 100.5, "blobType": new Uint8Array([1, 2, 3]), } - rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Insert failed, err: " + err) - return - } - console.log("Insert successfully: " + ret) - }) + await rdbStore.insert("test", valueBucket) rdbStore.commit() } catch (e) { rdbStore.rollBack() diff --git a/zh-cn/application-dev/reference/apis/js-apis-display.md b/zh-cn/application-dev/reference/apis/js-apis-display.md index 22e041d0a45217c562d4c421d82b9a721f0cfcce..f8eb4826175cd2e1caba1f2a0f89878d8163864e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-display.md +++ b/zh-cn/application-dev/reference/apis/js-apis-display.md @@ -28,29 +28,42 @@ import display from '@ohos.display'; | STATE_VR | 5 | 表示显示设备为VR模式。| | STATE_ON_SUSPEND | 6 | 表示显示设备为开启状态,CPU为挂起状态。 | +## Rect9+ -## Display +矩形区域。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ------ | -------- | ---- | ---- | ------------------ | +| left | number | 是 | 是 | 矩形区域的左边界。 | +| top | number | 是 | 是 | 矩形区域的上边界。 | +| width | number | 是 | 是 | 矩形区域的宽度。 | +| height | number | 是 | 是 | 矩形区域的高度。 | -描述display对象的属性。 +## WaterfallDisplayAreaRects9+ + +瀑布屏曲面部分显示区域。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| id | number | 是 | 否 | 显示设备的id号。| -| name | string | 是 | 否 | 显示设备的名称。| -| alive | boolean | 是 | 否 | 显示设备是否启用。| -| state | [DisplayState](#displaystate) | 是 | 否 | 显示设备的状态。| -| refreshRate | number | 是 | 否 | 显示设备的刷新率。| -| rotation | number | 是 | 否 | 显示设备的屏幕旋转角度。| -| width | number | 是 | 否 | 显示设备的宽度,单位为像素。| -| height | number | 是 | 否 | 显示设备的高度,单位为像素。| -| densityDPI | number | 是 | 否 | 显示设备的屏幕密度,单位为DPI。| -| densityPixels | number | 是 | 否 | 显示设备的屏幕密度,单位为像素。| -| scaledDensity | number | 是 | 否 | 显示设备的显示字体的缩放因子。| -| xDPI | number | 是 | 否 | x方向中每英寸屏幕的确切物理像素值。 | -| yDPI | number | 是 | 否 | y方向中每英寸屏幕的确切物理像素值。| +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ------ | ------------- | ---- | ---- | ------------------ | +| left | [Rect](#rect9) | 是 | 否 | 瀑布曲面区域的左侧矩形区域。 | +| top | [Rect](#rect9) | 是 | 否 | 瀑布曲面区域的顶部矩形区域。 | +| right | [Rect](#rect9) | 是 | 否 | 瀑布曲面区域的右侧矩形区域。 | +| bottom | [Rect](#rect9) | 是 | 否 | 瀑布曲面区域的底部矩形区域。 | + +## CutoutInfo9+ + +挖孔屏、刘海屏、瀑布屏等不可用屏幕区域信息。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| --------------------------- | ------------- | ---- | ---- | ------------------ | +| boudingRects | Array\<[Rect](#rect9)> | 是 | 否 | 挖孔、刘海等区域的边界矩形。 | +| waterfallDisplayAreaRects | [WaterfallDisplayAreaRects](#waterfalldisplayarearects9) | 是 | 否 | 瀑布屏曲面部分显示区域。 | ## display.getDefaultDisplay @@ -252,3 +265,67 @@ off(type: 'add'|'remove'|'change', callback?: Callback<number>): void display.off("remove"); ``` + +## Display +屏幕实例。描述display对象的属性和方法。 + +下列API示例中都需先使用[getAllDisplay()](#displaygetalldisplay)、[getDefaultDisplay()](#displaygetdefaultdisplay)、[getDefaultDisplaySync()](#displaygetdefaultdisplaysync)中的任一方法获取到Display实例,再通过此实例调用对应方法。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| id | number | 是 | 否 | 显示设备的id号。| +| name | string | 是 | 否 | 显示设备的名称。| +| alive | boolean | 是 | 否 | 显示设备是否启用。| +| state | [DisplayState](#displaystate) | 是 | 否 | 显示设备的状态。| +| refreshRate | number | 是 | 否 | 显示设备的刷新率。| +| rotation | number | 是 | 否 | 显示设备的屏幕旋转角度。| +| width | number | 是 | 否 | 显示设备的宽度,单位为像素。| +| height | number | 是 | 否 | 显示设备的高度,单位为像素。| +| densityDPI | number | 是 | 否 | 显示设备的屏幕密度,单位为DPI。| +| densityPixels | number | 是 | 否 | 显示设备的屏幕密度,单位为像素。| +| scaledDensity | number | 是 | 否 | 显示设备的显示字体的缩放因子。| +| xDPI | number | 是 | 否 | x方向中每英寸屏幕的确切物理像素值。 | +| yDPI | number | 是 | 否 | y方向中每英寸屏幕的确切物理像素值。| + +### getCutoutInfo9+ +getCutoutInfo(callback: AsyncCallback<CutoutInfo>): void + +获取挖孔屏、刘海屏、瀑布屏等不可用屏幕区域信息。使用callback异步回调。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[CutoutInfo](#cutoutinfo9)> | 是 | 回调函数。当获取信息成功,err为undefined,data为获取到的CutoutInfo对象;否则err为错误对象。 | + +**示例:** +```js +displayClass.getCutoutInfo((err, data) => { + if (err.code) { + console.error('Failed to get cutoutInfo. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); +}) +``` +### getCutoutInfo9+ +getCutoutInfo(): Promise<CutoutInfo> + +获取挖孔屏、刘海屏、瀑布屏等不可用屏幕区域信息。使用Promise异步回调。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**返回值:** +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<[CutoutInfo](#cutoutinfo9)> | Promise对象,返回描述不可用屏幕区域的CutoutInfo对象。 | + +**示例:** +```js +let promise = displayClass.getCutoutInfo(); +promise.then((data) => { + console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data)); +}); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index 626629182d7da7c388a03a3c4b0aa37168458d71..cc13be1e355381134ed6da2124d4cb0f9d78f03e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -19,8 +19,6 @@ getDistributedAccountAbility(): DistributedAccountAbility 获取分布式帐号单实例对象。 -**系统能力:** SystemCapability.Account.OsAccount - - 返回值: | 类型 | 说明 | | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-huks.md b/zh-cn/application-dev/reference/apis/js-apis-huks.md index e6ab60f61b19eebe48128c5dd85eef3f7de5586d..66863e90ae5a378554052e0f18d2788032882cbe 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-huks.md +++ b/zh-cn/application-dev/reference/apis/js-apis-huks.md @@ -16,7 +16,7 @@ import huks from '@ohos.security.huks' 表示错误码的枚举。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | -------------------------- | ----- | ---- | @@ -59,6 +59,11 @@ import huks from '@ohos.security.huks' | HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |表示存在新的根密钥材料。| | HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |表示更新根密钥材料失败。| | HUKS_ERROR_VERIFICATION_FAILED | -38 |表示验证证书链失败。| +| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |表示获取当前用户安全属性信息失败。| +| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |表示获取当前用户认证信息失败。| +| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |表示不支持当前用户认证类型的访问控制。| +| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |表示安全访问控制认证失败。| +| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |表示设备当前未录入凭据。| | HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |表示检查获取 ALG 失败。| | HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |表示检查获取密钥大小失败。| | HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |表示检查获取填充失败。| @@ -95,7 +100,7 @@ import huks from '@ohos.security.huks' 表示密钥用途。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ------------------------ | ---- | -------------------------------- | @@ -113,7 +118,7 @@ import huks from '@ohos.security.huks' 表示摘要算法。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ---------------------- | ---- | ---------------------------------------- | @@ -130,7 +135,7 @@ import huks from '@ohos.security.huks' 表示补齐算法。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ---------------------- | ---- | ---------------------------------------- | @@ -145,7 +150,7 @@ import huks from '@ohos.security.huks' 表示加密模式。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ------------- | ---- | --------------------- | @@ -160,7 +165,7 @@ import huks from '@ohos.security.huks' 表示密钥长度。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ---------------------------------- | ---- | ------------------------------------------ | @@ -189,7 +194,7 @@ import huks from '@ohos.security.huks' 表示密钥使用的算法。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ------------------------- | ---- | --------------------- | @@ -212,7 +217,7 @@ import huks from '@ohos.security.huks' 表示生成密钥的类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ------------------------------ | ---- | ---------------- | @@ -224,7 +229,7 @@ import huks from '@ohos.security.huks' 表示密钥的产生方式。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | -------------------------- | ---- | ------------------------------------ | @@ -237,7 +242,7 @@ import huks from '@ohos.security.huks' 表示密钥存储方式。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ----------------------- | ---- | ------------------------------ | @@ -248,7 +253,7 @@ import huks from '@ohos.security.huks' 表示发送Tag的方式。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | -------------------- | ---- | ----------------- | @@ -259,7 +264,7 @@ import huks from '@ohos.security.huks' 表示导入加密密钥的算法套件。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ---------------------------------------------- | ---- | ----------------------------------------------------- | @@ -270,7 +275,7 @@ import huks from '@ohos.security.huks' 表示导入密钥的密钥类型,默认为导入公钥,导入对称密钥时不需要该字段。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | ------------------------- | ---- | ------------------------------ | @@ -278,11 +283,69 @@ import huks from '@ohos.security.huks' | HUKS_KEY_TYPE_PRIVATE_KEY | 1 | 表示导入的密钥类型为私钥。 | | HUKS_KEY_TYPE_KEY_PAIR | 2 | 表示导入的密钥类型为公私钥对。 | +## HuksUserAuthType9+ + +表示用户认证类型。 + +**系统能力**:SystemCapability.Security.Huks + +| 名称 | 值 | 说明 | +| ------------------------------- | ---- | ------------------------- | +| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | 表示用户认证类型为指纹。 | +| HUKS_USER_AUTH_TYPE_FACE | 2 | 表示用户认证类型为人脸 。 | +| HUKS_USER_AUTH_TYPE_PIN | 4 | 表示用户认证类型为PIN码。 | + +## HuksAuthAccessType9+ + +表示安全访问控制类型。 + +**系统能力**:SystemCapability.Security.Huks + +| 名称 | 值 | 说明 | +| --------------------------------------- | ---- | ------------------------------------------------ | +| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | 表示安全访问控制类型为清除密码后密钥无效。 | +| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | 表示安全访问控制类型为新录入生物特征后密钥无效。 | + +## HuksChallengeType9+ + +表示密钥使用时生成challenge的类型。 + +**系统能力**:SystemCapability.Security.Huks + +| 名称 | 值 | 说明 | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_TYPE_NORMAL | 0 | 表示challenge为普通类型,默认32字节。 | +| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | 表示challenge为用户自定义类型。支持使用多个密钥仅一次认证。 | +| HUKS_CHALLENGE_TYPE_NONE | 2 | 表示免challenge类型。 | + +## HuksChallengePosition9+ + +表示challenge类型为用户自定义类型时,生成的challenge有效长度仅为8字节连续的数据,且仅支持4种位置 。 + +**系统能力**:SystemCapability.Security.Huks + +| 名称 | 值 | 说明 | +| ------------------------------- | ---- | ------------------------------ | +| HUKS_CHALLENGE_POS_0 | 0 | 表示0~7字节为当前密钥的有效challenge。 | +| HUKS_CHALLENGE_POS_1 | 1 | 表示8~15字节为当前密钥的有效challenge。 | +| HUKS_CHALLENGE_POS_2 | 2 | 表示16~23字节为当前密钥的有效challenge。 | +| HUKS_CHALLENGE_POS_3 | 3 | 表示24~31字节为当前密钥的有效challenge。 | + +## HuksSecureSignType9+ + +表示生成或导入密钥时,指定该密钥的签名类型。 + +**系统能力**:SystemCapability.Security.Huks + +| 名称 | 值 | 说明 | +| ------------------------------ | ---- | ------------------------------------------------------------ | +| HUKS_SECURE_SIGN_WITH_AUTHINFO | 1 | 表示签名类型为携带认证信息。生成或导入密钥时指定该字段,则在使用密钥进行签名时,对待签名的数据添加认证信息后进行签名。 | + ## HuksTagType 表示Tag的数据类型。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | @@ -298,7 +361,7 @@ import huks from '@ohos.security.huks' 表示调用参数的Tag。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 名称 | 值 | 说明 | | -------------------------------------------- | ---------------------------------------- | -------------------------------------- | @@ -336,9 +399,13 @@ import huks from '@ohos.security.huks' | HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | 预留。 | | HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | 预留。 | | HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | 预留。 | -| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | 预留。 | +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | 表示用户认证类型。从[HuksUserAuthType](#huksuserauthtype9)中选择,需要与安全访问控制类型同时设置。支持同时指定两种用户认证类型,如:安全访问控制类型指定为HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL时,密钥访问认证类型可以指定以下三种: HKS_USER_AUTH_TYPE_FACE 、HKS_USER_AUTH_TYPE_FINGERPRINT、HKS_USER_AUTH_TYPE_FACE \| HKS_USER_AUTH_TYPE_FINGERPRINT | | HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | 预留。 | | HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | 预留。 | +| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | 表示安全访问控制类型。从[HuksAuthAccessType](#huksauthaccesstype9)中选择,需要和用户认证类型同时设置。 | +| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | 表示生成或导入密钥时,指定该密钥的签名类型。 | +| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | 表示密钥使用时生成的challenge类型。从[HuksChallengeType](#hukschallengetype9)中选择 | +| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | 表示challenge类型为用户自定义类型时,huks产生的challenge有效长度仅为8字节连续的数据。从[HuksChallengePosition](#hukschallengeposition9)中选择。 | | HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | 表示attestation时的挑战值。 | | HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | 表示attestation时拥有该密钥的application的Id。 | | HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | 表示设备的品牌。 | @@ -387,7 +454,7 @@ generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ 生成密钥,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -488,7 +555,7 @@ deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ 删除密钥,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -547,7 +614,7 @@ getSdkVersion(options: HuksOptions) : string 获取当前系统sdk版本。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -577,7 +644,7 @@ importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ 导入明文密钥,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -694,13 +761,151 @@ var huksoptions = { var result = huks.importKey(keyAlias, huksoptions); ``` +## huks.attestkey9+ + +attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +获取密钥证书,使用Callback方式回调异步返回结果 。 + +**系统能力**:SystemCapability.Security.Huks + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | +| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 | +| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 | + +**示例:** + +```js +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +function printLog(...data) { + console.error(data.toString()); +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + generateKey(aliasString); + setTimeout(()=>huks.attestKey(aliasString, options, function (err, data) { + printLog(`key attest result : ${JSON.stringify(data)}`); + }), 1000); +} +``` + +## huks.attestkey9+ + +attestKey(keyAlias: string, options: HuksOptions) : Promise\ + +获取密钥证书,使用Promise方式异步返回结果 。 + +**系统能力**:SystemCapability.Security.Huks + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | +| keyAlias | string | 是 | 密钥别名,存放待获取证书密钥的别名。 | +| options | [HuksOptions](#huksoptions) | 是 | 用于获取证书时指定所需参数与数据。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | 返回HUKS_SUCCESS时表示接口使用成功,其他时为错误。 | + +**示例:** + +```js +let securityLevel = stringToUint8Array('sec_level'); +let challenge = stringToUint8Array('challenge_data'); +let versionInfo = stringToUint8Array('version_info'); +let keyAliasString = "key attest"; + +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +function printLog(...data) { + console.error(data.toString()); +} + +async function attestKey() { + let aliasString = keyAliasString; + let aliasUint8 = stringToUint8Array(aliasString); + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 + }; + let options = { + properties: properties + }; + generateKey(aliasString); + let result = await huks.exportKey(attestKey, options); + printLog(`key attest result : ${result.errorCode}`); +} +``` + ## huks.importWrappedKey9+ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void 导入加密密钥,使用Callback方式回调异步返回结果 。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -804,8 +1009,8 @@ async function TestImportWrappedKeyFunc( * 假设待导入的密钥为keyA * 1.生成ECC公私钥keyB,公钥为keyB_pub, 私钥为keyB_pri * 2.使用keyB_pri和wrappingAlias密钥中获取的公钥进行密钥协商,协商出共享密钥share_key - * 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1/aad1/加密后的密文keyA_enc/加密后的tag1。 - * 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2/aad2/加密后的密文kek_enc/加密后的tag2。 + * 3.随机生成密钥kek,用于加密keyA,采用AES-GCM加密,加密过程中需要记录:nonce1、aad1、加密后的密文keyA_enc、加密后的tag1。 + * 4.使用share_key加密kek,采用AES-GCM加密,加密过程中需要记录:nonce2、aad2、加密后的密文kek_enc、加密后的tag2。 * 5.拼接importOptions.inData字段,满足以下格式: * keyB_pub的长度(4字节) + keyB_pub的数据 + aad2的长度(4字节) + aad2的数据 + * nonce2的长度(4字节) + nonce2的数据 + tag2的长度(4字节) + tag2的数据 + @@ -888,7 +1093,7 @@ importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOption 导入加密密钥,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -924,7 +1129,7 @@ exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ 导出密钥,使用Promise方式回调异步返回的结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -983,7 +1188,7 @@ getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback 获取密钥属性,使用Callback回调异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -1010,7 +1215,7 @@ getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ 获取密钥属性,使用Promise回调异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -1042,7 +1247,7 @@ isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ 判断密钥是否存在,使用Promise回调异步返回结果 。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -1103,7 +1308,7 @@ init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ init操作密钥接口,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -1131,41 +1336,94 @@ init操作密钥接口,使用Promise方式异步返回结果。 | promise | Promise\<[HuksHandle](#hukshandle)> | 是 | 将Init操作返回的handle添加到密钥管理系统的回调。 | -## huks.update +## huks.update(deprecated) update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void update操作密钥接口,使用Callback回调异步返回结果 。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +> **说明:** 从API Version 9开始废弃,建议使用[huks.update9+](#huksupdate9)替代。 -**参数:** +**系统能力**: SystemCapability.Security.Huks -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------------------------- | -| handle | number | 是 | Update操作的handle。 | -| token | Uint8Array | 否 | Update操作的token。 | -| options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | -------------------------------------------- | +| handle | number | 是 | Update操作的handle。 | +| token | Uint8Array | 否 | Update操作的token。 | +| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | -## huks.update +## huks.update(deprecated) update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ update操作密钥接口,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +> **说明:** 从API Version 9开始废弃,建议使用[huks.update9+](#huksupdate9)替代。 + +**系统能力**: SystemCapability.Security.Huks **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------- | ---- | ------------------------------------- | -| handle | number | 是 | Update操作的handle。 | -| token | Uint8Array | 否 | Update操作的token。 | -| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | -| promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------- | ---- | -------------------------------------------- | +| handle | number | 是 | Update操作的handle。 | +| token | Uint8Array | 否 | Update操作的token。 | +| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | +| promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | + +## huks.update9+ +update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +update操作密钥接口,使用Callback回调异步返回结果 。 + +**系统能力**:SystemCapability.Security.Huks + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | -------------------------------------------- | +| handle | number | 是 | Update操作的handle。 | +| options | [HuksOptions](#huksoptions) | 是 | Update的参数集合。 | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | + + +## huks.update9+ + +update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +update操作密钥接口,使用Callback回调异步返回结果 。 + +**系统能力**:SystemCapability.Security.Huks + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | -------------------------------------------- | +| handle | number | 是 | Update操作的handle。 | +| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | +| token | Uint8Array | 是 | Update操作的token。 | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | + +## huks.update9+ + +update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +update操作密钥接口,使用Promise方式异步返回结果。 + +**系统能力**:SystemCapability.Security.Huks + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------- | ---- | -------------------------------------------- | +| handle | number | 是 | Update操作的handle。 | +| options | [HuksOptions](#huksoptions) | 是 | Update操作的参数集合。 | +| token | Uint8Array | 否 | Update操作的token。 | +| promise | Promise\<[HuksResult](#huksresult)> | 是 | 将Update操作的结果添加到密钥管理系统的回调。 | ## huks.finish @@ -1173,7 +1431,7 @@ finish(handle: number, options: HuksOptions, callback: AsyncCallback\ finish操作密钥接口,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -1198,8 +1456,42 @@ finish操作密钥接口,使用Promise方式异步返回结果。 | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | 是 | Finish操作的handle。 | | options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 | -| promise | Promise\<[HuksResult](#HuksResult)> | 是 | promise实例,用于获取异步返回结果。 | +| promise | Promise\<[HuksResult](#huksresult)> | 是 | promise实例,用于获取异步返回结果。 | + +## huks.finish9+ + +finish(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void + +finish操作密钥接口,使用Callback回调异步返回结果 。 + +**系统能力**:SystemCapability.Security.Huks + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | -------------------------------------------- | +| handle | number | 是 | Finish操作的handle。 | +| options | [HuksOptions](#huksoptions) | 是 | Finish的参数集合。 | +| token | Uint8Array | 是 | Finish操作的token。 | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | 是 | 将Finish操作的结果添加到密钥管理系统的回调。 | + + +## huks.finish9+ + +finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ + +finish操作密钥接口,使用Promise方式异步返回结果。 + +**系统能力**:SystemCapability.Security.Huks + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ----------------------------------- | ---- | ----------------------------------- | +| handle | number | 是 | Finish操作的handle。 | +| options | [HuksOptions](#huksoptions) | 是 | Finish操作的参数集合。 | +| token | Uint8Array | 否 | Finish操作的token。 | +| promise | Promise\<[HuksResult](#Huksresult)> | 是 | promise实例,用于获取异步返回结果。 | ## huks.abort @@ -1207,7 +1499,7 @@ abort(handle: number, options: HuksOptions, callback: AsyncCallback\ abort操作密钥接口,使用Callback回调异步返回结果 。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -1427,7 +1719,7 @@ abort(handle: number, options: HuksOptions) : Promise\; abort操作密钥接口,使用Promise方式异步返回结果。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks **参数:** @@ -1651,49 +1943,49 @@ struct Index { 调用接口使用的options中的properties数组中的param。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------------------- | ---- | ---------- | -| tag | HuksTag | 是 | 标签 | -| value | boolean\|number\|bigint\|Uint8Array | 是 | 标签对应值 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------- | ---- | ------------ | +| tag | [HuksTag](#hukstag) | 是 | 标签。 | +| value | boolean\|number\|bigint\|Uint8Array | 是 | 标签对应值。 | ## HuksOptions 调用接口使用的options。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 参数名 | 类型 | 必填 | 说明 | | ---------- | ----------------- | ---- | ------------------------ | -| properties | Array\ | 否 | 属性,存HuksParam的数组。 | +| properties | Array\<[HuksParam](#huksparam)> | 否 | 属性,用于存HuksParam的数组。 | | inData | Uint8Array | 否 | 输入数据。 | ## HuksHandle huks Handle结构体。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------- | ---- | -------- | -| errorCode | number | 是 | 错误码 | -| handle | number | 是 | handle值 | -| token | Uint8Array | 否 | 预留字段 | +| errorCode | number | 是 | 表示错误码。 | +| handle | number | 是 | 表示handle值。 | +| token | Uint8Array | 否 | 表示[init](#huksinit)操作之后获取到的challenge信息。 | ## HuksResult 调用接口返回的result。 -**系统能力**:以下各项对应的系统能力均为SystemCapability.Security.Huks。 +**系统能力**:SystemCapability.Security.Huks -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ----------------- | ---- | -------- | -| errorCode | number | 是 | 错误码 | -| outData | Uint8Array | 否 | 输出数据 | -| properties | Array\ | 否 | 属性 | -| certChains | Array\ | 否 | 证书链 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------- | ---- | ---------------- | +| errorCode | number | 是 | 表示错误码。 | +| outData | Uint8Array | 否 | 表示输出数据。 | +| properties | Array\<[HuksParam](#huksparam)> | 否 | 表示属性信息。 | +| certChains | Array\ | 否 | 表示证书链数据。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-image.md b/zh-cn/application-dev/reference/apis/js-apis-image.md index 99dce4e19d6327cee1d07f73605d99f6200a5749..f4aeef3b877acfc2634927e33743d707f60a7c07 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-image.md +++ b/zh-cn/application-dev/reference/apis/js-apis-image.md @@ -936,7 +936,7 @@ createImageSource(uri: string, options: SourceOptions): ImageSource | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ----------------------------------- | | uri | string | 是 | 图片路径,当前仅支持应用沙箱路径。 | -| options | [SourceOptions](#SourceOptions) | 是 | 图片属性,包括图片序号与默认属性值。| +| options | [SourceOptions](#sourceoptions9) | 是 | 图片属性,包括图片序号与默认属性值。| **返回值:** @@ -989,7 +989,7 @@ createImageSource(fd: number, options: SourceOptions): ImageSource | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ----------------------------------- | | fd | number | 是 | 文件描述符fd。 | -| options | [SourceOptions](#SourceOptions) | 是 | 图片属性,包括图片序号与默认属性值。| +| options | [SourceOptions](#sourceoptions9) | 是 | 图片属性,包括图片序号与默认属性值。| **返回值:** @@ -1037,7 +1037,7 @@ createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------------------------- | ---- | ------------------------------------ | | buf | ArrayBuffer | 是 | 图像缓冲区数组。 | -| options | [SourceOptions](#SourceOptions) | 是 | 图片属性,包括图片序号与默认属性值。 | +| options | [SourceOptions](#sourceoptions9) | 是 | 图片属性,包括图片序号与默认属性值。 | **返回值:** @@ -1092,7 +1092,7 @@ CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ------------------------------------ | | buf | ArrayBuffer | 是 | 增量数据。 | -| options | [SourceOptions](#SourceOptions) | 否 | 图片属性,包括图片序号与默认属性值。 | +| options | [SourceOptions](#sourceoptions9) | 否 | 图片属性,包括图片序号与默认属性值。 | **返回值:** @@ -2135,11 +2135,12 @@ img.release().then(() =>{ **系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core -| 名称 | 默认值 | 描述 | -| --------- | ------ | ----------------- | -| UNKNOWN | 0 | 未知格式。 | -| RGB_565 | 2 | 格式为RGB_565。 | -| RGBA_8888 | 3 | 格式为RGBA_8888。 | +| 名称 | 默认值 | 描述 | +| ---------------------- | ------ | ----------------- | +| UNKNOWN | 0 | 未知格式。 | +| RGB_565 | 2 | 格式为RGB_565 | +| RGBA_8888 | 3 | 格式为RGBA_8888。 | +| BGRA_88889+ | 4 | 格式为BGRA_8888。 | ## AlphaType9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md index c395dc04ac0700cd5ca2ca218f5383c79aa8cf78..a11614d149bfd2db3c3b8370aeba57ea906f880d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @@ -39,7 +39,7 @@ import inputMethod from '@ohos.inputmethod'; getInputMethodController(): InputMethodController -获取客户端实例[InputMethodController](#InputMethodController)。 +获取客户端实例[InputMethodController](#inputmethodcontroller)。 **系统能力**:SystemCapability.MiscServices.InputMethodFramework @@ -47,7 +47,7 @@ getInputMethodController(): InputMethodController | 类型 | 说明 | | -------- | -------- | - | [InputMethodController](#InputMethodController) | 回调返回当前客户端实例。 | + | [InputMethodController](#inputmethodcontroller) | 回调返回当前客户端实例。 | **示例:** @@ -59,7 +59,7 @@ getInputMethodController(): InputMethodController getInputMethodSetting(): InputMethodSetting -获取客户端设置实例[InputMethodSetting](#InputMethodSetting)。 +获取客户端设置实例[InputMethodSetting](#inputmethodsetting8)。 **系统能力**: SystemCapability.MiscServices.InputMethodFramework @@ -67,7 +67,7 @@ getInputMethodSetting(): InputMethodSetting | 类型 | 说明 | | ----------------------------------------- | ---------------------------- | -| [InputMethodSetting](#InputMethodSetting) | 回调返回当前客户端设置实例。 | +| [InputMethodSetting](#inputmethodsetting8) | 回调返回当前客户端设置实例。 | **示例:** @@ -127,7 +127,7 @@ switchInputMethod(target: InputmethodProperty): Promise<boolean> ``` ## InputMethodController -下列API示例中都需使用[getInputMethodController](#getinputmethodcontroller)回调获取到InputMethodController实例,再通过此实例调用对应方法。 +下列API示例中都需使用[getInputMethodController](#inputmethodgetinputmethodcontroller)回调获取到InputMethodController实例,再通过此实例调用对应方法。 ### stopInput @@ -175,7 +175,7 @@ stopInput(): Promise<boolean> ## InputMethodSetting8+ -下列API示例中都需使用[getInputMethodSetting](#getinputmethodsetting)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。 +下列API示例中都需使用[getInputMethodSetting](#inputmethodgetinputmethodcontroller)回调获取到InputMethodSetting实例,再通过此实例调用对应方法。 ### listInputMethod @@ -188,7 +188,7 @@ listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>) **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------------- | ---- | ---------------------- | -| callback | Array<[InputMethodProperty](#InputMethodProperty)> | 是 | 返回已安装输入法列表。 | +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | 是 | 返回已安装输入法列表。 | **示例:** @@ -212,7 +212,7 @@ listInputMethod(): Array<InputMethodProperty> **返回值:** | 类型 | 说明 | | ----------------------------------------------------------- | ---------------------- | -| Promise> | 返回已安装输入法列表。 | +| Promise> | 返回已安装输入法列表。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index dfc5e94bbb4043fdd0d79e40a10fe4d9cf3d8651..79e539d30e5f18e0a468e6e05cc000ba66115c20 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -1912,13 +1912,11 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1, (err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) + fetchFileResult.getPositionObject(1) .then(function (fileAsset){ + console.log('[Demo] fileAsset.displayName : ' + fileAsset.displayName); + }).catch(function (err) { + console.info("[Demo] getFileAssets failed with error:" + err); + }); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md index f3f3ba733bc56301ba22021a4fbd3edfaa1c92e2..e41944c75170b6c9d36d451a2500dcb77c7586e7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md +++ b/zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @@ -1,5 +1,6 @@ # 剪贴板 + 剪贴板服务主要组件包括剪贴板管理客户端和剪贴板服务。剪贴板管理客户端负责剪贴板接口管理,提供剪贴板北向JS API给应用;在应用框架侧创建剪贴板数据、请求剪贴板SA执行剪贴板的新建、删除、查询、转换文本、配置等。剪贴板服务负责剪贴板事件管理,管理剪贴板SA的生命周期,为系统复制、粘贴功能提供支持。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md index 38c1f1c7be9d1814ef5990dc61516e93975d04de..cadfc12098a6e85805136f8bf78d76705179f657 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @@ -191,7 +191,7 @@ privacyManager.getPermissionUsedRecords(request, (err, data) => { | -------- | -------------- | ---- | ---------------------------------------- | | beginTime | number | 否 | 查询记录的起始时间,单位:ms。 | | endTime | number | 否 | 查询记录的终止时间,单位:ms。 | -| bundleRecords | Array<[BundleUsedRecord](#BundleUsedRecord)> | 否 | 应用的权限使用记录集合。 | +| bundleRecords | Array<[BundleUsedRecord](#bundleusedrecord)> | 否 | 应用的权限使用记录集合。 | ## BundleUsedRecord @@ -205,7 +205,7 @@ privacyManager.getPermissionUsedRecords(request, (err, data) => { | isRemote | boolean | 否 | 默认值false。 | | deviceId | string | 否 | 目标应用所在设备的ID。 | | bundleName | string | 否 | 目标应用的包名。 | -| permissionRecords | Array<[PermissionUsedRecord](#PermissionUsedRecord)> | 否 | 每个应用的权限使用记录集合。 | +| permissionRecords | Array<[PermissionUsedRecord](#permissionusedrecord)> | 否 | 每个应用的权限使用记录集合。 | ## PermissionUsedRecord diff --git a/zh-cn/application-dev/reference/apis/js-apis-request.md b/zh-cn/application-dev/reference/apis/js-apis-request.md index b8d0060ec1db845e8e757d40cc11cd3f14c31435..b0e42ef70ce809931acd3248d1b99bb6d7b0cd6f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-request.md +++ b/zh-cn/application-dev/reference/apis/js-apis-request.md @@ -160,7 +160,7 @@ upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 | + | context | BaseContext | 是 | 基于应用程序的上下文。 | | config | [UploadConfig](#uploadconfig) | 是 | 上传的配置信息。 | @@ -203,7 +203,7 @@ upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<Up | 参数名 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 | + | context | BaseContext | 是 | 基于应用程序的上下文。 | | config | [UploadConfig](#uploadconfig) | 是 | 上传的配置信息。 | | callback | AsyncCallback<[UploadTask](#uploadtask)> | 否 | 回调函数,异步返回UploadTask对象。 | @@ -553,7 +553,7 @@ download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask& | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 | + | context | BaseContext | 是 | 基于应用程序的上下文。 | | config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 | **返回值:** @@ -588,7 +588,7 @@ download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&l | 参数名 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | config | [BaseContext](#baseContext) | 是 | 基于应用程序的上下文。 | + | context | BaseContext | 是 | 基于应用程序的上下文。 | | config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 | | callback | AsyncCallback<[DownloadTask](#downloadtask)> | 否 | 下载接口的回调函数。 | @@ -1118,6 +1118,7 @@ resume(callback: AsyncCallback<void>): void | filePath7+ | string | 否 | 设置下载路径(默认在'internal://cache/'路径下)。
- filePath:'workspace/test.txt':默认路径下创建workspace路径,并将文件存储在workspace路径下。
- filePath:'test.txt':将文件存储在默认路径下。
- filePath:'workspace/':默认路径下创建workspace路径,并将文件存储在workspace路径下。 | | networkType | number | 否 | 设置允许下载的网络类型。 | | title | string | 否 | 设置下载会话标题。 | +| background | boolean | 否 | 后台任务通知开关,开启后可在通知中显示下载状态。 | ## DownloadInfo7+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md index a7df410fcbcd25868c4b0fbb216e7d8916ff7790..a6730e833657cbb840b7f34d41401697c5a27acb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @@ -137,7 +137,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的回调函数。 | **示例:** @@ -170,7 +170,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的回调函数。 | @@ -207,9 +207,15 @@ 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所携带的参数。 | +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | Promise<void> | 返回一个Promise,包含接口的结果。 | + **示例:** ```js @@ -277,6 +283,12 @@ startServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | Promise<void> | 返回一个Promise,包含接口的结果。 | + **示例:** ```js @@ -311,7 +323,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的回调函数。 | **示例:** @@ -345,7 +357,13 @@ 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)。 | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | Promise<void> | 返回一个Promise,包含接口的结果。 | **示例:** @@ -379,8 +397,8 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | -| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +| want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 | +| callback | AsyncCallback\ | 是 | 停止Ability的回调函数。 | **示例:** @@ -409,7 +427,13 @@ stopServiceExtensionAbility(want: Want): Promise\; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | +| want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | Promise<void> | 返回一个Promise,包含接口的结果。 | **示例:** @@ -444,9 +468,9 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 需要启动的accountId。 | -| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +| want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 | +| accountId | number | 是 | 需要停止的系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| callback | AsyncCallback\ | 是 | 停止Ability的回调函数。 | **示例:** @@ -478,8 +502,14 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 需要启动的accountId。 | +| want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 | +| accountId | number | 是 | 需要停止的系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | + +**返回值:** + + | 类型 | 说明 | + | -------- | -------- | + | Promise<void> | 返回一个Promise,包含接口的结果。 | **示例:** @@ -602,7 +632,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 | 否 | 远端对象实例。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md index 06786292b2191a13172f00181d9047d86ed64153..a8a2ef957fda55a51383f73127df8edb805ba0b7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,5 +1,7 @@ # 壁纸 +壁纸管理服务是OpenHarmony中系统服务,是主题框架的部分组成,主要为系统提供壁纸管理服务能力,支持系统显示、设置、切换壁纸等功能。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifi.md b/zh-cn/application-dev/reference/apis/js-apis-wifi.md index 1e1b0112344c5ef4c9b18dc62e292ea1d48413f9..36ca5c551e9b39b493de56f16df955595ea9a687 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wifi.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifi.md @@ -162,14 +162,14 @@ WLAN热点信息。 | ssid | string | 只读 | 热点的SSID,编码格式为UTF-8。 | | bssid | string | 只读 | 热点的BSSID。 | | capabilities | string | 只读 | 热点能力。 | -| securityType | [WifiSecurityType](#WifiSecurityType) | 只读 | WLAN加密类型。 | +| securityType | [WifiSecurityType](#wifisecuritytype) | 只读 | WLAN加密类型。 | | rssi | number | 只读 | 热点的信号强度(dBm)。 | | band | number | 只读 | WLAN接入点的频段。 | | frequency | number | 只读 | WLAN接入点的频率。 | | channelWidth | number | 只读 | WLAN接入点的带宽。 | | centerFrequency09+ | number | 只读 | 中心频点。 | | centerFrequency19+ | number | 只读 | 中心频点。 | -| infoElems9+ | Array<[WifiInfoElem](#WifiInfoElem)> | 只读 | 信息元素。 | +| infoElems9+ | Array<[WifiInfoElem](#wifiinfoelem9)> | 只读 | 信息元素。 | | timestamp | number | 只读 | 时间戳。 | @@ -251,7 +251,7 @@ addDeviceConfig(config: WifiDeviceConfig): Promise<number> **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | **返回值:** | **类型** | **说明** | @@ -270,15 +270,15 @@ WLAN配置信息。 | bssid | string | 只读 | 热点的BSSID。 | | preSharedKey | string | 只读 | 热点的密钥。 | | isHiddenSsid | boolean | 只读 | 是否是隐藏网络。 | -| securityType | [WifiSecurityType](#WifiSecurityType) | 只读 | 加密类型。 | +| securityType | [WifiSecurityType](#wifisecuritytype) | 只读 | 加密类型。 | | creatorUid | number | 只读 | 创建用户的ID,仅系统应用可用。 | | disableReason | number | 只读 | 禁用原因,仅系统应用可用。 | | netId | number | 只读 | 分配的网络ID, 仅系统应用可用。 | | randomMacType | number | 只读 | 随机MAC类型,仅系统应用可用。 | | randomMacAddr | string | 只读 | 随机MAC地址,仅系统应用可用。 | -| ipType | [IpType](#IpType) | 只读 | IP地址类型,仅系统应用可用。 | -| staticIp | [IpConfig](#IpConfig) | 只读 | 静态IP配置信息,仅系统应用可用。 | -| eapConfig9+ | [WifiEapConfig](#WifiEapConfig) | 只读 | 可扩展身份验证协议配置,仅系统应用可用。 | +| ipType | [IpType](#iptype7) | 只读 | IP地址类型,仅系统应用可用。 | +| staticIp | [IpConfig](#ipconfig7) | 只读 | 静态IP配置信息,仅系统应用可用。 | +| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | 只读 | 可扩展身份验证协议配置,仅系统应用可用。 | ## IpType7+ @@ -316,8 +316,8 @@ IP配置信息。 | **参数名** | **类型** | **读写属性** | **说明** | | -------- | -------- | -------- | -------- | -| eapMethod | [EapMethod](#EapMethod) | 只读 | EAP认证方式。 | -| phase2Method | [Phase2Method](#Phase2Method) | 只读 | 第二阶段认证方式。 | +| eapMethod | [EapMethod](#eapmethod9) | 只读 | EAP认证方式。 | +| phase2Method | [Phase2Method](#phase2method9) | 只读 | 第二阶段认证方式。 | | identity | string | 只读 | 身份信息。 | | anonymousIdentity | string | 只读 | 匿名身份。 | | password | string | 只读 | 密码。 | @@ -382,7 +382,7 @@ addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>) **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | | callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。当error为非0,表示处理出现错误。 | @@ -399,7 +399,7 @@ addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | **返回值:** | **类型** | **说明** | @@ -420,7 +420,7 @@ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean& **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | | callback | AsyncCallback<boolean> | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | @@ -437,7 +437,7 @@ removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | **返回值:** | **类型** | **说明** | @@ -458,7 +458,7 @@ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boole **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | | callback | AsyncCallback<boolean> | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | @@ -475,7 +475,7 @@ addCandidateConfig(config: WifiDeviceConfig): Promise<number> **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | **返回值:** | **类型** | **说明** | @@ -496,7 +496,7 @@ addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number&g **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | | callback | AsyncCallback<number> | 是 | 回调函数。当操作成功时,err为0,data为添加的网络配置ID,如果data值为-1,表示添加失败。如果操作出现错误,err为非0值。 | @@ -513,7 +513,7 @@ removeCandidateConfig(config: WifiDeviceConfig): Promise<boolean> **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | **返回值:** | **类型** | **说明** | @@ -534,13 +534,13 @@ removeCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<boole **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | | callback | AsyncCallback<void> | 是 | 回调函数。当操作成功时,err为0,data表示操作结果,true: 成功, false: 失败。如果error为非0,表示处理出现错误。 | ## wifi.getCandidateConfigs9+ -getCandidateConfigs():  Array<[WifiDeviceConfig](#WifiDeviceConfig)> +getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> 获取候选网络配置。 @@ -551,7 +551,7 @@ getCandidateConfigs():  Array<[WifiDeviceConfig](#WifiDeviceConfig)> **返回值:** | **类型** | **说明** | | -------- | -------- | - |  Array<[WifiDeviceConfig](#WifiDeviceConfig)> | 候选网络配置数组。 | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | 候选网络配置数组。 | ## wifi.connectToCandidateConfig9+ @@ -613,7 +613,7 @@ connectToDevice(config: WifiDeviceConfig): boolean **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | **返回值:** | **类型** | **说明** | @@ -675,7 +675,7 @@ getLinkedInfo(): Promise<WifiLinkedInfo> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise<[WifiLinkedInfo](#WifiLinkedInfo)> | Promise对象。表示WLAN连接信息。 | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise对象。表示WLAN连接信息。 | ## wifi.getLinkedInfo @@ -691,7 +691,7 @@ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiLinkedInfo](#WifiLinkedInfo)> | 是 | 回调函数。当获取成功时,err为0,data表示WLAN连接信息。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | 是 | 回调函数。当获取成功时,err为0,data表示WLAN连接信息。如果error为非0,表示处理出现错误。 | **示例:** ```js @@ -735,8 +735,8 @@ getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void | macType9+ | number | 只读 | MAC地址类型。 | | macAddress | string | 只读 | 设备的MAC地址。 | | ipAddress | number | 只读 | WLAN连接的IP地址。 | -| suppState | [SuppState](#SuppState) | 只读 | 请求状态,仅系统应用可用。| -| connState | [ConnState](#ConnState) | 只读 | WLAN连接状态。 | +| suppState | [SuppState](#suppstate) | 只读 | 请求状态,仅系统应用可用。| +| connState | [ConnState](#connstate) | 只读 | WLAN连接状态。 | ## ConnState @@ -879,7 +879,7 @@ getIpInfo(): IpInfo **返回值:** | **类型** | **说明** | | -------- | -------- | - | [IpInfo](#IpInfo) | IP信息。 | + | [IpInfo](#ipinfo7) | IP信息。 | ## IpInfo7+ @@ -951,7 +951,7 @@ reconnect(): boolean ## wifi.getDeviceConfigs7+ -getDeviceConfigs():  Array<[WifiDeviceConfig](#WifiDeviceConfig)> +getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> 获取网络配置。 此接口为系统接口。 @@ -963,7 +963,7 @@ getDeviceConfigs():  Array<[WifiDeviceConfig](#WifiDeviceConfig)> **返回值:** | **类型** | **说明** | | -------- | -------- | - |  Array<[WifiDeviceConfig](#WifiDeviceConfig)> | 网络配置信息的数组。 | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | 网络配置信息的数组。 | ## wifi.updateNetwork7+ @@ -980,7 +980,7 @@ updateNetwork(config: WifiDeviceConfig): boolean **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | 是 | WLAN配置信息。 | + | config | [WifiDeviceConfig](#wifideviceconfig) | 是 | WLAN配置信息。 | **返回值:** | **类型** | **说明** | @@ -1131,7 +1131,7 @@ setHotspotConfig(config: HotspotConfig): boolean **参数:** | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | - | config | [HotspotConfig](#HotspotConfig) | 是 | 热点配置信息。 | + | config | [HotspotConfig](#hotspotconfig7) | 是 | 热点配置信息。 | **返回值:** | **类型** | **说明** | @@ -1148,7 +1148,7 @@ setHotspotConfig(config: HotspotConfig): boolean | **参数名** | **类型** | **读写属性** | **说明** | | -------- | -------- | -------- | -------- | | ssid | string | 只读 | 热点的SSID,编码格式为UTF-8。 | -| securityType | [WifiSecurityType](#WifiSecurityType) | 只读 | 加密类型。 | +| securityType | [WifiSecurityType](#wifisecuritytype) | 只读 | 加密类型。 | | band | number | 只读 | 热点的带宽。1: 2.4G, 2: 5G, 3: 双模频段 | | preSharedKey | string | 只读 | 热点的密钥。 | | maxConn | number | 只读 | 最大设备连接数。 | @@ -1168,12 +1168,12 @@ getHotspotConfig(): HotspotConfig **返回值:** | **类型** | **说明** | | -------- | -------- | - | [HotspotConfig](#HotspotConfig) | 热点的配置信息。 | + | [HotspotConfig](#hotspotconfig7) | 热点的配置信息。 | ## wifi.getStations7+ -getStations():  Array<[StationInfo](#StationInfo)> +getStations():  Array<[StationInfo](#stationinfo7)> 获取连接的设备。 此接口为系统接口。 @@ -1185,7 +1185,7 @@ getStations():  Array<[StationInfo](#StationInfo)> **返回值:** | **类型** | **说明** | | -------- | -------- | - |  Array<[StationInfo](#StationInfo)> | 连接的设备数组。 | + |  Array<[StationInfo](#stationinfo7)> | 连接的设备数组。 | ## StationInfo7+ @@ -1214,7 +1214,7 @@ getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Promise对象。表示P2P连接信息。 | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise对象。表示P2P连接信息。 | @@ -1226,7 +1226,7 @@ getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> | 参数名 | 类型 | 读写属性 | 说明 | | -------- | -------- | -------- | -------- | -| connectState | [P2pConnectState](#P2pConnectState) | 只读 | P2P连接状态。 | +| connectState | [P2pConnectState](#p2pconnectstate8) | 只读 | P2P连接状态。 | | isGroupOwner | boolean | 只读 | 是否是群主。 | | groupOwnerAddr | string | 只读 | 群组MAC地址。 @@ -1256,7 +1256,7 @@ getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | 是 | 回调函数。当操作成功时,err为0,data表示P2P连接信息。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 是 | 回调函数。当操作成功时,err为0,data表示P2P连接信息。如果error为非0,表示处理出现错误。 | ## wifi.getCurrentGroup8+ @@ -1272,7 +1272,7 @@ getCurrentGroup(): Promise<WifiP2pGroupInfo> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Promise对象。表示当前组信息。 | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise对象。表示当前组信息。 | ## wifi.getCurrentGroup8+ @@ -1288,7 +1288,7 @@ getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | 是 | 回调函数。当操作成功时,err为0,data表示当前组信息。如果error为非0,表示处理出现错误。 | ## wifi.getP2pPeerDevices8+ @@ -1304,7 +1304,7 @@ getP2pPeerDevices(): Promise<WifiP2pDevice[]> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise<[WifiP2pDevice[]](#WifiP2pDevice)> | Promise对象。表示对端设备列表信息。 | + | Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise对象。表示对端设备列表信息。 | ## wifi.getP2pPeerDevices8+ @@ -1320,7 +1320,7 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice[]](#WifiP2pDevice)> | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | 是 | 回调函数。当操作成功时,err为0,data表示对端设备列表信息。如果error为非0,表示处理出现错误。 | ## WifiP2pDevice8+ @@ -1334,7 +1334,7 @@ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void | deviceName | string | 只读 | 设备名称。 | | deviceAddress | string | 只读 | 设备MAC地址。 | | primaryDeviceType | string | 只读 | 主设备类型。 | -| deviceStatus | [P2pDeviceStatus](#P2pDeviceStatus) | 只读 | 设备状态。 | +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | 只读 | 设备状态。 | | groupCapabilitys | number | 只读 | 群组能力。 | @@ -1366,7 +1366,7 @@ getP2pLocalDevice(): Promise<WifiP2pDevice> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise<[WifiP2pDevice](#WifiP2pDevice)> | Promise对象。表示本端设备信息。 | + | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise对象。表示本端设备信息。 | ## wifi.getP2pLocalDevice9+ @@ -1382,7 +1382,7 @@ getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice](#WifiP2pDevice)> | 是 | 回调函数。当操作成功时,err为0,data表示本端设备信息。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | 是 | 回调函数。当操作成功时,err为0,data表示本端设备信息。如果error为非0,表示处理出现错误。 | ## wifi.createGroup8+ @@ -1399,7 +1399,7 @@ createGroup(config: WifiP2PConfig): boolean | **参数名** | **类型** | 必填 | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#WifiP2PConfig) | 是 | 群组配置信息。 | + | config | [WifiP2PConfig](#wifip2pconfig8) | 是 | 群组配置信息。 | **返回值:** | 类型 | 说明 | @@ -1419,7 +1419,7 @@ createGroup(config: WifiP2PConfig): boolean | netId | number | 只读 | 网络ID。创建群组时-1表示创建临时组,-2表示创建永久组。 | | passphrase | string | 只读 | 群组密钥。 | | groupName | string | 只读 | 群组名称。 | -| goBand | [GroupOwnerBand](#GroupOwnerBand) | 只读 | 群组带宽。 | +| goBand | [GroupOwnerBand](#groupownerband8) | 只读 | 群组带宽。 | ## GroupOwnerBand8+ @@ -1465,7 +1465,7 @@ p2pConnect(config: WifiP2PConfig): boolean | **参数名** | **类型** | 必填 | **说明** | | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#WifiP2PConfig) | 是 | 连接配置信息。 | + | config | [WifiP2PConfig](#wifip2pconfig8) | 是 | 连接配置信息。 | **返回值:** | 类型 | 说明 | @@ -1624,7 +1624,7 @@ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise< Array<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> > | Promise对象。表示所有群组信息。 | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise对象。表示所有群组信息。 | ## WifiP2pGroupInfo8+ @@ -1636,13 +1636,13 @@ getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> | 参数名 | 类型 | 读写属性 | 说明 | | -------- | -------- | -------- | -------- | | isP2pGo | boolean | 只读 | 是否是群主。 | -| ownerInfo | [WifiP2pDevice](#WifiP2pDevice) | 只读 | 群组的设备信息。 | +| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | 只读 | 群组的设备信息。 | | passphrase | string | 只读 | 群组密钥。 | | interface | string | 只读 | 接口名称。 | | groupName | string | 只读 | 群组名称。 | | networkId | number | 只读 | 网络ID。 | | frequency | number | 只读 | 群组的频率。 | -| clientDevices | [WifiP2pDevice[]](#WifiP2pDevice) | 只读 | 接入的设备列表信息。 | +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | 只读 | 接入的设备列表信息。 | | goIpAddress | string | 只读 | 群组IP地址。 | @@ -1659,7 +1659,7 @@ getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#WifiP2pGroupInfo)>> | 是 | 回调函数。当操作成功时,err为0,data表示所有群组信息。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | 是 | 回调函数。当操作成功时,err为0,data表示所有群组信息。如果error为非0,表示处理出现错误。 | ## wifi.setDeviceName8+ @@ -1961,7 +1961,7 @@ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): vo | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pConnectionChange"字符串。 | - | callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | 是 | 状态改变回调函数。 | + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 是 | 状态改变回调函数。 | ## wifi.off('p2pConnectionChange')8+ @@ -1978,7 +1978,7 @@ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pConnectionChange"字符串。 | - | callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | ## wifi.on('p2pDeviceChange')8+ @@ -1995,7 +1995,7 @@ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pDeviceChange"字符串。 | - | callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | 是 | 状态改变回调函数。 | + | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | 是 | 状态改变回调函数。 | ## wifi.off('p2pDeviceChange')8+ @@ -2012,7 +2012,7 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pDeviceChange"字符串。 | - | callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | + | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | ## wifi.on('p2pPeerDeviceChange')8+ @@ -2029,7 +2029,7 @@ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | - | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | 是 | 状态改变回调函数。 | + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | 是 | 状态改变回调函数。 | ## wifi.off('p2pPeerDeviceChange')8+ @@ -2046,7 +2046,7 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo | **参数名** | **类型** | **必填** | **说明** | | -------- | -------- | -------- | -------- | | type | string | 是 | 固定填"p2pPeerDeviceChange"字符串。 | - | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | 否 | 状态改变回调函数。如果callback不填,将去注册该事件关联的所有回调函数。 | ## wifi.on('p2pPersistentGroupChange')8+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-wifiext.md b/zh-cn/application-dev/reference/apis/js-apis-wifiext.md index 886be03f294d441acb7ef308fdaa0bf78f24f373..9afdcf23bfa5127d0477d8543d0dbeb855f1d29b 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-wifiext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wifiext.md @@ -57,7 +57,7 @@ getSupportedPowerModel(): Promise<Array<PowerModel>> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise<Array<[PowerModel](#PowerModel)>> | Promise对象。表示功率模式。 | + | Promise<Array<[PowerModel](#powermodel)>> | Promise对象。表示功率模式。 | ## PowerModel @@ -86,7 +86,7 @@ getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#PowerModel)> | 是 | 回调函数。当操作成功时,err为0,data表示支持的功率模式。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[PowerModel](#powermodel)> | 是 | 回调函数。当操作成功时,err为0,data表示支持的功率模式。如果error为非0,表示处理出现错误。 | ## wifiext.getPowerModel @@ -102,7 +102,7 @@ getPowerModel(): Promise<PowerModel> **返回值:** | 类型 | 说明 | | -------- | -------- | - | Promise<[PowerModel](#PowerModel)> | Promise对象。表示功率模式。 | + | Promise<[PowerModel](#powermodel)> | Promise对象。表示功率模式。 | ## wifiext.getPowerModel @@ -118,7 +118,7 @@ getPowerModel(callback: AsyncCallback<PowerModel>): void **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#PowerModel)> | 是 | 回调函数。当操作成功时,err为0,data表示功率模式。如果error为非0,表示处理出现错误。 | + | callback | AsyncCallback<[PowerModel](#powermodel)> | 是 | 回调函数。当操作成功时,err为0,data表示功率模式。如果error为非0,表示处理出现错误。 | ## wifiext.setPowerModel @@ -134,7 +134,7 @@ setPowerModel(model: PowerModel) : boolean; **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | model | AsyncCallback<[PowerModel](#PowerModel)> | 是 | 功率模式。 | + | model | AsyncCallback<[PowerModel](#powermodel)> | 是 | 功率模式。 | **返回值:** | **类型** | **说明** | diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index afe53ef7b86fe284054c7855ace5aa2619cb003e..b33a44742d7d5e4dafc522700532f82e34f26ba7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -121,6 +121,21 @@ import window from '@ohos.window'; | AUTO_ROTATION_LANDSCAPE_RESTRICTED | 10 | 表述受开关控制的自动横向旋转模式。 | | LOCKED | 11 | 表示锁定模式。 | +## BlurStyle9+ + +窗口模糊类型枚举。 + +此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +| 名称 | 值 | 说明 | +| ------- | ---- | -------------------- | +| OFF | 0 | 表示关闭模糊。 | +| THIN | 1 | 表示较薄的模糊类型。 | +| REGULAR | 2 | 表示适中的模糊类型。 | +| THICK | 3 | 表示较厚的模糊类型。 | + ## SystemBarRegionTint8+ 单个导航栏或状态栏回调信息。 @@ -2474,9 +2489,9 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void 窗口叠加时,设备有子窗口的情况下设置靠后的窗口的暗度值,使用callback异步回调。 -> **说明:** 从API version 9开始废弃。该API不支持使用。 -> -> 从 API version 7开始支持。 +> **说明:** 该接口不支持使用。 +> +> 从API version 9开始废弃。从API Version 7开始支持。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -2505,9 +2520,9 @@ setDimBehind(dimBehindValue: number): Promise<void> 窗口叠加时,设备有子窗口的情况下设置靠后的窗口的暗度值,使用Promise异步回调。 -> **说明:** 从API version 9开始废弃。该API不支持使用。 +> **说明:** 该接口不支持使用。 > -> 从 API version 7开始支持。 +> 从API version 9开始废弃。从API Version 7开始支持。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -2660,9 +2675,9 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): vo 设置是否允许可点击子窗口之外的区域,使用callback异步回调。 -> **说明:** 从API version 9开始废弃。该API不支持使用。 +> **说明:** 该接口不支持使用。 > -> 从 API version 7开始支持。 +> 从API version 9开始废弃。从API Version 7开始支持。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -2691,9 +2706,9 @@ setOutsideTouchable(touchable: boolean): Promise<void> 设置是否允许可点击子窗口之外的区域,使用Promise异步回调。。 -> **说明:** 从API version 9开始废弃。该API不支持使用。 +> **说明:** 该接口不支持使用。 > -> 从 API version 7开始支持。 +> 从API version 9开始废弃。从 API version 7开始支持。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -2979,6 +2994,119 @@ promise.then((pixelMap)=> { }); ``` +### setBlur9+ + +setBlur(radius: number): void + +设置窗口模糊。 + +此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | 是 | 表示窗口模糊的半径值,取值范围为大于等于0,0表示关闭窗口模糊。 | + +**示例:** + +```js +windowClass.setBlur(4.0); +``` + +### setBackdropBlur9+ + +setBackdropBlur(radius: number): void + +设置窗口背景模糊。 + +此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | 是 | 表示窗口背景模糊的半径值,取值范围为大于等于0,0表示关闭窗口背景模糊。 | + +**示例:** + +```js +windowClass.setBackdropBlur(4.0); +``` + +### setBackdropBlurStyle9+ + +setBackdropBlurStyle(blurStyle: BlurStyle): void + +设置窗口背景模糊类型。 + +此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | --------- | ---- | ---------------------- | +| blurStyle | [BlurStyle](#blurstyle9) | 是 | 表示窗口背景模糊类型。 | + +**示例:** + +```js +windowClass.setBackdropBlurStyle(window.BlurType.THIN); +``` + +### setShadow9+ + +setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void + +设置窗口边缘阴影。 + +此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| radius | number | 是 | 表示窗口边缘阴影的模糊半径,取值范围为大于等于0,0表示关闭窗口边缘阴影。 | +| color | string | 否 | 表示窗口边缘阴影的颜色,为十六进制颜色,不区分大小写,例如`#00FF00`或`#FF00FF00`。 | +| offsetX | number | 否 | 表示窗口边缘阴影的X轴的偏移量,单位为px。 | +| offsetY | number | 否 | 表示窗口边缘阴影的Y轴的偏移量,单位为px。 | + +**示例:** + +```js +windowClass.setShadow(4.0, '#FF00FF00', 2, 3); +``` + +### setCornerRadius9+ + +setCornerRadius(cornerRadius: number): void + +设置窗口圆角半径。 + +此接口为系统接口。 + +**系统能力:** SystemCapability.WindowManager.WindowManager.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------- | ---- | -------------------- | +| radius | number | 是 | 表示窗口圆角的半径值,取值范围为大于等于0,0表示没有窗口圆角。 | + +**示例:** + +```js +windowClass.setCornerRadius(4.0); +``` + ## WindowStageEventType9+ WindowStage生命周期。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md b/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md index 898c5117ba3283d96a67a2d93f4b53921f7e2b67..899d41aa44381b69b70098dd08de49c5e61738d8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @@ -278,7 +278,7 @@ isLastWorkTimeOut(workId: number): Promise\ ``` ## WorkInfo -提供工作的具体信息。 +提供工作的具体信息。WorkInfo设置参数约束见[延迟任务调度概述](../../task-management/work-scheduler-overview.md) **系统能力**:SystemCapability.ResourceSchedule.WorkScheduler diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 45a65bb736a911522458d2a7f5ead8ce687d1218..662ee7143260064add5d3defcd473d823a5af274 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -7,7 +7,7 @@ Worker是与主线程并行的独立线程。创建Worker的线程称之为宿 ## 导入模块 -``` +```js import worker from '@ohos.worker'; ``` @@ -50,7 +50,7 @@ Worker构造函数。 | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| scriptURL | string | 是 | Worker执行脚本的url,路径规范:若DevEco Studio新建工程在pages同级下没有workers目录,需要新建workers目录,将脚本文件放入workers目录。 | +| scriptURL | string | 是 | Worker执行脚本的url。
在FA和Stage模型下,DevEco Studio新建Worker工程路径分别存在以下两种情况:
(a) workers目录与pages目录同级。
(b) workers目录与pages目录不同级。 | options | [WorkerOptions](#workeroptions) | 否 | Worker构造的选项。 | **返回值:** @@ -61,11 +61,68 @@ Worker构造函数。 **示例:** -``` +```js +// worker线程创建 + +// FA模型-目录同级 const workerInstance = new worker.Worker("workers/worker.js", {name:"first worker"}); +// FA模型-目录不同级(以workers目录放置pages目录前一级为例) +const workerInstance = new worker.Worker("../workers/worker.js", {name:"first worker"}); + +// Stage模型-目录同级 +const workerInstance = new worker.Worker('entry/ets/workers/worker.ts'); +// Stage模型-目录不同级(以workers目录放置pages目录后一级为例) +const workerInstance = new worker.Worker('entry/ets/pages/workers/worker.ts'); + +// scriptURL——"entry/ets/workers/worker.ts"的解释: +// entry: 为module.json5中module中name属性的值; +// ets: 表明当前使用的语言。 +``` +同时,需在工程目录下build-profile.json5文件的buildOption属性中添加配置信息,主要分为下面两种情况: + +(1) 目录同级( **不添加也可以** ) +FA模型: + +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/MainAbility/workers/worker.ts" + ] + } + } +``` +Stage模型: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] + } + } +``` +(2) 目录不同级( **必须添加** ) +FA模型: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] + } + } +``` +Stage模型: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/pages/workers/worker.ts" + ] + } + } ``` - - ### postMessage postMessage(message: Object, options?: PostMessageOptions): void @@ -83,12 +140,9 @@ postMessage(message: Object, options?: PostMessageOptions): void **示例:** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.postMessage("hello world"); -``` - -``` const workerInstance= new worker.Worker("workers/worker.js"); var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); @@ -112,8 +166,8 @@ on(type: string, listener: EventListener): void **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); }) @@ -137,7 +191,7 @@ once(type: string, listener: EventListener): void **示例:** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); @@ -162,7 +216,7 @@ off(type: string, listener?: EventListener): void **示例:** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.off("alert"); ``` @@ -178,9 +232,9 @@ terminate(): void **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.terminate() +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.terminate(); ``` @@ -200,10 +254,10 @@ Worker对象的onexit属性表示Worker退出时被调用的事件处理程序 **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onexit = function(e) { - console.log("onexit") + console.log("onexit"); } ``` @@ -224,10 +278,10 @@ Worker对象的onerror属性表示Worker在执行过程中发生异常被调用 **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onerror = function(e) { - console.log("onerror") + console.log("onerror"); } ``` @@ -248,10 +302,12 @@ Worker对象的onmessage属性表示宿主线程接收到来自其创建的Worke **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onmessage = function(e) { - console.log("onerror") + // e : MessageEvent, 用法如下: + // let data = e.data; + console.log("onmessage"); } ``` @@ -272,10 +328,10 @@ Worker对象的onmessageerror属性表示当Worker对象接收到一条无法被 **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onmessageerror= function(e) { - console.log("onmessageerror") + console.log("onmessageerror"); } ``` @@ -300,8 +356,8 @@ addEventListener(type: string, listener: EventListener): void **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -325,9 +381,9 @@ removeEventListener(type: string, callback?: EventListener): void **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.removeEventListener("alert") +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.removeEventListener("alert"); ``` @@ -353,9 +409,9 @@ dispatchEvent(event: Event): boolean **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.dispatchEvent({type:"alert"}) +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.dispatchEvent({type:"alert"}); ``` @@ -369,9 +425,9 @@ removeAllListener(): void **示例:** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.removeAllListener({type:"alert"}) +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.removeAllListener(); ``` @@ -397,22 +453,23 @@ Worker向宿主线程发送消息。 **示例:** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.postMessage("hello world") +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { - console.log("receive data from worker.js") + // let data = e.data; + console.log("receive data from worker.js"); } ``` - -``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ - parentPort.postMessage("receive data from main.js") + // let data = e.data; + parentPort.postMessage("receive data from main.js"); } ``` @@ -427,13 +484,12 @@ close(): void **示例:** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -``` - +const workerInstance = new worker.Worker("workers/worker.js"); ``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; @@ -459,19 +515,18 @@ DedicatedWorkerGlobalScope的onmessage属性表示Worker线程收到来自其宿 **示例:** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.postMessage("hello world") -``` - +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("hello world"); ``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { - console.log("receive main.js message") + console.log("receive main.js message"); } ``` @@ -492,13 +547,12 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当Worker对象接收到 **示例:** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -``` - +const workerInstance = new worker.Worker("workers/worker.js"); ``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; @@ -556,7 +610,7 @@ parentPort.onmessageerror= function(e) { **示例:** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -620,17 +674,107 @@ WorkerGlobalScope的onerror属性表示Worker在执行过程中发生异常被 **示例:** -``` +```js // main.js import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.js") ``` - -``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort parentPort.onerror = function(e){ console.log("worker.js onerror") } +``` + +## 完整示例 +### FA模型 +```js +// main.js(同级目录为例) +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("workers/worker.ts"); +// 创建js和ts文件都可以 +// const workerInstance = new worker.Worker("workers/worker.js"); + +workerInstance.postMessage("123"); +workerInstance.onmessage = function(e) { + let data = e.data; + console.log("main.js onmessage"); + // 接收worker线程信息后执行terminate + workerInstance.terminate(); +} +// 在调用terminate后,执行onexit +workerInstance.onexit = function() { + console.log("main.js terminate"); +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort + +parentPort.onmessage = function(e) { + let data = e.data; + console.log("worker.js onmessage"); + parentPort.postMessage("123") +} + +parentPort.onerror= function(e) { + console.log("worker.js onerror"); +} +``` +build-profile.json5 配置 : +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/MainAbility/workers/worker.ts" + ] + } + } +``` +### Stage模型 +```js +// main.js(以不同目录为例) +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.ts"); +// 创建js和ts文件都可以 +// const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.js"); +workerInstance.postMessage("123"); +workerInstance.onmessage = function(e) { + let data = e.data; + console.log("main.js onmessage"); + // 接收worker线程信息后执行terminate + workerInstance.terminate(); +} +// 在调用terminate后,执行onexit +workerInstance.onexit = function() { + console.log("main.js terminate"); +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort + +parentPort.onmessage = function(e) { + let data = e.data; + console.log("worker.js onmessage"); + parentPort.postMessage("123") +} + +parentPort.onerror= function(e) { + console.log("worker.js onerror"); +} +``` +build-profile.json5 配置: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/pages/workers/worker.ts" + ] + } + } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index 1695c7d920128c10e0d842c1dfe1a174bc5aa3bc..8fd364541585acd19e53464a98d25a675b889425 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -38,6 +38,7 @@ - [组件标识](ts-universal-attributes-component-id.md) - [触摸热区设置](ts-universal-attributes-touch-target.md) - [多态样式](ts-universal-attributes-polymorphic-style.md) + - [触摸测试控制](ts-universal-attributes-hit-test-behavior.md) - 手势处理 - [绑定手势方法](ts-gesture-settings.md) - 基础手势 diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg index b12c5fb6563c7ee9d8dfa7e6af1cfe1dcfa1361c..e5af4f50ebd9bdab6af30219f30fdf948a019a52 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001236876377.jpg differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index ed99d0137cd965b927013eda6897a0ee0040d528..1eb4e1283c1c98c888489b5dbfa1e75ae33d488d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -53,45 +53,47 @@ CheckboxGroup( group?: string ) @Entry @Component struct CheckboxExample { - build() { Scroll() { Column() { - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){ - CheckboxGroup({group : 'checkboxGroup'}) - .selectedColor(0xed6f21) - .onChange((itemName:CheckboxGroupResult) => { - console.info("TextPicker::dialogResult is" + JSON.stringify(itemName)) - }) - Text('select all').fontSize(20) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){ - Checkbox({ name: 'checkbox1', group: 'checkboxGroup' }) - .select(true) - .selectedColor(0x39a2db) - .onChange((value: boolean) => { - console.info('Checkbox1 change is' + value) - }) - Text('Checkbox1').fontSize(20) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){ - Checkbox({ name: 'checkbox2', group: 'checkboxGroup' }) - .select(false) - .selectedColor(0x39a2db) - .onChange((value: boolean) => { - console.info('Checkbox2 change is' + value) - }) - Text('Checkbox2').fontSize(20) - } - Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }){ - Checkbox({ name: 'checkbox3', group: 'checkboxGroup' }) - .select(true) - .selectedColor(0x39a2db) - .onChange((value: boolean) => { - console.info('Checkbox3 change is' + value) - }) - Text('Checkbox3').fontSize(20) - } + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + CheckboxGroup({ group: 'checkboxGroup' }) + .selectedColor(0xed6f21) + .onChange((itemName: CheckboxGroupResult) => { + console.info("TextPicker::dialogResult is" + JSON.stringify(itemName)) + }) + Text('select all').fontSize(20) + } + + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox1', group: 'checkboxGroup' }) + .select(true) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox1 change is' + value) + }) + Text('Checkbox1').fontSize(20) + } + + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox2', group: 'checkboxGroup' }) + .select(false) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox2 change is' + value) + }) + Text('Checkbox2').fontSize(20) + } + + Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { + Checkbox({ name: 'checkbox3', group: 'checkboxGroup' }) + .select(true) + .selectedColor(0x39a2db) + .onChange((value: boolean) => { + console.info('Checkbox3 change is' + value) + }) + Text('Checkbox3').fontSize(20) + } } } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index 48d2d22bc117b96b700739d129e12a6cb1827c63..0898543bf6b745b7a166d1bfe0a41f0342b0772a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -50,7 +50,8 @@ Image(src: string | PixelMap | Resource) | interpolation | [ImageInterpolation](#imageinterpolation) | ImageInterpolation.None | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。
> **说明:**
> - svg类型图源不支持该属性。
> - PixelMap资源不支持该属性。 | | renderMode | [ImageRenderMode](#imagerendermode) | ImageRenderMode.Original | 设置图片渲染的模式。
> **说明:**
> - svg类型图源不支持该属性。 | | sourceSize | {
width: number,
height: number
} | - | 设置图片裁剪尺寸,将原始图片解码成pixelMap,指定尺寸的图片,单位为px。
> **说明:**
> PixelMap资源不支持该属性。 | -| syncLoad8+ | boolean | false | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。 | +| syncLoad8+ | boolean | false | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。 | +| copyOption9+ | boolean\|[CopyOption](#copyoption) | false | 设置图片是否可复制(SVG图片不支持复制)。 | ### ImageFit @@ -78,6 +79,14 @@ Image(src: string | PixelMap | Resource) | Original | 按照原图进行渲染,包括颜色。 | | Template | 将图片渲染为模板图片,忽略图片的颜色信息。 | +### CopyOption9+ + + | 名称 | 描述 | + | -------- | -------- | + | InApp | 支持应用内复制粘贴。 | + | LocalDevice | 支持设备内复制粘贴。 | + | CrossDevice | 支持跨设备复制粘贴。 | + ## 事件 除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md index 290c065e01ab19dda9b62fda3739171d764f6d86..b7b0543679eab4ca33d6d88e88f3ab3144f977d0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-select.md @@ -53,16 +53,16 @@ Select(options: Array\) struct SelectExample { build() { Column() { - Select([{value:'aaa',icon: "/common/1.png"}, - {value:'bbb',icon: "/common/2.png"}, - {value:'ccc',icon: "/common/3.png"}, - {value:'ddd',icon: "/common/4.png"}]) + Select([{ value: 'aaa', icon: "/common/1.png" }, + { value: 'bbb', icon: "/common/2.png" }, + { value: 'ccc', icon: "/common/3.png" }, + { value: 'ddd', icon: "/common/4.png" }]) .selected(2) .value('TTT') - .font({size: 30, weight:400, family: 'serif', style: FontStyle.Normal }) - .selectedOptionFont({size: 40, weight: 500, family: 'serif', style: FontStyle.Normal }) - .optionFont({size: 30, weight: 400, family: 'serif', style: FontStyle.Normal }) - .onSelect((index:number)=>{ + .font({ size: 30, weight: 400, family: 'serif', style: FontStyle.Normal }) + .selectedOptionFont({ size: 40, weight: 500, family: 'serif', style: FontStyle.Normal }) + .optionFont({ size: 30, weight: 400, family: 'serif', style: FontStyle.Normal }) + .onSelect((index: number) => { console.info("Select:" + index) }) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md index 4e57b1813c3091e0fdb802d955c64f12613d0c64..d8cb0bb3008facedca47015abeb1270802e1f9a9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-stepper.md @@ -63,47 +63,50 @@ struct StepperExample { .fontColor(Color.Blue) .width(200) .lineHeight(50) - .margin({top:250}) + .margin({ top: 250 }) } .nextLabel('') - .position({x: '35%', y: 0}) + .position({ x: '35%', y: 0 }) + StepperItem() { Text('Page Two') .fontSize(35) .fontColor(Color.Blue) .width(200) .lineHeight(50) - .margin({top:250}) - .onClick(()=>{ + .margin({ top: 250 }) + .onClick(() => { this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip }) } .nextLabel('Next') .prevLabel('Previous') .status(this.firstState) - .position({x: '35%', y: 0}) + .position({ x: '35%', y: 0 }) + StepperItem() { Text('Page Three') .fontSize(35) .fontColor(Color.Blue) .width(200) .lineHeight(50) - .margin({top:250}) - .onClick(()=>{ + .margin({ top: 250 }) + .onClick(() => { this.secondState = this.secondState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting }) } - .position({x: '35%', y: 0}) + .position({ x: '35%', y: 0 }) .status(this.secondState) + StepperItem() { Text('Page four') .fontSize(35) .fontColor(Color.Blue) .width(200) .lineHeight(50) - .margin({top:250}) + .margin({ top: 250 }) } - .position({x: '35%', y: 0}) + .position({ x: '35%', y: 0 }) .nextLabel('Finish') } .onFinish(() => { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md index 6f80bffcacf25c553d6d11f380a4195131ce3cb2..9c36c5f32c78b870089b7c97de46611da195d046 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-textclock.md @@ -21,7 +21,7 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | -------- | -------- | ---- | ------------------ | ------------------------------------------------------------ | -| timeZoneOffset | number | 否 | 时区偏移量 | 设置时区偏移量。
取值范围为[-14:00, 12:00],表示东十二区到西十二区,其中负值表示东时区,正值表示西时区,比如东八区为-8:00。
对横跨国际日界线的国家或地区,用-13:00(UTC+13)和-14:00(UTC+14)来保证整个国家或者区域处在相同的时间。 | +| timeZoneOffset | number | 否 | 当前系统的时区偏移量 | 设置时区偏移量。
取值范围为[-14, 12],表示东十二区到西十二区,其中负值表示东时区,正值表示西时区,比如东八区为-8。
对横跨国际日界线的国家或地区,用-13(UTC+13)和-14(UTC+14)来保证整个国家或者区域处在相同的时间,当设置的值不在取值范围内时,将使用当前系统的时区偏移量。 | | contorller | [TextClockContorller](#textclockcontroller) | 否 | null | 绑定一个控制器,用来控制文本时钟的状态。| ## 属性 @@ -30,7 +30,7 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController | 名称 | 参数类型 | 默认值 | 描述 | | ------ | -------- | -------- | ------------------------------------------------------------ | -| format | string | 'hhmmss' | 设置显示时间格式,如“yyyy/mm/dd”、“yyyy-mm-dd”等。
支持的时间格式化字符串:
- yyyy:年份。
- mm:英文月份简写。
- mmm:英文月份简写。
- mmmm:英文月份全称。
- dd:英文星期简写。
- ddd:英文星期简写。
- dddd:英文星期全称。
- HH:24小时制。
- hh:12小时制。
- MM/mm:分钟。
- SS/ss:秒。 | +| format | string | 'hms' | 设置显示时间格式。
日期间隔符固定为"/",时间间隔符为":"。
如yyyyMMdd,yyyy-MM-dd显示为yyyy/MM/dd,
hhmmss显示为hh:mm:ss。
时间格式只用写一位即可,如"hhmmss"等同于"hms"。
支持的时间格式化字符串:
- YYYY/yyyy:完整年份。
- YY/yy:年份后两位。
- M:月份(若想使用01月则使用MM)。
- d:日期(若想使用01日则使用dd)。
- D:年中日(一年中的第几天)。
- H:24小时制。
- h:12小时制。
- m:分钟。
- s:秒。
- SSS:毫秒。| ## 事件 @@ -73,27 +73,27 @@ struct Second { controller: TextClockController = new TextClockController() build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center}) { - Text('Current milliseconds is ' + this.accumulateTime) - .fontSize(20) - // 以12小时制显示东八区的系统时间,精确到秒。 - TextClock({timeZoneOffset: -8, controller: this.controller}) - .format('hhmmss') - .onDateChange((value: number) => { - this.accumulateTime = value - }) - .margin(20) - .fontSize(30) - Button("start TextClock") - .margin({ bottom: 10 }) - .onClick(()=>{ - this.controller.start() - }) - Button("stop TextClock") - .onClick(()=>{ - this.controller.stop() - }) - } + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Current milliseconds is ' + this.accumulateTime) + .fontSize(20) + // 以12小时制显示东八区的系统时间,精确到秒。 + TextClock({ timeZoneOffset: -8, controller: this.controller }) + .format('hms') + .onDateChange((value: number) => { + this.accumulateTime = value + }) + .margin(20) + .fontSize(30) + Button("start TextClock") + .margin({ bottom: 10 }) + .onClick(() => { + this.controller.start() + }) + Button("stop TextClock") + .onClick(() => { + this.controller.stop() + }) + } .width('100%') .height('100%') } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md index 5250682fe76350b21c831f0245d5458ac83d6efc..afcdae8754a0fce1ea876c3a0d8142a3dbec6300 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-badge.md @@ -89,8 +89,8 @@ struct BadgeExample { }.width(80).height(50) Badge({ - value: '', - position: BadgePosition.Right, + value: ' ', + position: 1, style: { badgeSize: 6, badgeColor: Color.Red } }) { Text('message') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md index 36959733612a951be41c2149c7ceca7e4c9a4a8e..8bb8b3941407b4d87c412161d1b0453a75865348 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-panel.md @@ -4,7 +4,7 @@ > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -可滑动面板。提供一种轻量的内容展示的窗口,可方便的在不同尺寸中切换,属于弹出式组件。 +可滑动面板,提供一种轻量的内容展示窗口,方便在不同尺寸中切换。 ## 权限列表 @@ -37,6 +37,7 @@ Panel(value:{show:boolean}) | fullHeight | Length | - | 指定PanelMode.Full状态下的高度。 | | halfHeight | Length | - | 指定PanelMode.Half状态下的高度,默认为屏幕尺寸的一半。 | | miniHeight | Length | - | 指定PanelMode.Mini状态下的高度。 | +| backgroundMask9+|(color: ResourceColor)| - |指定Panel的背景蒙层。| - PanelType枚举说明 | 名称 | 描述 | @@ -58,7 +59,7 @@ Panel(value:{show:boolean}) | 名称 | 功能描述 | | -------- | -------- | | onChange(callback: (width: number, height: number, mode: PanelMode) => void) | 当可滑动面板发生状态变化时触发, 返回的height值为内容区高度值,当dragbar属性为true时,panel本身的高度值为dragbar高度加上内容区高度。 | - +| onHeightChange(callback: (value: number) => void)9+ |当可滑动面板发生高度变化时触发,返回的height值为内容区高度值,当dragbar属性为true时,panel本身的高度值为dragbar高度加上内容区高度。因用户体验设计原因,panel最高只能滑到 fullHeight-8vp | ## 示例 @@ -70,7 +71,7 @@ struct PanelExample { @State show: boolean = false build() { - Column() { + Stack() { Text('2021-09-30 Today Calendar: 1.afternoon......Click for details') .width('90%').height(50).borderRadius(10) .backgroundColor(0xFFFFFF).padding({ left: 20 }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md index df2ace39644d48184188f66496ca8e03e40b48ed..4fa205a6d17c448a23c7036382a17dba00f84a21 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-refresh.md @@ -21,7 +21,7 @@ Refresh\(value: \{refreshing: boolean, offset?: Length, friction?: number | stri | 参数 | 参数名 | 必填 | 默认值 | 参数描述 | | -------- | -------- | -------- | -------- | -------- | - | refreshing | boolean | 是 | - | 当前组件是否正在刷新。 | + | refreshing | boolean | 是 | - | 当前组件是否正在刷新。
该参数支持[$$](../../ui/ts-syntactic-sugar.md)双向绑定变量。 | | offset | Length | 否 | 16 | 刷新组件静止时距离父组件顶部的距离。| | friction | number \| string | 否 | 62 | 下拉摩擦系数,取值范围为0到100。
- 0表示下拉刷新容器不跟随手势下拉而下拉。
- 100表示下拉刷新容器紧紧跟随手势下拉而下拉。
- 数值越大,下拉刷新容器跟随手势下拉的反应越灵敏。 | @@ -58,7 +58,7 @@ struct RefreshExample { build() { Column() { - Refresh({refreshing: this.isRefreshing, offset: 120, friction: 100}) { + Refresh({refreshing: $$this.isRefreshing, offset: 120, friction: 100}) { Text('Pull Down and refresh: ' + this.counter) .fontSize(30) .margin(10) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index 6217c50da6b0fd7d2eec01b7d3b98a59b372ebf9..7bcd121930a08b8e892d31cda640625c455117c4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -43,6 +43,7 @@ SideBarContainer( type?: SideBarContainerType ) | minSideBarWidth | number \| [Length9+](../../ui/ts-types.md#长度类型) | 200 | 设置侧边栏最小宽度。 | | maxSideBarWidth | number \| [Length9+](../../ui/ts-types.md#长度类型) | 280 | 设置侧边栏最大宽度。 | | autoHide9+ | boolean | true | 设置当侧边栏拖拽到小于最小宽度后,是否自动隐藏。 | +| sideBarPosition9+ | SideBarPosition | SideBarPosition.Start | 设置侧边栏显示位置。 | - ButtonStyle对象说明 | 名称 | 参数类型 | 必填 | 默认值 | 描述 | @@ -53,6 +54,11 @@ SideBarContainer( type?: SideBarContainerType ) | height | number | 否 | 32 | 设置侧边栏控制按钮的高度。 | | icons | {
shown: string \| PixelMap \| [Resource](../../ui/ts-types.md) ,
hidden: string \| PixelMap \| [Resource](../../ui/ts-types.md) ,
switching?: string \| PixelMap \| [Resource](../../ui/ts-types.md)
} | 否 | - | 设置侧边栏控制按钮的图标:

- shown: 设置侧边栏显示时控制按钮的图标。
- hidden: 设置侧边栏隐藏时控制按钮的图标。
- switching:设置侧边栏显示和隐藏状态切换时控制按钮的图标。 | +- SideBarPosition9+枚举说明 + | 名称 | 描述 | + | -------- | -------- | + | Start | 侧边栏位于容器左侧。 | + | End | 侧边栏位于容器右侧。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md index 20e5fafc7e541a777b61d16ae3199c2fcae4d1fa..7a64be6a6bd8d668babfb0738660eb53aba8f0de 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-menu.md @@ -3,39 +3,48 @@ 在页面范围内关闭通过[bindContextMenu](./ts-universal-attributes-menu.md#属性)属性绑定的菜单。 > **说明:** -> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 权限列表 + +无 + ## ContextMenu.close |方法|描述| |----|---| | close(): void | 可以通过该方法在页面范围内关闭通过[bindContextMenu](./ts-universal-attributes-menu.md#属性)给组件绑定的菜单。 | -- 示例 -``` + +## 示例 + +```ts // xxx.ets @Entry - @Component - struct Index { - @Builder MenuBuilder(){ - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('close') - .fontSize(30) - .fontWeight(FontWeight.Bold) - .onClick(() => { - ContextMenu.close(); - }) - }.height(400) - .backgroundColor(Color.Pink) - - } - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) { - Column(){ - Text("Text") - }.bindContextMenu(this.MenuBuilder, ResponseType.LongPress) - } - .width('100%') - .height('100%') +@Component +struct Index { + @Builder MenuBuilder() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('close') + .fontSize(30) + .fontWeight(FontWeight.Bold) + .onClick(() => { + ContextMenu.close(); + }) + }.height(400) + .backgroundColor(Color.Pink) + + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) { + Column() { + Text("Text") + }.bindContextMenu(this.MenuBuilder, ResponseType.LongPress) } + .width('100%') + .height('100%') } +} ``` diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md index 57e660947ef0d81e680f46434190181e91da34ae..4232e4edc4edef65815bfc289f63d6f81ff98b0d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border.md @@ -24,16 +24,16 @@ | borderStyle | BorderStyle |  BorderStyle.Solid | 设置元素的边框样式。 | | borderWidth | Length | 0 | 设置元素的边框宽度。 | | borderColor | [ResourceColor](../../ui/ts-types.md) | - | 设置元素的边框颜色。 | -| borderRadius | Length | 0 | 设置元素的边框圆角半径。 | +| borderRadius | Length \| BorderRadiuses9+ | 0 | 设置元素的边框圆角半径。 | - BorderOptions属性说明 | 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | | -------- | ------------------------------------------------------------ | ----------------- | ---- | ---------- | - | width | [Length](../../ui/ts-types.md#长度类型)\|EdgeWidth9+ | 0 | 否 | 边框宽度。 | - | color | [ResourceColor](../../ui/ts-types.md)\|EdgeColor9+ | 'Black' | 否 | 边框颜色。 | - | radius | [Length](../../ui/ts-types.md#长度类型)\| EdgeRadiuses9+ | 0 | 否 | 边框角度。 | - | style | BorderStyle\|EdgeStyle9+ | BorderStyle.Solid | 否 | 边框样式。 | + | width | [Length](../../ui/ts-types.md#长度类型) \| EdgeWidth9+ | 0 | 否 | 边框宽度。 | + | color | [ResourceColor](../../ui/ts-types.md) \| EdgeColor9+ | 'Black' | 否 | 边框颜色。 | + | radius | [Length](../../ui/ts-types.md#长度类型) \| BorderRadiuses9+ | 0 | 否 | 边框角度。 | + | style | BorderStyle \| EdgeStyle9+ | BorderStyle.Solid | 否 | 边框样式。 | - EdgeWidth9+对象说明 @@ -58,7 +58,7 @@ | top | [ResourceColor](../../ui/ts-types.md) | 否 | 'Black' | 上侧边框颜色。 | | bottom | [ResourceColor](../../ui/ts-types.md) | 否 | 'Black' | 下侧边框颜色。 | -- EdgeRadiuses9+对象说明 +- BorderRadiuses9+对象说明 引用该对象时,至少传入一个参数。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md new file mode 100644 index 0000000000000000000000000000000000000000..28ef7ac0961068bb853ccd4bdf077efec5f5ca00 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md @@ -0,0 +1,70 @@ +# 触摸测试控制 + +设置组件的触摸测试类型。ArkUI开发框架在处理触屏事件时,会在触屏事件触发前,进行按压点和组件区域的触摸测试来收集需要响应触屏事件的组件,然后基于触摸测试结果分发相应的触屏事件。hitTestBehavior属性可以设置不同的触摸测试响应模式,影响组件的触摸测试收集结果,最终影响后续的触屏事件分发,具体影响参考HitTestMode枚举说明。 + +> **说明:** +> - 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> - 当Stack组件中有多个节点触摸区域重叠时,如两个节点,默认只会对显示在最上层的节点做触摸测试,若需要显示在下层的节点触发触摸测试,请给显示在上层的节点设置hitTestBehavior为HitTestMode.Transparent。 + + +## 权限列表 + +无 + + +## 属性 + +| **名称** | **参数类型** | **默认值** | **描述** | +| -------------------- | -------- | ------- | ---------------------------------------- | +| hitTestBehavior | HitTestMode | HitTestMode.Default | 设置当前组件的触摸测试类型。 | + +- HitTestMode 枚举说明 + + | 名称 | 描述 | + | -------- | -------- | + | Default | 默认触摸测试效果,自身和子节点都响应触摸测试,但会阻塞兄弟节点的触摸测试。 | + | Block | 自身响应触摸测试,阻塞子节点和兄弟节点的触摸测试。 | + | Transparent | 自身和子节点都响应触摸测试,不会阻塞兄弟节点的触摸测试。 | + | None | 自身不响应触摸测试,不会阻塞子节点和兄弟节点的触摸测试。 | + + +## 示例 + +Text组件设置hitTestBehavior为HitTestMode.Transparent,不会阻塞内层Stack的触摸测试,因此Text和内层Stack的onTouch事件都会触发。 +内层Stack设置hitTestBehavior为HitTestMode.Block,会阻塞子节点和外层Button进行触摸测试,因此内层Button和外层Button组件不会响应onTouch事件。 + +```ts +// xxx.ets +@Entry +@Component +struct HitTestBehaviorExample { + build() { + // outer stack + Stack() { + Button('outer button') + .onTouch((event) => { + console.info('outer button touched type: ' + event.type) + }) + // inner stack + Stack() { + Button('inner button') + .onTouch((event) => { + console.info('inner button touched type: ' + event.type) + }) + } + .width("100%").height("100%") + .hitTestBehavior(HitTestMode.Block) + .onTouch((event) => { + console.info('stack touched type: ' + event.type) + }) + + Text('Transparent') + .hitTestBehavior(HitTestMode.Transparent) + .width("100%").height("100%") + .onTouch((event) => { + console.info('text touched type: ' + event.type) + }) + }.width(300).height(300) + } +} +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index 9168b2896a1d0ca20e7389d4c477c4667ca315f1..2c11bf39c4104b2d26dbf5988cdd43ecaf2ec2a8 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -3,7 +3,6 @@ 例如背景模糊、内容模糊和灰度效果等。 > **说明:** -> > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 @@ -27,7 +26,7 @@ | invert | number | 0 | 反转输入的图像。入参为图像反转的比例。值为1时完全反转。值为0则图像无变化。(百分比) | | colorBlend 8+ | Color \| string \| [Resource](../../ui/ts-types.md#resource类型)| | - | 为当前组件添加颜色叠加效果,入参为叠加的颜色。 | | sepia | number | 0 | 将图像转换为深褐色。入参为图像反转的比例。值为1则完全是深褐色的,值为0图像无变化。 (百分比) | -| hueRotate | number \| string | '0deg' | 为当前组件添加色相旋转效果,入参为旋转的角度值,0deg时图像无变化。入参没有最大值,超过360deg时相当于又绕一圈,即,370deg和10deg的色相旋转效果相同。 | +| hueRotate | number | string | '0deg' | 为当前组件添加色相旋转效果,入参为旋转的角度值,0deg时图像无变化。入参没有最大值,超过360deg时相当于又绕一圈,即,370deg和10deg的色相旋转效果相同。 | ## 示例 @@ -37,6 +36,7 @@ @Entry @Component struct ImageEffectsExample { + build() { Column({space: 10}) { // 对字体进行模糊 @@ -75,5 +75,3 @@ struct ImageEffectsExample { } } ``` - - diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 5f7430a51ddcff6391a9ca61173464fd98b0804a..c6182fe332d009a5fb4d77424a5f59e6873826c4 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -38,6 +38,7 @@ @Entry @Component struct PositionExample { + build() { Column() { Column({space: 10}) { @@ -72,6 +73,7 @@ struct PositionExample { @Entry @Component struct PositionExample2 { + build() { Column({ space: 20 }) { Text('position').fontSize(12).fontColor(0xCCCCCC).width('90%') diff --git a/zh-cn/application-dev/security/huks-overview.md b/zh-cn/application-dev/security/huks-overview.md index b6bfae7f5a0be1cfb7bce7fa381a5b4e0b641032..3711420d9b14dba3709cddfe07a58741760173f5 100755 --- a/zh-cn/application-dev/security/huks-overview.md +++ b/zh-cn/application-dev/security/huks-overview.md @@ -16,13 +16,13 @@ HUKS对密钥的使用主要通过Init、Update、Finish操作来实现。 - **Init操作**:读取密钥,并为其创建Session Id返回给调用者。 -- **Udate操作**:根据Init操作获取的Session Id对数据进行分段update处理。 +- **Update操作**:根据Init操作获取的Session Id对数据进行分段update处理。 -- **Fnish操作**:当所有待处理的数据均传入HUKS后,调用Finish操作完成最终数据处理,释放资源。 +- **Finish操作**:当所有待处理的数据均传入HUKS后,调用Finish操作完成最终数据处理,释放资源。 > **须知:**
> 当Init、Update、Finish操作中的任一阶段发生错误时,都需要调用Abort操作来终止密钥的使用。 ## 约束与限制 -不涉及。 \ No newline at end of file +不涉及。 diff --git a/zh-cn/application-dev/security/userauth-guidelines.md b/zh-cn/application-dev/security/userauth-guidelines.md index de8b8987c78ef6e3254b2d26a05113037efba605..d30a71e607a2f8492b134e7ecc843347597ceac8 100644 --- a/zh-cn/application-dev/security/userauth-guidelines.md +++ b/zh-cn/application-dev/security/userauth-guidelines.md @@ -111,9 +111,3 @@ userIAM_userAuth模块提供了用户认证的相关方法,包括检测认证 console.error("cancel auth fail"); } ``` - -## 相关实例 - -针对用户认证开发,有以下相关实例可供参考: - -- [`UserAuth`:用户认证(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/Safety/UserAuth) diff --git a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md index ed5b30d8e68f0f4a1d487ec083257d2b9572ee83..412d2d2cb2cc5882fe29f1d83c39cf6eb0e3c0b5 100644 --- a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md +++ b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md @@ -34,6 +34,8 @@ isLastWorkTimeOut(workId: number): Promise\;| 获取上次任务是否 **表2** WorkInfo包含参数 +> **说明:** WorkInfo设置参数约束见[延迟任务调度概述](./work-scheduler-overview.md) + 接口名|描述|类型 ---------------------------------------------------------|-----------------------------------------|--------------------------------------------------------- workId | 延迟任务Id(必填)|number diff --git a/zh-cn/application-dev/task-management/work-scheduler-overview.md b/zh-cn/application-dev/task-management/work-scheduler-overview.md index ce33b5cd3c61ba95c38827780b449931205f675b..c2ce0fe7fe8203b8863fe8688131a33e9d1b0d5b 100644 --- a/zh-cn/application-dev/task-management/work-scheduler-overview.md +++ b/zh-cn/application-dev/task-management/work-scheduler-overview.md @@ -11,6 +11,17 @@ 延迟调度任务的使用需要遵从如下约束和规则: - **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。 +- **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。 + +应用分组 | 延迟任务执行频率约束 +--------------------|------------------------- +活跃 | 最小间隔2小时 +每日使用 | 最小间隔4小时 +经常使用 | 最小间隔24小时 +不经常使用 | 最小间隔48小时 +受限分组 | 禁止 +未使用分组 | 禁止 + - **WorkInfo设置参数约束** (1) workId、bundleName、abilityName为必填项,bundleName必须填本应用,否则校验失败。 diff --git a/zh-cn/application-dev/ui/ts-syntactic-sugar.md b/zh-cn/application-dev/ui/ts-syntactic-sugar.md index 0ce4cad3b5efa6ba2184a88f79649eeda9a133ac..0a368cadb47366004f82cb2c8535c8e3f74c0412 100644 --- a/zh-cn/application-dev/ui/ts-syntactic-sugar.md +++ b/zh-cn/application-dev/ui/ts-syntactic-sugar.md @@ -128,7 +128,7 @@ TS语言的使用在生成器函数中存在一定的限制: build() { let a: number = 1 // invalid: variable declaration not allowed Column() { - Text('Hello ${this.myName.toUpperCase()}') // ok. + Text(`Hello ${this.myName.toUpperCase()}`) // ok. ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array variable in place } buildSpecial() // invalid: no function calls @@ -137,11 +137,11 @@ build() { ``` -## $ +## 变量双向绑定 $$支持变量双向绑定,支持简单变量、@State、@Link、@Prop等类型。 -当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性的show参数和@State变量之间的渲染,以及Radio组件的checked属性。 +当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性的show参数和@State变量之间的渲染,以及Radio组件的checked属性和Refresh组件的refreshing参数。 ```ts diff --git a/zh-cn/application-dev/website.md b/zh-cn/application-dev/website.md index 5b88e9ebaeb11790c0050c0f1d0d7bf5dc648a1e..73fe0eafdb686669b46e73ccfa581b9a67eee093 100644 --- a/zh-cn/application-dev/website.md +++ b/zh-cn/application-dev/website.md @@ -190,7 +190,9 @@ - 窗口管理 - 窗口 - [窗口开发概述](windowmanager/window-overview.md) - - [窗口开发指导](windowmanager/window-guidelines.md) + - [管理应用窗口(Stage模型)](windowmanager/application-window-stage.md) + - [管理应用窗口(FA模型)](windowmanager/application-window-fa.md) + - [管理系统窗口(仅Stage模型支持)](windowmanager/system-window-stage.md) - 屏幕属性 - [屏幕属性开发概述](windowmanager/display-overview.md) - [屏幕属性开发指导](windowmanager/display-guidelines.md) @@ -415,6 +417,7 @@ - [组件标识](reference/arkui-ts/ts-universal-attributes-component-id.md) - [触摸热区设置](reference/arkui-ts/ts-universal-attributes-touch-target.md) - [多态样式](reference/arkui-ts/ts-universal-attributes-polymorphic-style.md) + - [触摸测试控制](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md) - 手势处理 - [绑定手势方法](reference/arkui-ts/ts-gesture-settings.md) - 基础手势 diff --git a/zh-cn/application-dev/windowmanager/Readme-CN.md b/zh-cn/application-dev/windowmanager/Readme-CN.md index fcfb79f31d426720360b787f9efba03f1be16849..fff76b863d6b9198dec861f7cffaf7e9025009d2 100644 --- a/zh-cn/application-dev/windowmanager/Readme-CN.md +++ b/zh-cn/application-dev/windowmanager/Readme-CN.md @@ -1,12 +1,16 @@ # 窗口管理 -* 窗口 - * [窗口开发概述](window-overview.md) - * [窗口开发指导](window-guidelines.md) -* 屏幕属性 - * [屏幕属性开发概述](display-overview.md) - * [屏幕属性开发指导](display-guidelines.md) -* 屏幕截图 - * [屏幕截图开发概述](screenshot-overview.md) - * [屏幕截图开发指导](screenshot-guidelines.md) +- 窗口 + - [窗口开发概述](window-overview.md) + - [管理应用窗口(Stage模型)](application-window-stage.md) + - [管理应用窗口(FA模型)](application-window-fa.md) + - [管理系统窗口(仅Stage模型支持)](system-window-stage.md) + +- 屏幕属性 + - [屏幕属性开发概述](display-overview.md) + - [屏幕属性开发指导](display-guidelines.md) + +- 屏幕截图 + - [屏幕截图开发概述](screenshot-overview.md) + - [屏幕截图开发指导](screenshot-guidelines.md) \ No newline at end of file diff --git a/zh-cn/application-dev/windowmanager/application-window-fa.md b/zh-cn/application-dev/windowmanager/application-window-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..be0148a32c242e3d38c3baefbd6265aaa3ce0889 --- /dev/null +++ b/zh-cn/application-dev/windowmanager/application-window-fa.md @@ -0,0 +1,260 @@ +# 管理应用窗口(FA模型) + +## 基本概念 + +窗口沉浸式能力:指对状态栏、导航栏等系统窗口进行控制,减少状态栏导航栏等系统界面的突兀感,从而使用户获得最佳体验的能力。 +沉浸式能力只在应用主窗口作为全屏窗口时生效。通常情况下,应用子窗口(弹窗、悬浮窗口等辅助窗口)和处于自由窗口下的应用主窗口无法使用沉浸式能力。 + +## 场景介绍 + +在FA模型下,管理应用窗口的典型场景有: + +- 设置应用子窗口属性及目标页面 + +- 体验窗口沉浸式能力 + +以下分别介绍具体开发方式。 + + +## 接口说明 + +上述场景涉及的常用接口如下表所示。更多API说明请参见[API参考](../reference/apis/js-apis-window.md)。 + +| 实例名 | 接口名 | 描述 | +| -------- | -------- | -------- | +| window静态方法 | create(id:string,type:WindowType,callback:AsyncCallback]<Window>):void | 创建子窗口。
此接口仅可在`FA`模型下使用。 | +| window静态方法 | getTopWindow(callback:AsyncCallback<Window>):void | 获取当前应用内最后显示的窗口。
此接口仅可在`FA`模型下使用。 | +| window静态方法 | find(id:string,callback:AsyncCallback<Window>):void | 查找`id`所对应的窗口。 | +| Window | loadContent(path:string,callback:AsyncCallback<void>):void | 为当前窗口加载具体页面内容。 | +| Window | moveTo(x:number,y:number,callback:AsyncCallback<void>):void | 移动当前窗口。 | +| Window | setBackgroundColor(color:string,callback:AsyncCallback<void>):void | 设置窗口的背景色 | +| Window | setBrightness(brightness:number,callback:AsyncCallback<void>):void | 设置屏幕亮度值。 | +| Window | resetSize(width:number,height:number,callback:AsyncCallback<void>):void | 改变当前窗口大小。 | +| Window | setFullScreen(isFullScreen:boolean,callback:AsyncCallback<void>):void | 设置窗口是否全屏显示。 | +| Window | setLayoutFullScreen(isLayoutFullScreen:boolean,callback:AsyncCallback<void>):void | 设置窗口布局是否为全屏布局。 | +| Window | setSystemBarEnable(names:Array<'status'\|'navigation'>):Promise<void> | 设置导航栏、状态栏是否显示。 | +| Window | setSystemBarProperties(systemBarProperties:SystemBarProperties,callback:AsyncCallback<void>):void | 设置窗口内导航栏、状态栏属性。
`systemBarProperties`:导航栏、状态栏的属性集合。 | +| Window | show(callback: AsyncCallback\): void | 显示当前窗口。 | +| Window | on(type:'touchOutside',callback:Callback<void>):void | 开启本窗口区域外的点击事件的监听。 | +| Window | destroy(callback: AsyncCallback<void>):void | 销毁当前窗口。 | + + +## 设置应用子窗口 + +开发者可以按需创建应用子窗口,如弹窗等,并对其进行属性设置等操作。 + + +### 开发步骤 + +1. 创建/获取子窗口对象。 + + - 可以通过`window.create`接口创建子窗口。 + - 可以通过`window.getTopWindow`来获取最后显示的窗口得到子窗口。 + - 也可以通过`window.find`接口来查找已经创建的窗口从而得到子窗口。 + + ```js + import window from '@ohos.window'; + + var windowClass = null; + // 1.方式一:创建子窗口。 + window.create("subWindow", window.WindowType.TYPE_APP, (err, data) => { + if (err.code) { + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data)); + windowClass = data; + }); + // 1.方式二:获取子窗口。 + window.getTopWindow((err, data) => { + if (err.code) { + console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting subWindow. Data: ' + JSON.stringify(data)); + windowClass = data; + }); + // 1.方式三:查找得到子窗口。 + window.find("subWindow", (err, data) => { + if (err.code) { + console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data)); + windowClass = data; + }); + ``` + +2. 设置子窗口属性。 + + 子窗口创建成功后,可以改变其大小、位置等,还可以根据应用需要设置窗口背景色、亮度等属性。 + + + ```js + // 2.移动子窗口位置。 + windowClass.moveTo(300, 300, (err, data) => { + if (err.code) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + }); + // 2.改变子窗口大小。 + windowClass.resetSize(500, 1000, (err, data) => { + if (err.code) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + }); + ``` + +3. 加载显示子窗口的具体内容。 + + 使用`loadContent`和`show`接口加载显示子窗口的具体内容。 + + + ```js + // 3.为子窗口加载对应的目标页面。 + windowClass.loadContent("pages/page2", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + // 3.显示子窗口。 + windowClass.show((err, data) => { + if (err.code) { + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + }); + }); + ``` + +4. 销毁子窗口。 + + 当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用`destroy`接口销毁子窗口。 + + + ```js + // 4.销毁子窗口。当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用destroy接口销毁子窗口,此处以监听窗口区域外的点击事件实现子窗口的销毁。 + windowClass.on('touchOutside', () => { + console.info('touch outside'); + windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the subwindow. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the subwindow. Data: ' + JSON.stringify(data)); + }); + }); + ``` + + +## 体验窗口沉浸式能力 + +在看视频、玩游戏等场景下,用户往往希望隐藏状态栏、导航栏等不必要的系统窗口,从而获得更佳的沉浸式体验。此时可以借助窗口沉浸式能力(窗口沉浸式能力都是针对应用主窗口而言的),达到预期效果。 + + +### 开发步骤 + +1. 获取主窗口对象。 + + 沉浸式能力需要在成功获取应用主窗口对象的前提下进行。使用`window.getTopWindow`接口来获取得到主窗口。 + + + ```js + import window from '@ohos.window'; + + var mainWindowClass = null; + // 1.获取主窗口 + window.getTopWindow((err, data) => { + if (err.code) { + console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting subWindow. Data: ' + JSON.stringify(data)); + mainWindowClass = data; + }); + ``` + +2. 实现沉浸式效果。有以下三种方式: + + - 方式一:调用`setFullScreen`接口,设置应用主窗口为全屏显示,此时导航栏、状态栏将隐藏,从而达到沉浸式效果。 + - 方式二:调用`setSystemBarEnable`接口,设置导航栏、状态栏不显示,从而达到沉浸式效果。 + - 方式三:调用`setLayoutFullScreen`接口,设置应用主窗口为全屏布局;然后调用`setSystemPropertites`接口,设置导航栏、状态栏的透明度、背景/文字颜色以及高亮图标等属性,使之保持与主窗口显示协调一致,从而达到沉浸式效果。 + + ```js + // 2.实现沉浸式效果。方式一:设置窗口全屏显示。 + var isFullScreen = true; + mainWindowClass.setFullScreen(isFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + }); + // 2.实现沉浸式效果。方式二:设置导航栏、状态栏不显示。 + var names = null; + mainWindowClass.setSystemBarEnable(names, (err, data) => { + if (err.code) { + console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + }); + // 2.实现沉浸式效果。 + // 方式三:设置窗口为全屏布局,配合设置状态栏、导航栏的透明度、背景/文字颜色及高亮图标等属性,与主窗口显示保持协调一致。 + var isLayoutFullScreen = true; + mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); + }); + var SystemBarProperties = { + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // 以下两个属性从API Version7开始支持 + isStatusBarLightIcon: false, + isNavigationBarLightIcon: false, + // 以下两个属性从API Version8开始支持 + statusBarContentColor: '#ffffff', + navigationBarContentColor: '#ffffff' + }; + mainWindowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { + if (err.code) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); + }); + ``` + +3. 加载显示沉浸式窗口的具体内容。 + + 使用`loadContent`和`show`接口加载显示沉浸式窗口的具体内容。 + + + ```js + // 3.为沉浸式窗口加载对应的目标页面。 + mainWindowClass.loadContent("pages/page3", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + // 3.显示沉浸式窗口。 + mainWindowClass.show((err, data) => { + if (err.code) { + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + }); + }); + ``` + diff --git a/zh-cn/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..33fe1385b290ea4b51630d9152f6c3a8341db84d --- /dev/null +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -0,0 +1,406 @@ +# 管理应用窗口(Stage模型) + + +## 基本概念 + +- 窗口沉浸式能力:指对状态栏、导航栏等系统窗口进行控制,减少状态栏导航栏等系统界面的突兀感,从而使用户获得最佳体验的能力。 + 沉浸式能力只在应用主窗口作为全屏窗口时生效。通常情况下,应用子窗口(弹窗、悬浮窗口等辅助窗口)和处于自由窗口下的应用主窗口无法使用沉浸式能力。 + +- 悬浮窗:全局悬浮窗口是一种特殊的应用窗口,具备在应用主窗口和对应Ability退至后台后仍然可以在前台显示的能力。 + 悬浮窗口可以用于应用退至后台后,使用小窗继续播放视频,或者为特定的应用创建悬浮球等快速入口。应用在创建悬浮窗口前,需要申请对应的权限。 + + +## 场景介绍 + +在`Stage`模型下,管理应用窗口的典型场景有: + +- 设置应用主窗口属性及目标页面 + +- 设置应用子窗口属性及目标页面 + +- 体验窗口沉浸式能力 + +- 设置悬浮窗 + +以下分别介绍具体开发方式。 + + +## 接口说明 + +上述场景涉及的常用接口如下表所示。更多API说明请参见[API参考](../reference/apis/js-apis-window.md)。 + +| 实例名 | 接口名 | 描述 | +| -------- | -------- | -------- | +| WindowStage | getMainWindow(callback:AsyncCallback<Window>):void | 获取`WindowStage`实例下的主窗口。
此接口仅可在`Stage`模型下使用。 | +| WindowStage | loadContent(path:string,callback:AsyncCallback<void>):void | 为当前`WindowStage`的主窗口加载具体页面。
此接口仅可在`Stage`模型下使用。 | +| WindowStage | createSubWindow(name:string,callback:AsyncCallback<Window>):void | 创建子窗口。
此接口仅可在`Stage`模型下使用。 | +| window静态方法 | create(ctx:Context,id:string,type:WindowType,callback:AsyncCallback<Window>):void | 创建子窗口。
-`ctx`:为应用上下文信息。
-`type`:为创建的窗口类型。 | +| Window | loadContent(path:string,callback:AsyncCallback<void>):void | 为当前窗口加载具体页面。 | +| Window | setBackgroundColor(color:string,callback:AsyncCallback<void>):void | 设置窗口的背景色。 | +| Window | setBrightness(brightness:number,callback:AsyncCallback<void>):void | 设置屏幕亮度值。 | +| Window | setTouchable(isTouchable:boolean,callback:AsyncCallback<void>):void | 设置窗口是否为可触状态。 | +| Window | moveTo(x:number,y:number,callback:AsyncCallback<void>):void | 移动当前窗口位置。 | +| Window | resetSize(width:number,height:number,callback:AsyncCallback<void>):void | 改变当前窗口大小。 | +| Window | setFullScreen(isFullScreen:boolean,callback:AsyncCallback<void>):void | 设置窗口是否全屏显示。 | +| Window | setLayoutFullScreen(isLayoutFullScreen:boolean,callback:AsyncCallback<void>):void | 设置窗口布局是否为全屏布局。 | +| Window | setSystemBarEnable(names:Array<'status'\|'navigation'>):Promise<void> | 设置导航栏、状态栏是否显示。 | +| Window | setSystemBarProperties(systemBarProperties:SystemBarProperties,callback:AsyncCallback<void>):void | 设置窗口内导航栏、状态栏属性。
`systemBarProperties`:导航栏、状态栏的属性集合。 | +| Window | show(callback: AsyncCallback\): void | 显示当前窗口。 | +| Window | on(type:'touchOutside',callback:Callback<void>):void | 开启本窗口区域外的点击事件的监听。 | +| Window | destroy(callback: AsyncCallback<void>):void | 销毁当前窗口。 | + + +## 设置应用主窗口 + +在`Stage`模型下,应用主窗口由`Ability`创建并维护生命周期。在`Ability`的`onWindowStageCreate`回调中,通过`WindowStage`获取应用主窗口,即可对其进行属性设置等操作 + + +### 开发步骤 + +1. 获取应用主窗口。 + 通过`getMainWindow`接口获取应用主窗口。 + +2. 设置主窗口属性。 + 可设置主窗口的背景色、亮度值、是否可触等多个属性,开发者可根据需要选择对应的接口。本示例以设置“是否可触”属性为例。 + +3. 为主窗口加载对应的目标页面。 + 通过`loadContent`接口加载主窗口的目标页面。 + + +```ts +import Ability from '@ohos.application.Ability' + +class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + // 1.获取应用主窗口。 + var windowClass = null; + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); + // 2.设置主窗口属性。以设置"是否可触"属性为例。 + var isTouchable = true; + windowClass.setTouchable(isTouchable, (err, data) => { + if (err.code) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be touchable. Data:' + JSON.stringify(data)); + }) + }) + // 3.为主窗口加载对应的目标页面。 + windowStage.loadContent("pages/page2", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + }); + } +}; +``` + + +## 设置应用子窗口 + +开发者可以按需创建应用子窗口,如弹窗等,并对其进行属性设置等操作。 + + +### 开发步骤 + +1. 创建/获取应用子窗口。 + 通过`createSubWindow`接口创建应用子窗口。 + + 通过`getSubWindow`接口获取已创建的应用子窗口。 + +2. 设置子窗口属性。 + 子窗口创建成功后,可以改变其大小、位置等,还可以根据应用需要设置窗口背景色、亮度等属性。 + +3. 加载显示子窗口的具体内容。 + 通过`loadContent`和`show`接口加载显示子窗口的具体内容。 + +4. 销毁子窗口。 + 当不再需要某些子窗口时,可根据具体实现逻辑,使用`destroy`接口销毁子窗口。 + + + ```ts + import Ability from '@ohos.application.Ability' + + class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + // 1.创建应用子窗口。 + var sub_windowClass = null; + windowStage.createSubWindow("mySubWindow", (err, data) => { + if (err.code) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + sub_windowClass = data; + console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); + // 1.获取已创建的应用子窗口。 + windowStage.getSubWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the subWindow. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the subWindow. Data: ' + JSON.stringify(data)); + sub_windowClass = data; + }); + // 2.子窗口创建成功后,设置子窗口的位置、大小及相关属性等。 + sub_windowClass.moveTo(300, 300, (err, data) => { + if (err.code) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + }); + sub_windowClass.resetSize(500, 1000, (err, data) => { + if (err.code) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + }); + // 3.为子窗口加载对应的目标页面。 + sub_windowClass.loadContent("pages/page3", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + // 3.显示子窗口。 + sub_windowClass.show((err, data) => { + if (err.code) { + console.error('Failed to show the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + }); + }); + // 4.销毁子窗口。当不再需要子窗口时,可根据具体实现逻辑,使用destroy对其进行销毁,此处以监听窗口区域外的点击事件为例实现子窗口的销毁。 + sub_windowClass.on('touchOutside', () => { + console.info('touch outside'); + sub_windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + }); + }); + }) + } + }; + ``` + + +## 体验窗口沉浸式能力 + +在看视频、玩游戏等场景下,用户往往希望隐藏状态栏、导航栏等不必要的系统窗口,从而获得更佳的沉浸式体验。此时可以借助窗口沉浸式能力(窗口沉浸式能力都是针对应用主窗口而言的),达到预期效果。 + + +### 开发步骤 + +1. 获取应用主窗口。 + 通过`getMainWindow`接口获取应用主窗口。 + +2. 实现沉浸式效果。有以下三种方式: + - 方式一:调用`setFullScreen`接口,设置应用主窗口为全屏显示,此时导航栏、状态栏将隐藏,从而达到沉浸式效果。 + - 方式二:调用`setSystemBarEnable`接口,设置导航栏、状态栏不显示,从而达到沉浸式效果。 + - 方式三:调用`setLayoutFullScreen`接口,设置应用主窗口为全屏布局;然后调用`setSystemPropertites`接口,设置导航栏、状态栏的透明度、背景/文字颜色以及高亮图标等属性,使之保持与主窗口显示协调一致,从而达到沉浸式效果。 + +3. 加载显示沉浸式窗口的具体内容。 + 通过`loadContent`和`show`接口加载显示沉浸式窗口的具体内容。 + + + ```ts + import Ability from '@ohos.application.Ability' + + class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + // 1.获取应用主窗口。 + var windowClass = null; + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); + + // 2.实现沉浸式效果。方式一:设置应用主窗口为全屏显示。 + var isFullScreen = true; + windowClass.setFullScreen(isFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + }); + // 2.实现沉浸式效果。方式二:设置导航栏、状态栏不显示。 + var names = null; + windowClass.setSystemBarEnable(names, (err, data) => { + if (err.code) { + console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + }); + // 2.实现沉浸式效果。方式三:设置窗口为全屏布局,配合设置导航栏、状态栏的透明度、背景/文字颜色及高亮图标等属性,与主窗口显示保持协调一致。 + var isLayoutFullScreen = true; + windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); + }); + var SystemBarProperties = { + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // 以下两个属性从API Version 7开始支持 + isStatusBarLightIcon: false, + isNavigationBarLightIcon: false, + // 以下两个属性从API Version 8开始支持 + statusBarContentColor: '#ffffff', + navigationBarContentColor: '#ffffff' + }; + windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { + if (err.code) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); + }); + }) + // 3.为沉浸式窗口加载对应的目标页面。 + windowStage.loadContent("pages/page2", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + // 3.显示沉浸式窗口。 + windowStage.show((err, data) => { + if (err.code) { + console.error('Failed to show the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + }); + }); + } + }; + ``` + + +## 设置悬浮窗 + +悬浮窗可以在已有的任务基础上,创建一个始终在前台显示的窗口。即使创建悬浮窗的任务退至后台,悬浮窗仍然可以在前台显示。开发者可以创建悬浮窗,并对悬浮窗进行属性设置等操作。 + + +### 开发步骤 + +1. 申请权限。 + 创建`WindowType.TYPE_FLOAT`即悬浮窗类型的窗口,需要在`module.json5`文件的`requestPermissions`对象中配置`ohos.permission.SYSTEM_FLOAT_WINDOW`权限。更多配置信息详见[应用包结构配置文件的说明](../quick-start/stage-structure.md)。 + + > **说明:** + > 虽然悬浮窗具备始终在前台显示的能力,但如果创建悬浮窗的应用任务被系统回收,仍然会导致悬浮窗从界面移除。如果想要保持悬浮窗口始终在前台显示,请申请[长时任务](../task-management/background-task-overview.md)。 + + + ```json + { + "module": { + "requestPermissions":[ + { + "name" : "ohos.permission.SYSTEM_FLOAT_WINDOW", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when":"inuse" + } + } + ] + } + } + ``` + +2. 创建悬浮窗。 + 通过`window.create`接口创建悬浮窗类型的窗口。 + +3. 对悬浮窗进行属性设置等操作。 + 悬浮窗窗口创建成功后,可以改变其大小、位置等,还可以根据应用需要设置悬浮窗背景色、亮度等属性。 + +4. 加载显示悬浮窗的具体内容。 + 通过`loadContent`和`show`接口加载显示悬浮窗的具体内容。 + +5. 销毁悬浮窗。 + + 当不再需要悬浮窗时,可根据具体实现逻辑,使用`destroy`接口销毁悬浮窗。 + + ```ts + import Ability from '@ohos.application.Ability' + import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; + import window from '@ohos.window'; + + class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + // 2. 创建悬浮窗。 + var windowClass = null; + window.create(this.context, "floatWindow", window.WindowType.TYPE_FlOAT, (err, data) => { + if (err.code) { + console.error('Failed to create the floatWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in creating the floatWindow. Data: ' + JSON.stringify(data)); + windowClass = data; + // 3.悬浮窗窗口创建成功后,设置悬浮窗的位置、大小及相关属性等。 + windowClass.moveTo(300, 300, (err, data) => { + if (err.code) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + }); + windowClass.resetSize(500, 1000, (err, data) => { + if (err.code) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + }); + // 4.为悬浮窗加载对应的目标页面。 + windowClass.loadContent("pages/page4", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + // 4.显示悬浮窗。 + windowClass.show((err, data) => { + if (err.code) { + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + }); + }); + //5.销毁悬浮窗。当不再需要悬浮窗时,可根据具体实现逻辑,使用destroy对其进行销毁,此处以监听窗口区域外的点击事件为例实现悬浮窗的销毁。 + windowClass.on('touchOutside', () => { + console.info('touch outside'); + windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + }); + }); + }); + } + }; + ``` diff --git a/zh-cn/application-dev/windowmanager/figures/windowMode.png b/zh-cn/application-dev/windowmanager/figures/windowMode.png new file mode 100644 index 0000000000000000000000000000000000000000..6d4b793d46343ff33efec41ce90c7418ba2fe779 Binary files /dev/null and b/zh-cn/application-dev/windowmanager/figures/windowMode.png differ diff --git a/zh-cn/application-dev/windowmanager/system-window-stage.md b/zh-cn/application-dev/windowmanager/system-window-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..d602dad84a919ff9a0823616f5b808b6980e3008 --- /dev/null +++ b/zh-cn/application-dev/windowmanager/system-window-stage.md @@ -0,0 +1,112 @@ +# 管理系统窗口(仅Stage模型支持) + +## 管理系统窗口概述 + +在`Stage`模型下, 允许系统应用创建和管理系统窗口,包括音量条、壁纸、通知栏、状态栏、导航栏等。具体支持的系统窗口类型见[API参考-WindowType](../reference/apis/js-apis-window.md)。 + + +## 接口说明 + +更多API说明请参见[API参考](../reference/apis/js-apis-window.md)。 + +| 实例名 | 接口名 | 描述 | +| -------- | -------- | -------- | +| window静态方法 | create(ctx:Context,id:string,type:WindowType,callback:AsyncCallback<Window>):void | 创建窗口。
-`ctx`:为应用上下文信息。当`Context`为[ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md)时,创建系统窗口。
-`type`:为创建的窗口类型。 | +| Window | resetSize(width:number,height:number,callback:AsyncCallback<void>):void | 改变当前窗口大小。 | +| Window | moveTo(x:number,y:number,callback:AsyncCallback<void>):void | 移动当前窗口位置。 | +| Window | loadContent(path:string,callback:AsyncCallback<void>):void | 为当前窗口加载具体页面。 | +| Window | show(callback: AsyncCallback\): void | 显示当前窗口。 | +| Window | on(type:'touchOutside',callback:Callback<void>):void | 开启本窗口区域外的点击事件的监听。 | +| Window | hide (callback: AsyncCallback\): void | 隐藏当前窗口。此接口为系统接口。 | +| Window | destroy(callback: AsyncCallback<void>):void | 销毁当前窗口。 | + + +## 开发步骤 + + +本文以音量条窗口为例,介绍系统窗口的基本开发和管理步骤。 + + +1. 创建系统窗口。 + + 在[ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md)下,使用`window.create`接口创建音量条系统窗口。 + +2. 操作或设置系统窗口的属性。 + + 系统窗口创建成功后,可以改变其大小、位置等,还可以根据需要设置系统窗口的背景色、亮度等属性。 + +3. 加载显示系统窗口的具体内容。 + + 通过`loadContent`和`show`接口加载显示音量条窗口的具体内容。 + +4. 隐藏/销毁系统窗口。 + + 当不再需要音量条窗口时,可根据具体实现逻辑,使用`hide`接口或`destroy`接口对其进行隐藏或销毁。 + +```ts +import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; +import window from '@ohos.window'; + +var windowClass = null; + +export default class ServiceExtensionAbility1 extends ExtensionContext { + onCreate(want) { + console.log("[Demo] MainAbility onCreate") + globalThis.abilityWant = want; + // 1.创建音量条窗口。 + var windowClass = null; + window.create(this.context, "volume", window.WindowType.TYPE_VOLUME_OVERLAY, (err, data) => { + if (err.code) { + console.error('Failed to create the volume window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in creating the volume window.') + windowClass = data; + // 2.创建音量条窗口成功之后,可以改变其大小、位置或设置背景色、亮度等属性。 + windowClass.moveTo(300, 300, (err, data) => { + if (err.code) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + }); + windowClass.resetSize(500, 1000, (err, data) => { + if (err.code) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + }); + // 3.为音量条窗口加载对应的目标页面。 + windowClass.loadContent("pages/page_volume", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + // 3.显示音量条窗口。 + windowClass.show((err, data) => { + if (err.code) { + console.error('Failed to show the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + }); + }); + // 4.隐藏/销毁音量条窗口。当不再需要音量条时,可根据具体实现逻辑,对其进行隐藏或销毁。 + // 此处以监听音量条区域外的点击事件为例实现音量条窗口的隐藏。 + windowClass.on('touchOutside', () => { + console.info('touch outside'); + windowClass.hide((err, data) => { + if (err.code) { + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in hidinging the window. Data: ' + JSON.stringify(data)); + }); + }); + }); + } +}; +``` + diff --git a/zh-cn/application-dev/windowmanager/window-guidelines.md b/zh-cn/application-dev/windowmanager/window-guidelines.md deleted file mode 100644 index 7758fec39628b8c33c9b6b17f9ccb86e9fec2d60..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/windowmanager/window-guidelines.md +++ /dev/null @@ -1,107 +0,0 @@ -# 窗口开发指导 - -## 场景介绍 -窗口的接口层在应用进程运行,负责对页面布局的加载,和提供应用程序接口。 -通过调用窗口接口可以实现窗口创建与销毁,窗口的位置、大小布局,以及进入沉浸式等。 - -## 接口说明 -窗口开放的能力如下:Window类,具体的API详见[接口文档](../reference/apis/js-apis-window.md)。 - -**表1** 窗口主要接口API - -| 接口名 | 描述 | -| :----------------------------------------------------------- | :--------------------------------------------- | -| create(id: string, type: WindowType, callback: AsyncCallback\): void | 创建子窗口。 | -| moveTo(x: number, y: number): Promise\ | 移动窗口位置,x值为正表示右移,y为正表示下移。 | -| resetSize(width: number, height: number): Promise\ | 改变当前窗口大小。 | -| hide(): Promise\ | 隐藏当前窗口。 | -| destroy(): Promise\ | 销毁当前窗口。 | - -## 开发步骤 - -### 创建主窗口 - -在当前模型下,应用启动时会自动创建主窗口,由应用管理窗口的生命周期,隐藏及销毁由应用管理。 -### 创建子窗口 -当前可以通过`create`接口创建子窗口。具体示例代码如下: - -```js - import window from '@ohos.window'; - var windowClass = null; - let promise = window.create("subWindow", window.WindowType.TYPE_APP); - promise.then((data)=> { - windowClass = data; - console.info('SubWindow created. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); - }); -``` - -### 获取窗口对象 - -- 应用内可以通过`getTopWindow`来获取当前应用内最后显示的窗口。具体示例代码如下: - -```js - var windowClass = null; - let promise = window.getTopWindow(); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - }) -``` - -- 应用内也可以通过`Find`来获取已经创建的子窗口。具体示例代码如下: - -```js - var windowClass = null; - let promise = window.find("subWindow"); - promise.then((data)=> { - windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); - }); -``` - -### 窗口的隐藏和销毁 - -在已经获取到窗口对象的前提下,可以调用`hide`、`destroy`来隐藏和销毁已经创建的窗口对象。具体示例代码如下: - -```js - let promise = windowClass.hide(); - promise.then((data)=> { - console.info('window hidden. Data: ' + JSON.stringify(data)) - windowClass.destroy((err, data) => { - if (err.code) { - console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)) - }) - }).catch((err)=>{ - console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); - }) -``` - -### 设置沉浸式窗口 - -在已经获取到应用窗口对象的前提下,调用`setFullScreen`来设置窗口进入全屏沉浸式。 - -示例代码如下: - -```js -import window from '@ohos.window'; -try { - const win = await window.getTopWindow() - await win.setFullScreen(true) -} catch (err) { - console.log(`setFullScreen fail, code = ${err.code}`) -} -``` - -## 相关实例 -针对窗口开发,有以下相关实例可供参考: -- [`Window`:窗口(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/Graphics/Window) - diff --git a/zh-cn/application-dev/windowmanager/window-overview.md b/zh-cn/application-dev/windowmanager/window-overview.md index 72f7a17f350a53dc5e56eb3203aa383c1263a306..f3e2ba39243ce42c7052249b967d9467550f8715 100644 --- a/zh-cn/application-dev/windowmanager/window-overview.md +++ b/zh-cn/application-dev/windowmanager/window-overview.md @@ -1,13 +1,75 @@ # 窗口开发概述 -**窗口子系统**提供窗口管理的基础能力,是系统图形界面显示所需的基础子系统。 -窗口系统的作用,是提供一种机制,让多个应用界面复用同一块物理屏幕进行显示和交互。每个应用程序中,需要实现固定窗口区域内的交互界面设计,窗口作用应用界面的显示容器,而窗口系统负责将这些交互界面组织成最终用户见到的形态。 + +## 窗口模块的定义 + +窗口模块用于在同一块物理屏幕上,提供多个应用界面显示、交互的机制。 + +- 对应用开发者而言,窗口模块提供了界面显示和交互能力。 + +- 对终端用户而言,窗口模块提供了控制应用界面的方式。 + +- 对整个操作系统而言,窗口模块提供了不同应用界面的组织管理逻辑。 + + +## 窗口模块的用途 + +在OpenHarmony中,窗口模块主要负责以下职责: + +- 提供应用和系统界面的窗口对象。应用开发者通过窗口加载UI界面,实现界面显示功能。 + +- 组织不同窗口的显示关系,即维护不同窗口间的叠加层次和位置属性。应用和系统的窗口具有多种类型,不同类型的窗口具有不同的默认位置和叠加层次(Z轴高度)。同时,用户操作也可以在一定范围内对窗口的位置和叠加层次进行调整。 + +- 提供窗口装饰。窗口装饰指窗口标题栏和窗口边框。窗口标题栏通常包括窗口最大化、最小化及关闭按钮等界面元素,具有默认的点击行为,方便用户进行操作;窗口边框则方便用户对窗口进行拖拽缩放等行为。窗口装饰是系统的默认行为,开发者可选择启用/禁用,无需关注UI代码层面的实现。 + +- 提供窗口动效。在窗口显示、隐藏及窗口间切换时,窗口模块通常会添加动画效果,以使各个交互过程更加连贯流畅。在OpenHarmony中,应用窗口的动效为默认行为,不需要开发者进行设置或者修改。 + +- 指导输入事件分发。即根据当前窗口的状态或焦点,进行事件的分发。触摸和鼠标事件根据窗口的位置和尺寸进行分发,而键盘事件会被分发至焦点窗口。应用开发者可以通过窗口模块提供的接口设置窗口是否可以触摸和是否可以获焦。 + ## 基本概念 -**沉浸式**:应用窗口跟状态栏与导航栏颜色一致,视觉上融合。 +### 窗口类型 + +OpenHarmony的窗口模块将窗口界面分为系统窗口、应用窗口两种基本类型。 + +- 系统窗口 + 系统窗口指完成系统特定功能的窗口。如音量条、壁纸、通知栏、状态栏、导航栏等。 + +- 应用窗口 + 应用窗口区别于系统窗口,指与应用显示相关的窗口。根据显示内容的不同,应用窗口又分为应用主窗口、应用子窗口两种类型。 + + - 应用主窗口 + 应用主窗口用于显示应用界面,会在"任务管理界面"显示。 + - 应用子窗口 + 应用子窗口用于显示应用的弹窗、悬浮窗等辅助窗口,不会在"任务管理界面"显示。 + + +### 应用窗口模式 + +应用窗口模式指应用主窗口启动时的显示方式。OpenHarmony目前支持全屏、分屏、自由窗口三种应用窗口模式。这种对多种应用窗口模式的支持能力,也称为操作系统的“多窗口能力”。 + + +- 全屏:应用主窗口启动时铺满整个屏幕。 + +- 分屏:应用主窗口启动时占据屏幕的某个部分,当前支持二分屏。两个分屏窗口之间具有分界线,可通过拖拽分界线调整两个部分的窗口尺寸。 + +- 自由窗口:自由窗口的大小和位置可自由改变。同一个屏幕上可同时显示多个自由窗口,这些自由窗口按照打开或者获取焦点的顺序在Z轴排布。当自由窗口被点击或触摸时,将导致其Z轴高度提升,并获取焦点。 + + +![windowMode](figures/windowMode.png) + + +## 实现原理 + +当前窗口的实现和开发与应用开发模型相关联,不同模型下的接口功能略有区别。当前应用开发模型分为FA模型和Stage模型。 + +两个模型的整体架构和设计思想,详见[FA模型综述](../ability/fa-brief.md)和[Stage模型综述](../ability/stage-brief.md)。 + +针对窗口开发,推荐使用Stage模型进行相关开发。 + -## 运作机制 +## 约束与限制 -为了将图形界面显示在屏幕上,应用和系统需要向窗口系统申请窗口对象,这通常代表了屏幕上一块矩形区域,具有位置、宽高、和叠加层次等属性。同时,窗口对象也负责加载界面中UI框架的根节点,应用程序的UI界面就通过这个根节点在窗口中加载显示。 \ No newline at end of file +在FA模型下,不支持系统窗口的相关开发。 diff --git a/zh-cn/device-dev/driver/Readme-CN.md b/zh-cn/device-dev/driver/Readme-CN.md index 3ee6c11799a477f3f9b9178545d23d518ba9c006..4118cdf0596261ee5c53161a6855cc7eecbfb544 100755 --- a/zh-cn/device-dev/driver/Readme-CN.md +++ b/zh-cn/device-dev/driver/Readme-CN.md @@ -46,6 +46,7 @@ - [Audio](driver-peripherals-audio-des.md) - [Camera](driver-peripherals-camera-des.md) - [Face_auth](driver-peripherals-face_auth-des.md) + - [Fingerprint_auth](driver-peripherals-fingerprint_auth-des.md) - [LCD](driver-peripherals-lcd-des.md) - [Light](driver-peripherals-light-des.md) - [Pin_auth](driver-peripherals-pinauth-des.md) diff --git a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md b/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md index 4ae5304c6e6ad49648d23e5b7834770faa2fc326..04dfe33a0f2735bd355b6dea4b3c24da14410310 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md +++ b/zh-cn/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 config info */ .mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT }, /* backlight config info */ diff --git a/zh-cn/device-dev/kernel/Readme-CN.md b/zh-cn/device-dev/kernel/Readme-CN.md index 4f32b8e9e9822ea707a23a10f9e378c5f9b97e69..fdeb7b452e6580d5db0f55d9959528bacc4e740a 100755 --- a/zh-cn/device-dev/kernel/Readme-CN.md +++ b/zh-cn/device-dev/kernel/Readme-CN.md @@ -6,10 +6,7 @@ - 基础内核 - [中断管理](kernel-mini-basic-interrupt.md) - [任务管理](kernel-mini-basic-task.md) - - 内存管理 - - [基本概念](kernel-mini-basic-memory-basic.md) - - [静态内存](kernel-mini-basic-memory-static.md) - - [动态内存](kernel-mini-basic-memory-dynamic.md) + - [内存管理](kernel-mini-basic-memory.md) - 内核通信机制 - [事件](kernel-mini-basic-ipc-event.md) - [互斥锁](kernel-mini-basic-ipc-mutex.md) @@ -21,23 +18,16 @@ - [C++支持](kernel-mini-extend-support.md) - [CPU占用率](kernel-mini-extend-cpup.md) - [动态加载](kernel-mini-extend-dynamic-loading.md) - - 文件系统 - - [FAT](kernel-mini-extend-file-fat.md) - - [LittleFS](kernel-mini-extend-file-lit.md) + - [文件系统](kernel-mini-extend-file.md) - 内核调测 - - 内存调测 - - [内存信息统计](kernel-mini-memory-debug-mes.md) - - [内存泄漏检测](kernel-mini-memory-debug-det.md) - - [踩内存检测](kernel-mini-memory-debug-cet.md) + - [内存调测](kernel-mini-memory-debug.md) - [异常调测](kernel-mini-memory-exception.md) - [Trace调测](kernel-mini-memory-trace.md) - [LMS调测](kernel-mini-memory-lms.md) - 附录 - [内核编码规范](kernel-mini-appx-code.md) - [双向链表](kernel-mini-appx-data-list.md) - - 标准库支持 - - [CMSIS支持](kernel-mini-appx-lib-cmsis.md) - - [POSIX支持](kernel-mini-appx-lib-posix.md) + - [标准库支持](kernel-mini-appx-lib.md) - 小型系统内核 - [内核概述](kernel-small-overview.md) - 内核启动 @@ -71,13 +61,9 @@ - [虚拟动态共享库](kernel-small-bundles-share.md) - [轻量级进程间通信](kernel-small-bundles-ipc.md) - 文件系统 + - [文件系统概述](kernel-small-bundles-fs.md) - [虚拟文件系统](kernel-small-bundles-fs-virtual.md) - - 支持的文件系统 - - [FAT](kernel-small-bundles-fs-support-fat.md) - - [JFFS2](kernel-small-bundles-fs-support-jffs2.md) - - [NFS](kernel-small-bundles-fs-support-nfs.md) - - [Ramfs](kernel-small-bundles-fs-support-ramfs.md) - - [Procfs](kernel-small-bundles-fs-support-procfs.md) + - [支持的文件系统](kernel-small-bundles-fs-support.md) - [适配新的文件系统](kernel-small-bundles-fs-new.md) - 调测与工具 - Shell @@ -155,15 +141,7 @@ - [内存信息统计](kernel-small-debug-memory-info.md) - [内存泄漏检测](kernel-small-debug-memory-leak.md) - [踩内存检测](kernel-small-debug-memory-corrupt.md) - - 用户态内存调测 - - [基本概念](kernel-small-debug-user-concept.md) - - [运行机制](kernel-small-debug-user-function.md) - - 使用指导 - - [接口说明](kernel-small-debug-user-guide-api.md) - - [使用说明](kernel-small-debug-user-guide-use.md) - - [接口调用方式](kernel-small-debug-user-guide-use-api.md) - - [命令行参数方式](kernel-small-debug-user-guide-use-cli.md) - - [常见问题](kernel-small-debug-user-faqs.md) + - [用户态内存调测](kernel-small-debug-user.md) - 其他内核调测手段 - [临终遗言](kernel-small-debug-trace-other-lastwords.md) - [常见问题](kernel-small-debug-trace-other-faqs.md) diff --git a/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md b/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md index 8ce3db5c735a90579bb5693248740808c0664419..d2f4b54be58063e23b8f7fc145e96c555b4e27ca 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md +++ b/zh-cn/device-dev/kernel/kernel-mini-appx-lib.md @@ -1,7 +1,500 @@ # 标准库支持 +## CMSIS支持 -- **[CMSIS支持](kernel-mini-appx-lib-cmsis.md)** -- **[POSIX支持](kernel-mini-appx-lib-posix.md)** \ No newline at end of file +### 基本概念 + +[CMSIS](https://developer.arm.com/tools-and-software/embedded/cmsis)是Cortex Microcontroller Software Interface Standard(Cortex微控制器软件接口标准)的缩写,是对于那些基于ARM Cortex处理器的微控制器独立于供应商的硬件抽象层。它包含多个组件层,其中之一是RTOS层,该层定义了一套通用及标准化的RTOS API接口,减少了应用开发者对特定RTOS的依赖,方便用户软件的移植重用。该套API有2个版本,分别为版本1(CMSIS-RTOS v1)和版本2(CMSIS-RTOS v2),OpenHarmony LiteOS-M仅提供其版本2的实现。 + + +### 开发指导 + + +#### 接口说明 + +CMSIS-RTOS v2提供下面几种功能,接口详细信息可以查看API参考。 + + **表1** 内核信息与控制 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osKernelGetInfo | 获取RTOS内核信息。 | +| osKernelGetState | 获取当前的RTOS内核状态。 | +| osKernelGetSysTimerCount | 获取RTOS内核系统计时器计数。 | +| osKernelGetSysTimerFreq | 获取RTOS内核系统计时器频率。 | +| osKernelInitialize | 初始化RTOS内核。 | +| osKernelLock | 锁定RTOS内核调度程序。 | +| osKernelUnlock | 解锁RTOS内核调度程序。 | +| osKernelRestoreLock | 恢复RTOS内核调度程序锁定状态。 | +| osKernelResume | 恢复RTOS内核调度程序。(暂未实现) | +| osKernelStart | 启动RTOS内核调度程序。 | +| osKernelSuspend | 挂起RTOS内核调度程序。(暂未实现) | +| osKernelGetTickCount | 获取RTOS内核滴答计数。 | +| osKernelGetTickFreq | 获取RTOS内核滴答频率。 | + + **表2** 线程管理 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osThreadDetach | 分离线程(线程终止时可以回收线程存储)。(暂未实现) | +| osThreadEnumerate | 枚举活动线程。(暂未实现) | +| osThreadExit | 终止当前正在运行的线程的执行。 | +| osThreadGetCount | 获取活动线程的数量。 | +| osThreadGetId | 返回当前正在运行的线程的线程ID。 | +| osThreadGetName | 获取线程的名称。 | +| osThreadGetPriority | 获取线程的当前优先级。 | +| osThreadGetStackSize | 获取线程的堆栈大小。 | +| osThreadGetStackSpace | 根据执行期间的堆栈水印记录获取线程的可用堆栈空间。 | +| osThreadGetState | 获取线程的当前线程状态。 | +| osThreadJoin | 等待指定线程终止。(暂未实现) | +| osThreadNew | 创建一个线程并将其添加到活动线程中。 | +| osThreadResume | 恢复线程的执行。 | +| osThreadSetPriority | 更改线程的优先级。 | +| osThreadSuspend | 暂停执行线程。 | +| osThreadTerminate | 终止线程的执行。 | +| osThreadYield | 将控制权传递给处于就绪状态的下一个线程。 | + + **表3** 线程标志 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osThreadFlagsSet | 设置线程的指定线程标志。(暂未实现) | +| osThreadFlagsClear | 清除当前正在运行的线程的指定线程标志。(暂未实现) | +| osThreadFlagsGet | 获取当前正在运行的线程的当前线程标志。(暂未实现) | +| osThreadFlagsWait | 等待当前正在运行的线程的一个或多个线程标志发出信号。(暂未实现) | + + **表4** 事件标志 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osEventFlagsGetName | 获取事件标志对象的名称。(暂未实现) | +| osEventFlagsNew | 创建并初始化事件标志对象。 | +| osEventFlagsDelete | 删除事件标志对象。 | +| osEventFlagsSet | 设置指定的事件标志。 | +| osEventFlagsClear | 清除指定的事件标志。 | +| osEventFlagsGet | 获取当前事件标志。 | +| osEventFlagsWait | 等待一个或多个事件标志被发出信号。 | + + **表5** 通用等待函数 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osDelay | 等待超时(时间延迟)。 | +| osDelayUntil | 等到指定时间。 | + + **表6** 计时器管理 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osTimerDelete | 删除计时器。 | +| osTimerGetName | 获取计时器的名称。(暂未实现) | +| osTimerIsRunning | 检查计时器是否正在运行。 | +| osTimerNew | 创建和初始化计时器。 | +| osTimerStart | 启动或重新启动计时器。 | +| osTimerStop | 停止计时器。 | + + **表7** 互斥管理 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osMutexAcquire | 获取互斥或超时(如果已锁定)。 | +| osMutexDelete | 删除互斥对象。 | +| osMutexGetName | 获取互斥对象的名称。(暂未实现) | +| osMutexGetOwner | 获取拥有互斥对象的线程。 | +| osMutexNew | 创建并初始化Mutex对象。 | +| osMutexRelease | 释放由osMutexAcquire获取的Mutex。 | + + **表8** 信号量 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osSemaphoreAcquire | 获取信号量令牌或超时(如果没有可用的令牌)。 | +| osSemaphoreDelete | 删除一个信号量对象。 | +| osSemaphoreGetCount | 获取当前信号量令牌计数。 | +| osSemaphoreGetName | 获取信号量对象的名称。(暂未实现) | +| osSemaphoreNew | 创建并初始化一个信号量对象。 | +| osSemaphoreRelease | 释放信号量令牌,直到初始最大计数。 | + + **表9** 内存池 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osMemoryPoolAlloc | 从内存池分配一个内存块。 | +| osMemoryPoolDelete | 删除内存池对象。 | +| osMemoryPoolFree | 将分配的内存块返回到内存池。 | +| osMemoryPoolGetBlockSize | 获取内存池中的内存块大小。 | +| osMemoryPoolGetCapacity | 获取内存池中最大的内存块数。 | +| osMemoryPoolGetCount | 获取内存池中使用的内存块数。 | +| osMemoryPoolGetName | 获取内存池对象的名称。 | +| osMemoryPoolGetSpace | 获取内存池中可用的内存块数。 | +| osMemoryPoolNew | 创建并初始化一个内存池对象。 | + + **表10** 消息队列 + +| 接口名 | 接口描述 | +| -------- | -------- | +| osMessageQueueDelete | 删除消息队列对象。 | +| osMessageQueueGet | 从队列获取消息,或者如果队列为空,则从超时获取消息。 | +| osMessageQueueGetCapacity | 获取消息队列中的最大消息数。 | +| osMessageQueueGetCount | 获取消息队列中排队的消息数。 | +| osMessageQueueGetMsgSize | 获取内存池中的最大消息大小。 | +| osMessageQueueGetName | 获取消息队列对象的名称。(暂未实现) | +| osMessageQueueGetSpace | 获取消息队列中消息的可用插槽数。 | +| osMessageQueueNew | 创建和初始化消息队列对象。 | +| osMessageQueuePut | 如果队列已满,则将消息放入队列或超时。 | +| osMessageQueueReset | 将消息队列重置为初始空状态。(暂未实现) | + + +#### 开发流程 + +CMSIS-RTOS2组件可以作为库或源代码提供(下图显示了库)。通过添加CMSIS-RTOS2组件(通常是一些配置文件),可以将基于CMSIS的应用程序扩展为具有RTOS功能。只需包含cmsis_os2.h头文件就可以访问RTOS API函数,这使用户应用程序能够处理RTOS内核相关事件,而在更换内核时无需重新编译源代码。 + +静态对象分配需要访问RTOS对象控制块定义。特定于实现的头文件(下图中的os_xx .h)提供对此类控制块定义的访问。对于OpenHarmony LiteOS-M内核,由文件名以los_开头的头文件提供,这些文件包含OpenHarmony LiteOS-M内核的这些定义。 + +![zh-cn_image_0000001153834574](figures/zh-cn_image_0000001153834574.png) + + +#### 编程实例 + + +``` +#include ... +#include "cmsis_os2.h" + +/*---------------------------------------------------------------------------- + * 应用程序主线程 + *---------------------------------------------------------------------------*/ +void app_main (void *argument) { + // ... + for (;;) {} +} + +int main (void) { + // 系统初始化 + MySystemInit(); + // ... + + osKernelInitialize(); // 初始化CMSIS-RTOS + osThreadNew(app_main, NULL, NULL); // 创建应用程序主线程 + osKernelStart(); // 开始执行线程 + for (;;) {} +} +``` + +## POSIX支持 + + +### 基本概念 + +OpenHarmony内核使用**musl libc**库以及自研接口,支持部分标准POSIX接口,开发者可基于POSIX标准接口开发内核之上的组件及应用。 + + +### 开发指导 + + +#### 接口说明 + + **表1** process + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <stdlib.h> | void abort(void); | 中止线程执行 | +| \#include <assert.h> | void assert(scalar expression); | 断言为假终止线程 | +| \#include <pthread.h> | int pthread_cond_destroy(pthread_cond_t \*cond); | 销毁条件变量 | +| \#include <pthread.h> | int pthread_cond_init(pthread_cond_t \*restrict co
nd, const pthread_condattr_t \*restrict attr); | 初始化条件变量 | +| \#include <pthread.h> | int pthread_cond_timedwait(pthread_cond_t \*restr
ict cond, pthread_mutex_t \*restrict mutex, const st
ruct timespec \*restrict abstime); | 等待条件 | +| \#include <pthread.h> | int pthread_condattr_init(pthread_condattr_t \*attr); | 初始化条件变量属性对象 | +| \#include <pthread.h> | int pthread_mutex_unlock(pthread_mutex_t \*mutex); | 解锁互斥锁 | +| \#include <pthread.h> | int pthread_create(pthread_t \*thread, const pthread_
attr_t \*attr, void \*(\*start_routine)(void \*), void \*arg); | 创建一个新的线程 | +| \#include <pthread.h> | int pthread_join(pthread_t thread, void \*\*retval); | 等待指定的线程结束 | +| \#include <pthread.h> | pthread_t pthread_self(void); | 获取当前线程的ID | +| \#include <pthread.h> | int pthread_getschedparam(pthread_t thread, int \*
policy, struct sched_param \*param); | 获取线程的调度策略和参数 | +| \#include <pthread.h> | int pthread_setschedparam(pthread_t thread, int
policy, const struct sched_param \*param); | 设置线程的调度策略和参数 | +| \#include <pthread.h> | int pthread_mutex_init(pthread_mutex_t \*__restrict m
, const pthread_mutexattr_t \*__restrict a); | 初始化互斥锁 | +| \#include <pthread.h> | int pthread_mutex_lock(pthread_mutex_t \*m); | 互斥锁加锁操作 | +| \#include <pthread.h> | int pthread_mutex_trylock(pthread_mutex_t \*m); | 互斥锁尝试加锁操作 | +| \#include <pthread.h> | int pthread_mutex_destroy(pthread_mutex_t \*m); | 销毁互斥锁 | +| \#include <pthread.h> | int pthread_attr_init(pthread_attr_t \*attr); | 初始化线程属性对象 | +| \#include <pthread.h> | int pthread_attr_destroy(pthread_attr_t \*attr); | 销毁线程属性对象 | +| \#include <pthread.h> | int pthread_attr_getstacksize(const pthread_attr
_t \*attr, size_t \*stacksize); | 获取线程属性对象的堆栈大小 | +| \#include <pthread.h> | int pthread_attr_setstacksize(pthread_attr_t \*attr
, size_t stacksize); | 设置线程属性对象的堆栈大小 | +| \#include <pthread.h> | int pthread_attr_getschedparam(const pthread_
attr_t \*attr, struct sched_param \*param); | 获取线程属性对象的调度参数属性 | +| \#include <pthread.h> | int pthread_attr_setschedparam(pthread_attr_t \*
attr, const struct sched_param \*param); | 设置线程属性对象的调度参数属性 | +| \#include <pthread.h> | int pthread_getname_np(pthread_t pthread, char
\*name, size_t len); | 获取线程名称 | +| \#include <pthread.h> | int pthread_setname_np(pthread_t pthread, const
char \*name); | 设置线程名称 | +| \#include <pthread.h> | int pthread_cond_broadcast(pthread_cond_t \*c); | 解除若干已被等待条件阻塞的线程 | +| \#include <pthread.h> | int pthread_cond_signal(pthread_cond_t \*c); | 解除被阻塞的线程 | +| \#include <pthread.h> | int pthread_cond_wait(pthread_cond_t \*__restrict
c, pthread_mutex_t \*__restrict m); | 等待条件 | + + **表2** fs + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <libgen.h> | char \*dirname(char \*path); | 获取目录名 | +| \#include <dirent.h> | struct dirent \*readdir(DIR \*dirp); | 读目录 | +| \#include <sys/stat.h> | int stat(const char \*restrict path, struct stat \*restrict buf); | 获取文件信息 | +| \#include <unistd.h> | int unlink(const char \*pathname); | 删除文件 | +| \#include <fcntl.h | int open(const char \*path, int oflags, ...); | 用于打开文件,如文件不存在,创建文件并打开 | +| \#include <nistd.h> | int close(int fd); | 关闭文件 | +| \#include <stdio.h> | int rename(const char \*oldpath, const char \*newpath); | 重命名指定的文件 | +| \#include <dirent.h> | DIR  \*opendir(const char \*dirname); | 打开指定目录 | +| \#include <dirent.h> | int closedir(DIR \*dir); | 关闭指定目录 | +| \#include <sys/mount.h> | int mount(const char \*source, const char \*target, con
st char \*filesystemtype, unsigned long mountflags, c
onst void \*data); | 挂载文件系统 | +| \#include <sys/mount.h> | int umount(const char \*target); | 卸载文件系统 | +| \#include <sys/mount.h> | int umount2(const char \*target, int flag); | 卸载文件系统 | +| \#include <sys/stat.h> | int fsync(int fd); | 将与指定文件描述符关联的文件同步到存储设备 | +| \#include <sys/stat.h> | int mkdir(const char \*pathname, mode_t mode); | 创建目录 | +| \#include <unistd.h> | int rmdir(const char \*path); | 删除目录 | +| \#include <sys/stat.h> | int fstat(int fd, struct stat \*buf); | 获取文件状态信息 | +| \#include <sys/statfs.h> | int statfs(const char \*path, struct statfs \*buf); | 获取指定路径下文件的文件系统信息 | + + **表3** time + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <sys/time.h> | int gettimeofday(struct timeval \*tv, struct timezone \*tz); | 获取时间。当前暂无时区概念,tz返回为空 | +| \#include <time.h> | struct tm \*gmtime(const time_t \*timep); | 将日期和时间转换为细分时间或ASCII | +| \#include <time.h> | struct tm \*localtime(const time_t \*timep); | 获取时间 | +| \#include <time.h> | struct tm \*localtime_r(const time_t \*timep, struct tm \*result); | 获取时间 | +| \#include <time.h> | time_t mktime(struct tm \*tm); | 将日期和时间转换为细分时间或ASCII | +| \#include <time.h> | size_t strftime(char \*s, size_t max, const char \*
format,const struct tm \*tm); | 格式化日期和时间字符串 | +| \#include <time.h> | time_t time(time_t \*tloc); | 获得日历时间 | +| \#include <sys/times.h> | clock_t times(struct tms \*buf); | 获取线程时间 | +| \#include <unistd.h> | int usleep(useconds_t usec); | 休眠(微秒单位) | +| \#include <time.h> | int nanosleep(const struct timespec \*tspec1, struct
timespec \*tspec2); | 暂停当前线程直到指定的时间到达 | +| \#include <time.h> | int clock_gettime(clockid_t id, struct timespec \*tspec); | 获取时钟的时间 | +| \#include <time.h> | int timer_create(clockid_t id, struct sigevent \*__
restrict evp, timer_t \*__restrict t); | 为线程创建计时器 | +| \#include <time.h> | int timer_delete(timer_t t); | 为线程删除计时器 | +| \#include <time.h> | int timer_settime(timer_t t, int flags, const struct
itimerspec \*__restrict val, struct itimerspec \*__restrict old); | 为线程设置计时器 | +| \#include <time.h> | time_t time (time_t \*t); | 获取时间 | +| \#include <time.h> | char \*strptime(const char \*s, const char \*format, struct tm \*tm); | 将时间的字符串表示形式转换为时间tm结构 | + + **表4** util + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <stdlib.h> | int atoi(const char \*nptr); | 字符串转换整型(int) | +| \#include <stdlib.h> | long atol(const char \*nptr); | 字符串转换整型(long) | +| \#include <stdlib.h> | long long atoll(const char \*nptr); | 字符串转换整型(long long) | +| \#include <ctype.h> | int isalnum(int c); | 检查字母数字字符 | +| \#include <ctype.h> | int isascii(int c); | 检查ASCII | +| \#include <ctype.h> | int isdigit(int c); | 检查数字字符 | +| \#include <ctype.h> | int islower(int c); | 检查小写字符 | +| \#include <ctype.h> | int isprint(int c); | 检查任何可打印字符,包括空格 | +| \#include <ctype.h> | int isspace(int c); | 检查空格字符 | +| \#include <ctype.h> | int isupper(int c); | 检查所传的字符是否是大写字母 | +| \#include <ctype.h> | int isxdigit(int c); | 判断字符是否为十六进制数 | +| \#include <stdlib.h> | long int random (void); | 生成伪随机数 | +| \#include <stdlib.h> | void srandom(unsigned int seed); | 初始化随机数生成器 | +| \#include <ctype.h> | int tolower(int c); | 字母转换成小写 | +| \#include <ctype.h> | int toupper(int c); | 字母转换成大写 | +| \#include <stdarg.h> | type va_arg(va_list ap, type); | 获取可变参数的当前参数,返回指定类型并将指针指向下一参数 | +| \#include <stdarg.h> | void va_copy(va_list dest, va_list src); | 复制参数 | +| \#include <stdarg.h> | void va_end(va_list ap); | 清空va_list可变参数列表 | +| \#include <stdarg.h> | void va_start(va_list ap, last); | 定义变长参数列表的起始位置 | +| \#include <string.h> | char \*strchr(const char \*s, int c); | 在字符串中定位字符 | +| \#include <string.h> | int strcmp(const char \*s1, const char \*s2); | 比较字符串 | +| \#include <string.h> | size_t strcspn(const char \*s, const char \*reject); | 获取前缀子串的长度 | +| \#include <string.h> | char \*strdup(const char \*s); | 字符串拷贝到新建的位置处 | +| \#include <string.h> | size_t strlen(const char \*s); | 计算字符串长度 | +| \#include <strings.h> | int strncasecmp(const char \*s1, const char \*s2, size_t n); | 比较固定长度字符串(忽略大小写) | +| \#include <strings.h> | int strcasecmp(const char \*s1, const char \*s2); | 比较字符串(忽略大小写) | +| \#include <string.h> | int strncmp(const char \*s1, const char \*s2, size_t n); | 比较字符串(指定长度) | +| \#include <string.h> | char \*strrchr(const char \*s, int c); | 在字符串中定位字符 | +| \#include <string.h> | char \*strstr(const char \*haystack, const char \*needle); | 寻找指定的子串 | +| \#include <stdlib.h> | long int strtol(const char \*nptr, char \*\*endptr, int base); | 将字符串转换为long型整数 | +| \#include <stdlib.h> | unsigned long int strtoul(const char \*nptr, char
\*\*endptr, int base); | 将字符串转换为unsigned long型整数 | +| \#include <stdlib.h> | unsigned long long int strtoull(const char \*nptr,
char \*\*endptr,int base); | 将字符串转换为unsigned long long型整数 | +| \#include <regex.h> | int regcomp(regex_t \*preg, const char \*regex,
int cflags); | 编译正则表达式 | +| \#include <regex.h> | int regexec(const regex_t \*preg, const char \*
string, size_t nmatch,regmatch_t pmatch[], int eflags); | 匹配正则表达式 | +| \#include <regex.h> | void regfree(regex_t \*preg); | 释放正则表达式 | +| \#include <string.h> | char \*strerror(int errnum); | 返回描述错误号的字符串 | + + **表5** math + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <stdlib.h> | int abs(int i); | 取绝对值 | +| \#include <math.h> | double log(double x); | 自然对数函数 | +| \#include <math.h> | double pow(double x, double y); | 求x的指数y次幂 | +| \#include <math.h> | double round(double x); | 从零开始,舍入到最接近的整数 | +| \#include <math.h> | double sqrt(double x); | 平方根 | + + **表6** IO + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <stdio.h> | void clearerr(FILE \*stream); | 清除流的文件结尾和错误指示 | +| \#include <stdio.h> | int fclose(FILE \*stream); | 关闭文件流 | +| \#include <stdio.h> | FILE \*fdopen(int fd, const char \*mode); | 通过文件描述符打开文件流 | +| \#include <stdio.h> | int feof(FILE \*stream); | 检测返回文件末尾指示位 | +| \#include <stdio.h> | int fflush(FILE \*stream); | 刷新流 | +| \#include <stdio.h> | char \*fgets(char \*s, int size, FILE \*stream); | 读取流的下一行 | +| \#include <stdio.h> | int fileno(FILE \*stream); | 返回流的文件描述符 | +| \#include <stdio.h> | FILE \*fopen(const char \*path, const char \*mode); | 打开流 | +| \#include <stdio.h> | int fputs(const char \*s, FILE \*stream); | 向指定流写入一行 | +| \#include <stdio.h> | size_t fread(void \*ptr, size_t size, size_t nmemb,
FILE \*stream); | 读一个流 | +| \#include <stdio.h> | int fseek(FILE \*stream, long offset, int whence); | 设置流指针的位置 | +| \#include <stdio.h> | long ftell(FILE \*stream); | 获取流指针的位置 | +| \#include <stdio.h> | size_t fwrite(const void \*ptr, size_t size, size_t
nmemb,FILE \*stream); | 向流写入 | +| \#include <stdio.h> | void perror(const char \*s); | 打印系统错误信息 | +| \#include <stdio.h> | void rewind(FILE \*stream); | 重新定位流 | +| \#include <unistd.h> | ssize_t write(int fd, const void \*buf, size_t size); | 写文件内容 | +| \#include <unistd.h> | ssize_t read(int fd, void \*buf, size_t size); | 读文件内容 | + + **表7** net + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <sys/socket.h> | void freeaddrinfo(struct addrinfo \*res); | 释放调用getaddrinfo所分配的动态内存 | +| \#include <sys/socket.h> | int getaddrinfo(const char \*restrict nodename,const
char \*restrict servname,const struct addrinfo \*restrict
hints,struct addrinfo \*\*restrict res); | 网络地址和服务转换 | +| \#include <sys/socket.h> | int getnameinfo(const struct sockaddr \*restrict sa,
socklen_t salen,char \*restrict node, socklen_t nodelen
, char \*restrict service,socklen_t servicelen, int flags); | 以协议无关的方式进行地址到名称的转换 | +| \#include <net/if.h> | unsigned int if_nametoindex(const char \*ifname); | 通过网络接口名得到索引 | +| \#include <arpa/inet.h> | in_addr_t inet_addr(const char \*cp); | 网络主机地址点分十进制形式转换位二进制形式 | +| \#include <arpa/inet.h> | char \*inet_ntoa(struct in_addr in); | 网络主机地址二进制形式转换位点分十进制形式 | +| \#include <arpa/inet.h> | const char \*inet_ntop(int af, const void \*src,char \*dst,
socklen_t size); | 网络地址转换 | +| \#include <arpa/inet.h> | int inet_pton(int af, const char \*src, void \*dst); | 网络地址转换 | +| \#include <sys/socket.h> | int listen(int sockfd, int backlog); | 监听套接字 | +| \#include <sys/socket.h> | ssize_t recvmsg(int sockfd, struct msghdr \*msg, int flags); | 从套接字接收消息.只支持iov大小为1的场景,且不支持ancillary消息 | +| \#include <sys/socket.h> | ssize_t send(int sockfd, const void \*buf, size_t len, int flags); | 从socket发送消息 | +| \#include <sys/socket.h> | ssize_t sendmsg(int sockfd, const struct msghdr \*msg, int flags); | 从socket发送消息。不支持ancillary消息 | +| \#include <sys/socket.h> | ssize_t sendto(int sockfd, const void \*buf, size_t len, int
flags,const struct sockaddr \*dest_addr, socklen_t addrlen); | 从socket发送消息 | +| \#include <sys/socket.h> | int setsockopt(int sockfd, int level, int optname,const
void \*optval, socklen_t optlen); | 设置与套接字关联的选项 | + + **表8** mem + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <string.h> | int memcmp(const void \*s1, const void \*s2, size_t n); | 内存比较 | +| \#include <string.h> | void \*memcpy(void \*dest, const void \*src, size_t n); | 内存拷贝 | +| \#include <string.h> | void \*memset(void \*s, int c, size_t n); | 内存初始化 | +| \#include <stdlib.h> | void \*realloc(void \*ptr, size_t size); | 重分配内存 | +| \#include <stdlib.h> | void \*malloc(size_t size); | 动态分配内存块大小 | +| \#include <stdlib.h> | void free(void \*ptr); | 释放ptr所指向的内存空间 | + + **表9** IPC + +| 需要包含的头文件 | 接口名 | 描述 | +| -------- | -------- | -------- | +| \#include <semaphore.h> | int sem_timedwait(sem_t \*sem, const struct
 timespec \*abs_timeout); | 计时锁定信号量 | +| \#include <semaphore.h> | int sem_destroy(sem_t \*sem); | 销毁指定的无名信号量 | +| \#include <semaphore.h> | int sem_init(sem_t \*sem, int pshared
, unsigned int value); | 创建并初始化一个无名信号量 | +| \#include <semaphore.h> | int sem_post(sem_t \*sem); | 增加信号量计数 | +| \#include <semaphore.h> | int sem_wait(sem_t \*sem); | 获取信号量 | +| \#include <mqueue.h> | mqd_t mq_open(const char \*mqName,
 int openFlag, ...); | 此API用于打开一个具有指定名称的已有消息队列或创建一个新的消息队列 | +| \#include <mqueue.h> | int mq_close(mqd_t personal); | 此API用于关闭具有指定描述符的消息队列 | +| \#include <mqueue.h> | int mq_unlink(const char \*mqName); | 此API用于删除具有指定名称的消息队列 | +| \#include <mqueue.h> | int mq_send(mqd_t personal, const
 char \*msg,size_t msgLen, unsigned int msgPrio); | 此API用于将具有指定内容和长度的消息放入具有指定描述符的消息队列中 | +| \#include <mqueue.h> | ssize_t mq_receive(mqd_t personal, char \*msg,
size_t msgLen, unsigned int \*msgPrio); | 此API用于从具有指定描述符的消息队列中删除最老的消息,并将其放入msg_ptr所指向的缓冲区中 | +| \#include <mqueue.h> | int mq_timedsend(mqd_t personal, const char
\*msg, size_t msgLen, unsigned int msgPrio, c
onst struct timespec \*absTimeout) | 此API用于在预定时间将具有指定内容和长度的消息放入具有描述符的消息队列中 | +| \#include <mqueue.h> | ssize_t mq_timedreceive(mqd_t personal, char
\*msg, size_t msgLen, unsigned int \*msgPrio,
const struct timespec \*absTimeout); | 此API用于从具有指定描述符的消息队列消息中获取具有指定消息内容和长度的消息 | +| \#include <mqueue.h> | int mq_setattr(mqd_t mqdes, const struct mq_
attr \*__restrict newattr, struct mq_attr \*__restrict oldattr); | 设置描述符指定的消息队列属性 | +| \#include <libc.h> | const char \*libc_get_version_string(void); | 获取libc版本字符串 | +| \#include <libc.h> | int libc_get_version(void); | 获取libc版本号 | + + +#### 注意事项 + +常用错误码对照表: + +| 错误码 | 值 | 描述 | 含义 | +| -------- | -------- | -------- | -------- | +| ENOERR | 0 | Success | 成功 | +| EPERM | 1 | Operation not permitted | 操作不允许 | +| ENOENT | 2 | No such file or directory | 没有这样的文件或目录 | +| ESRCH | 3 | No such process | 没有这样的进程(暂不支持) | +| EINTR | 4 | Interrupted system call | 系统调用被中断 | +| EIO | 5 | I/O error | I/O错误 | +| ENXIO | 6 | No such device or address | 没有这样的设备或地址 | +| E2BIG | 7 | Arg list too long | 参数列表太长 | +| ENOEXEC | 8 | Exec format error | 执行格式错误 | +| EBADF | 9 | Bad file number | 坏的文件描述符 | +| ECHILD | 10 | No child processes | 没有子进程(暂不支持) | +| EAGAIN | 11 | Try again | 资源暂时不可用 | +| ENOMEM | 12 | Out of memory | 内存溢出 | +| EACCES | 13 | Permission denied | 拒绝许可 | +| EFAULT | 14 | Bad address | 错误的地址 | +| ENOTBLK | 15 | Block device required | 块设备请求 | +| EBUSY | 16 | Device or resource busy | 设备或资源忙 | +| EEXIST | 17 | File exists | 文件存在 | +| EXDEV | 18 | Cross-device link | 无效的交叉链接 | +| ENODEV | 19 | No such device | 设备不存在 | +| ENOTDIR | 20 | Not a directory | 不是一个目录 | +| EISDIR | 21 | Is a directory | 是一个目录 | +| EINVAL | 22 | Invalid argument | 无效的参数 | +| ENFILE\* | 23 | File table overflow | 打开太多的文件系统 | +| EMFILE | 24 | Too many open files | 打开的文件过多 | +| EFBIG | 27 | File too large | 文件太大 | +| ENOSPC | 28 | No space left on device | 设备上没有空间 | +| ESPIPE | 29 | Illegal seek | 非法移位 | +| EROFS | 30 | Read-only file system | 只读文件系统 | +| EMLINK | 31 | Too many links | 太多的链接 | +| EDOM | 33 | Math argument out of domain | 数值结果超出范围 | +| ERANGE | 34 | Math result not representable | 数值结果不具代表性 | +| EDEADLK | 35 | Resource deadlock would occur | 资源死锁错误 | +| ENAMETOOLONG | 36 | Filename too long | 文件名太长 | +| ENOLCK | 37 | No record locks available | 没有可用锁 | +| ENOSYS | 38 | Function not implemented | 功能没有实现 | +| ENOTEMPTY | 39 | Directory not empty | 目录不空 | +| ELOOP | 40 | Too many symbolic links encountered | 符号链接层次太多 | +| ENOMSG | 42 | No message of desired type | 没有期望类型的消息 | +| EIDRM | 43 | Identifier removed | 标识符删除 | +| ELNRNG | 48 | Link number out of range | 链接数超出范围 | +| EBADR | 53 | Invalid request descriptor | 请求描述符无效 | +| EBADRQC | 56 | Invalid request code | 无效的请求代码 | +| ENOSTR | 60 | Device not a stream | 设备不是字符流 | +| ENODATA | 61 | No data available | 无可用数据 | +| ETIME | 62 | Timer expired | 计时器过期 | +| EPROTO | 71 | Protocol error | 协议错误 | +| EBADMSG | 74 | Not a data message | 非数据消息 | +| EOVERFLOW | 75 | Value too large for defined data type | 值太大,对于定义数据类型 | +| EMSGSIZE | 90 | Message too long | 消息太长 | + + +#### 编程实例 + +demo功能: + +创建一个线程并将父线程中的信息传递给子线程,在子线程中打印传递过来的信息和自身线程id值。 + + +``` +#include +#include + +pthread_t ntid; + +void *ThreadFn(void *arg) +{ + pthread_t tid; + while(1) { + tid = pthread_self(); + printf("\n++++++++++++++ %s %s tid = %d ++++++++++++++\n", (char*)arg, __FUNCTION__, tid); + } + return ((void *)0); +} + +void DemoForTest() +{ + int err; + char* str = "Hello world"; + err = pthread_create(&ntid, NULL, ThreadFn, (void*)str); + if(err != 0) { + printf("can't create thread\n"); + } +} + +``` + +执行DemoForTest运行结果如下: + + +``` +++++++++++++++ Hello world ThreadFn tid = 48 ++++++++++++++ + +++++++++++++++ Hello world ThreadFn tid = 48 ++++++++++++++ + +++++++++++++++ Hello world ThreadFn tid = 48 ++++++++++++++ +``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md index afc518c52ce6037e598cad7b54a883c0f8c7e6eb..5071ddf325680c7d939907b5bb2fd8d8f1368e77 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-memory.md @@ -1,9 +1,322 @@ # 内存管理 +## 基本概念 +内存管理模块管理系统的内存资源,它是操作系统的核心模块之一,主要包括内存的初始化、分配以及释放。 -- **[基本概念](kernel-mini-basic-memory-basic.md)** -- **[静态内存](kernel-mini-basic-memory-static.md)** +在系统运行过程中,内存管理模块通过对内存的申请/释放来管理用户和OS对内存的使用,使内存的利用率和使用效率达到最优,同时最大限度地解决系统的内存碎片问题。 -- **[动态内存](kernel-mini-basic-memory-dynamic.md)** \ No newline at end of file + +OpenHarmony LiteOS-M的内存管理分为静态内存管理和动态内存管理,提供内存初始化、分配、释放等功能。 + + +- 动态内存:在动态内存池中分配用户指定大小的内存块。 + - 优点:按需分配。 + - 缺点:内存池中可能出现碎片。 + +- 静态内存:在静态内存池中分配用户初始化时预设(固定)大小的内存块。 + - 优点:分配和释放效率高,静态内存池中无碎片。 + - 缺点:只能申请到初始化预设大小的内存块,不能按需申请。 +## 静态内存 + + +### 运行机制 + +静态内存实质上是一个静态数组,静态内存池内的块大小在初始化时设定,初始化后块大小不可变更。 + +静态内存池由一个控制块LOS_MEMBOX_INFO和若干相同大小的内存块LOS_MEMBOX_NODE构成。控制块位于内存池头部,用于内存块管理,包含内存块大小uwBlkSize,内存块数量uwBlkNum,已分配使用的内存块数量uwBlkCnt和空闲内存块链表stFreeList。内存块的申请和释放以块大小为粒度,每个内存块包含指向下一个内存块的指针pstNext。 + + **图1** 静态内存示意图 + ![zh-cn_image_0000001199352039](figures/zh-cn_image_0000001199352039.png) + + +### 开发指导 + + +#### 使用场景 + +当用户需要使用固定长度的内存时,可以通过静态内存分配的方式获取内存,一旦使用完毕,通过静态内存释放函数归还所占用内存,使之可以重复使用。 + + +#### 接口说明 + +OpenHarmony LiteOS-M的静态内存管理主要为用户提供以下功能,接口详细信息可以查看API参考。 + + **表1** 静态内存模块接口 + +| 功能分类 | 接口名 | +| -------- | -------- | +| 初始化静态内存池 | LOS_MemboxInit:初始化一个静态内存池,根据入参设定其起始地址、总大小及每个内存块大小。 | +| 清除静态内存块内容 | LOS_MemboxClr:清零从静态内存池中申请的静态内存块的内容。 | +| 申请、释放静态内存 | - LOS_MemboxAlloc:从指定的静态内存池中申请一块静态内存块。
- LOS_MemboxFree:释放从静态内存池中申请的一块静态内存块。 | +| 获取、打印静态内存池信息 | - LOS_MemboxStatisticsGet:获取指定静态内存池的信息,包括内存池中总内存块数量、已经分配出去的内存块数量、每个内存块的大小。
- LOS_ShowBox:打印指定静态内存池所有节点信息(打印等级是LOS_INFO_LEVEL),包括内存池起始地址、内存块大小、总内存块数量、每个空闲内存块的起始地址、所有内存块的起始地址。 | + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 初始化后的内存池的内存块数量,不等于总大小除于内存块大小,因为内存池的控制块和每个内存块的控制头,都存在内存开销,设置总大小时,需要将这些因素考虑进去。 + + +#### 开发流程 + +本节介绍使用静态内存的典型场景开发流程。 + +1. 规划一片内存区域作为静态内存池。 + +2. 调用LOS_MemboxInit初始化静态内存池。 + 初始化会将入参指定的内存区域分割为N块(N值取决于静态内存总大小和块大小),将所有内存块挂到空闲链表,在内存起始处放置控制头。 + +3. 调用LOS_MemboxAlloc接口分配静态内存。 + 系统将会从空闲链表中获取第一个空闲块,并返回该内存块的起始地址。 + +4. 调用LOS_MemboxClr接口。 + 将入参地址对应的内存块清零。 + +5. 调用LOS_MemboxFree接口。 + 将该内存块加入空闲链表。 + + +#### 编程实例 + +本实例执行以下步骤: + +1. 初始化一个静态内存池。 + +2. 从静态内存池中申请一块静态内存。 + +3. 在内存块存放一个数据。 + +4. 打印出内存块中的数据。 + +5. 清除内存块中的数据。 + +6. 释放该内存块。 + 示例代码如下: + + +``` +#include "los_membox.h" + +VOID Example_StaticMem(VOID) +{ + UINT32 *mem = NULL; + UINT32 blkSize = 10; + UINT32 boxSize = 100; + UINT32 boxMem[1000]; + UINT32 ret; + + /*内存池初始化*/ + ret = LOS_MemboxInit(&boxMem[0], boxSize, blkSize); + if(ret != LOS_OK) { + printf("Membox init failed!\n"); + return; + } else { + printf("Membox init success!\n"); + } + + /*申请内存块*/ + mem = (UINT32 *)LOS_MemboxAlloc(boxMem); + if (NULL == mem) { + printf("Mem alloc failed!\n"); + return; + } + printf("Mem alloc success!\n"); + + /*赋值*/ + *mem = 828; + printf("*mem = %d\n", *mem); + + /*清除内存内容*/ + LOS_MemboxClr(boxMem, mem); + printf("Mem clear success \n *mem = %d\n", *mem); + + /*释放内存*/ + ret = LOS_MemboxFree(boxMem, mem); + if (LOS_OK == ret) { + printf("Mem free success!\n"); + } else { + printf("Mem free failed!\n"); + } + + return; +} +``` + + +#### 结果验证 + +输出结果如下: + + +``` +Membox init success! +Mem alloc success! +*mem = 828 +Mem clear success +*mem = 0 +Mem free success! +``` +## 动态内存 + + +### 运行机制 + +动态内存管理,即在内存资源充足的情况下,根据用户需求,从系统配置的一块比较大的连续内存(内存池,也是堆内存)中分配任意大小的内存块。当用户不需要该内存块时,又可以释放回系统供下一次使用。与静态内存相比,动态内存管理的优点是按需分配,缺点是内存池中容易出现碎片。 + +OpenHarmony LiteOS-M动态内存在TLSF算法的基础上,对区间的划分进行了优化,获得更优的性能,降低了碎片率。动态内存核心算法框图如下: + + **图1** 轻量系统动态内存核心算法 + ![zh-cn_image_0000001199352445](figures/zh-cn_image_0000001199352445.png) + +根据空闲内存块的大小,使用多个空闲链表来管理。根据内存空闲块大小分为两个部分:[4, 127]和[27, 231],如上图size class所示: + +1. 对[4,127]区间的内存进行等分,如上图下半部分所示,分为31个小区间,每个小区间对应内存块大小为4字节的倍数。每个小区间对应一个空闲内存链表和用于标记对应空闲内存链表是否为空的一个比特位,值为1时,空闲链表非空。[4,127]区间的31个小区间内存对应31个比特位进行标记链表是否为空。 + +2. 大于127字节的空闲内存块,按照2的次幂区间大小进行空闲链表管理。总共分为24个小区间,每个小区间又等分为8个二级小区间,见上图上半部分的Size Class和Size SubClass部分。每个二级小区间对应一个空闲链表和用于标记对应空闲内存链表是否为空的一个比特位。总共24\*8=192个二级小区间,对应192个空闲链表和192个比特位进行标记链表是否为空。 + +例如,当有40字节的空闲内存需要插入空闲链表时,对应小区间[40,43],第10个空闲链表,位图标记的第10比特位。把40字节的空闲内存挂载第10个空闲链表上,并判断是否需要更新位图标记。当需要申请40字节的内存时,根据位图标记获取存在满足申请大小的内存块的空闲链表,从空闲链表上获取空闲内存节点。如果分配的节点大于需要申请的内存大小,进行分割节点操作,剩余的节点重新挂载到相应的空闲链表上。当有580字节的空闲内存需要插入空闲链表时,对应二级小区间[2^9,2^9+2^6],第31+2\*8=47个空闲链表,并使用位图的第47个比特位来标记链表是否为空。把580字节的空闲内存挂载第47个空闲链表上,并判断是否需要更新位图标记。当需要申请580字节的内存时,根据位图标记获取存在满足申请大小的内存块的空闲链表,从空闲链表上获取空闲内存节点。如果分配的节点大于需要申请的内存大小,进行分割节点操作,剩余的节点重新挂载到相应的空闲链表上。如果对应的空闲链表为空,则向更大的内存区间去查询是否有满足条件的空闲链表,实际计算时,会一次性查找到满足申请大小的空闲链表。 + +内存管理结构如下图所示: + + **图2** 轻量系统动态内存管理结构图 + ![zh-cn_image_0000001153313284](figures/zh-cn_image_0000001153313284.png) + +- 内存池池头部分 + 内存池池头部分包含内存池信息、位图标记数组和空闲链表数组。内存池信息包含内存池起始地址及堆区域总大小,内存池属性。位图标记数组有7个32位无符号整数组成,每个比特位标记对应的空闲链表是否挂载空闲内存块节点。空闲内存链表包含223个空闲内存头节点信息,每个空闲内存头节点信息维护内存节点头和空闲链表中的前驱、后继空闲内存节点。 + +- 内存池节点部分 + 包含3种类型节点:未使用空闲内存节点,已使用内存节点和尾节点。每个内存节点维护一个前序指针,指向内存池中上一个内存节点,还维护内存节点的大小和使用标记。空闲内存节点和已使用内存节点后面的内存区域是数据域,尾节点没有数据域。 + +一些芯片片内RAM大小无法满足要求,需要使用片外物理内存进行扩充。对于这样的多段非连续性内存, LiteOS-M内核支持把多个非连续性内存逻辑上合一,用户不感知底层的多段非连续性内存区域。 LiteOS-M内核内存模块把不连续的内存区域作为空闲内存结点插入到空闲内存节点链表,把不同内存区域间的不连续部分标记为虚拟的已使用内存节点,从逻辑上把多个非连续性内存区域实现为一个统一的内存池。下面通过示意图说明下多段非连续性内存的运行机制: + + **图3** 非连续性内存合一示意图 + ![zh-cn_image_0000001198253551](figures/zh-cn_image_0000001198253551.png) + +结合上述示意图,非连续性内存合并为一个统一的内存池的步骤如下: + +1. 把多段非连续性内存区域的第一块内存区域通过调用LOS_MemInit接口进行初始化。 + +2. 获取下一个内存区域的开始地址和长度,计算该内存区域和上一块内存区域的间隔大小gapSize。 + +3. 把内存区域间隔部分视为虚拟的已使用节点,使用上一个内存区域的尾节点,设置其大小为gapSize+ OS_MEM_NODE_HEAD_SIZE。 + +4. 把当前内存区域划分为一个空闲内存节点和一个尾节点,把空闲内存节点插入到空闲链表,并设置各个节点的前后链接关系。 + +5. 如果有更多的非连续内存区域,重复上述步骤2-4。 + + +### 开发指导 + + +#### 使用场景 + +动态内存管理的主要工作是动态分配并管理用户申请到的内存区间。动态内存管理主要用于用户需要使用大小不等的内存块的场景,当用户需要使用内存时,可以通过操作系统的动态内存申请函数索取指定大小的内存块,一旦使用完毕,通过动态内存释放函数归还所占用内存,使之可以重复使用。 + + +#### 接口说明 + +OpenHarmony LiteOS-M的动态内存管理主要为用户提供以下功能,接口详细信息可以查看API参考。 + + **表1** 动态内存模块接口 + +| 功能分类 | 接口描述 | +| -------- | -------- | +| 初始化和删除内存池 | - LOS_MemInit:初始化一块指定的动态内存池,大小为size。
- LOS_MemDeInit:删除指定内存池,仅打开LOSCFG_MEM_MUL_POOL时有效。 | +| 申请、释放动态内存 | - LOS_MemAlloc:从指定动态内存池中申请size长度的内存。
- LOS_MemFree:释放从指定动态内存中申请的内存。
- LOS_MemRealloc:释放从指定动态内存中申请的内存。 | +| 获取内存池信息 | - LOS_MemPoolSizeGet:获取指定动态内存池的总大小。
- LOS_MemTotalUsedGet:获取指定动态内存池的总使用量大小。
- LOS_MemInfoGet:获取指定内存池的内存结构信息,包括空闲内存大小、已使用内存大小、空闲内存块数量、已使用的内存块数量、最大的空闲内存块大小。
- LOS_MemPoolList:打印系统中已初始化的所有内存池,包括内存池的起始地址、内存池大小、空闲内存总大小、已使用内存总大小、最大的空闲内存块大小、空闲内存块数量、已使用的内存块数量。仅打开LOSCFG_MEM_MUL_POOL时有效。 | +| 获取内存块信息 | - LOS_MemFreeNodeShow:打印指定内存池的空闲内存块的大小及数量。
- LOS_MemUsedNodeShow:打印指定内存池的已使用内存块的大小及数量。 | +| 检查指定内存池的完整性 | LOS_MemIntegrityCheck:对指定内存池做完整性检查,仅打开LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK时有效。 | +| 增加非连续性内存区域 | LOS_MemRegionsAdd:支持多段非连续性内存区域,把非连续性内存区域逻辑上整合为一个统一的内存池。仅打开LOSCFG_MEM_MUL_REGIONS时有效。如果内存池指针参数pool为空,则使用多段内存的第一个初始化为内存池,其他内存区域,作为空闲节点插入;如果内存池指针参数pool不为空,则把多段内存作为空闲节点,插入到指定的内存池。 | + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> - 由于动态内存管理需要管理控制块数据结构来管理内存,这些数据结构会额外消耗内存,故实际用户可使用内存总量小于配置项OS_SYS_MEM_SIZE的大小。 +> +> - 对齐分配内存接口LOS_MemAllocAlign/LOS_MemMallocAlign因为要进行地址对齐,可能会额外消耗部分内存,故存在一些遗失内存,当系统释放该对齐内存时,同时回收由于对齐导致的遗失内存。 +> +> - 非连续性内存区域接口LOS_MemRegionsAdd的LosMemRegion数组参数传入的非连续性内存区域需要按各个内存区域的内存开始地址升序,且内存区域不能重叠。 + + +#### 开发流程 + +本节介绍使用动态内存的典型场景开发流程。 + +1. 初始化LOS_MemInit。 + 初始一个内存池后生成一个内存池控制头、尾节点EndNode,剩余的内存被标记为FreeNode内存节点。注:EndNode作为内存池末尾的节点,size为0。 + +1. 申请任意大小的动态内存LOS_MemAlloc。 + 判断动态内存池中是否存在大于申请量大小的空闲内存块空间,若存在,则划出一块内存块,以指针形式返回,若不存在,返回NULL。如果空闲内存块大于申请量,需要对内存块进行分割,剩余的部分作为空闲内存块挂载到空闲内存链表上。 + +1. 释放动态内存LOS_MemFree。 + 回收内存块,供下一次使用。调用LOS_MemFree释放内存块,则会回收内存块,并且将其标记为FreeNode。在回收内存块时,相邻的FreeNode会自动合并。 + + +#### 编程实例 + +本实例执行以下步骤: + +1. 初始化一个动态内存池。 + +2. 从动态内存池中申请一个内存块。 + +3. 在内存块中存放一个数据。 + +4. 打印出内存块中的数据。 + +5. 释放该内存块。 + +示例代码如下: + + +``` +#include "los_memory.h" +#define TEST_POOL_SIZE (2*1024) +__attribute__((aligned(4))) UINT8 g_testPool[TEST_POOL_SIZE]; +VOID Example_DynMem(VOID) +{ + UINT32 *mem = NULL; + UINT32 ret; + + /*初始化内存池*/ + ret = LOS_MemInit(g_testPool, TEST_POOL_SIZE); + if (LOS_OK == ret) { + printf("Mem init success!\n"); + } else { + printf("Mem init failed!\n"); + return; + } + + /*分配内存*/ + mem = (UINT32 *)LOS_MemAlloc(g_testPool, 4); + if (NULL == mem) { + printf("Mem alloc failed!\n"); + return; + } + printf("Mem alloc success!\n"); + + /*赋值*/ + *mem = 828; + printf("*mem = %d\n", *mem); + + /*释放内存*/ + ret = LOS_MemFree(g_testPool, mem); + if (LOS_OK == ret) { + printf("Mem free success!\n"); + } else { + printf("Mem free failed!\n"); + } + + return; +} +``` + + +#### 结果验证 + +输出结果如下: + + +``` +Mem init success! +Mem alloc success! +*mem = 828 +Mem free success! +``` diff --git a/zh-cn/device-dev/kernel/kernel-mini-extend-file.md b/zh-cn/device-dev/kernel/kernel-mini-extend-file.md index 65e95f800c497f322f28bc990c0665978e7580bf..e0df347da27479ec128062a02c44d458cf6cd9b7 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-extend-file.md +++ b/zh-cn/device-dev/kernel/kernel-mini-extend-file.md @@ -40,7 +40,292 @@ M核的文件系统子系统当前支持的文件系统有FATFS与LittleFS。同 | umount2 | 分区卸载,可通过MNT_FORCE参数进行强制卸载 | 支持 | 不支持 | | statfs | 获取分区信息 | 支持 | 不支持 | +## FAT -- **[FAT](kernel-mini-extend-file-fat.md)** -- **[LittleFS](kernel-mini-extend-file-lit.md)** \ No newline at end of file +### 基本概念 + +FAT文件系统是File Allocation Table(文件配置表)的简称,主要包括DBR区、FAT区、DATA区三个区域。其中,FAT区各个表项记录存储设备中对应簇的信息,包括簇是否被使用、文件下一个簇的编号、是否文件结尾等。FAT文件系统有FAT12、FAT16、FAT32等多种格式,其中,12、16、32表示对应格式中FAT表项的比特数。FAT文件系统支持多种介质,特别在可移动存储介质(U盘、SD卡、移动硬盘等)上广泛使用,使嵌入式设备和Windows、Linux等桌面系统保持很好的兼容性,方便用户管理操作文件。 + +OpenHarmony内核支持FAT12、FAT16与FAT32三种格式的FAT文件系统,具有代码量小、资源占用小、可裁切、支持多种物理介质等特性,并且与Windows、Linux等系统保持兼容,支持多设备、多分区识别等功能。OpenHarmony内核支持硬盘多分区,可以在主分区以及逻辑分区上创建FAT文件系统。 + + +### 开发指导 + + +#### 驱动适配 + +FAT文件系统的使用需要底层MMC相关驱动的支持。在一个带MMC存储设备的板子上运行FATFS,需要: + +1、适配板端EMMC驱动,实现disk_status、disk_initialize、disk_read、disk_write、disk_ioctl接口; + +2、新增fs_config.h文件,配置FS_MAX_SS(存储设备最大sector大小)、FF_VOLUME_STRS(分区名)等信息,例如: + + +``` +#define FF_VOLUME_STRS "system", "inner", "update", "user" +#define FS_MAX_SS 512 +#define FAT_MAX_OPEN_FILES 50 +``` + + +#### 开发流程 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> - FATFS文件与目录操作: +> - 单个文件大小不超过4G。 +> - 支持同时打开的文件数最大为FAT_MAX_OPEN_FILES,文件夹数最大为FAT_MAX_OPEN_DIRS。 +> - 暂不支持根目录管理,文件/目录名均以分区名开头,例如“user/testfile”就是在“user”分区下名为“testfile”的文件或目录。 +> - 若需要同时多次打开同一文件,必须全部使用只读方式(O_RDONLY)。以可写方式(O_RDWR、O_WRONLY等)只能打开一次。 +> - 读写指针未分离,例如以O_APPEND(追加写)方式打开文件后,读指针也在文件尾,从头读文件前需要用户手动置位。 +> - 暂不支持文件与目录的权限管理。 +> - stat及fstat接口暂不支持查询修改时间、创建时间和最后访问时间。微软FAT协议不支持1980年以前的时间。 +> +> - FATFS分区挂载与卸载: +> - 支持以只读属性挂载分区。当mount函数的入参为MS_RDONLY时,所有的带有写入的接口,如write、mkdir、unlink,以及非O_RDONLY属性的open,将均被拒绝。 +> - mount支持通过MS_REMOUNT标记修改已挂载分区的权限。 +> - 在umount操作前,需确保所有目录及文件全部关闭。 +> - umount2支持通过MNT_FORCE参数强制关闭所有文件与文件夹并umount,但可能造成数据丢失,请谨慎使用。 +> +> - FATFS支持重新划分存储设备分区、格式化分区,对应接口为fatfs_fdisk与fatfs_format: +> - 在fatfs_format操作之前,若需要格式化的分区已挂载,需确保分区中的所有目录及文件全部关闭,并且分区umount。 +> - 在fatfs_fdisk操作前,需要该设备中的所有分区均已umount。 +> - fatfs_fdisk与fatfs_format会造成设备数据丢失,请谨慎使用。 + + +### 编程实例 + + +#### 实例描述 + +本实例实现以下功能: + +1. 创建目录“user/test” + +2. 在“user/test”目录下创建文件“file.txt” + +3. 在文件起始位置写入“Hello OpenHarmony!” + +4. 将文件内容刷入设备中 + +5. 设置偏移到文件起始位置 + +6. 读取文件内容 + +7. 关闭文件 + +8. 删除文件 + +9. 删除目录 + + +#### 示例代码 + + **前提条件:** + + 系统已将MMC设备分区挂载到user目录 + + **代码实现如下:** + + ``` + #include + #include + #include "sys/stat.h" + #include "fcntl.h" + #include "unistd.h" + + #define LOS_OK 0 + #define LOS_NOK -1 + + int FatfsTest(void) + { + int ret; + int fd = -1; + ssize_t len; + off_t off; + char dirName[20] = "user/test"; + char fileName[20] = "user/test/file.txt"; + char writeBuf[20] = "Hello OpenHarmony!"; + char readBuf[20] = {0}; + + /* 创建目录“user/test” */ + ret = mkdir(dirName, 0777); + if (ret != LOS_OK) { + printf("mkdir failed.\n"); + return LOS_NOK; + } + + /* 创建可读写文件"user/test/file.txt" */ + fd = open(fileName, O_RDWR | O_CREAT, 0777); + if (fd < 0) { + printf("open file failed.\n"); + return LOS_NOK; + } + + /* 将writeBuf中的内容写入文件 */ + len = write(fd, writeBuf, strlen(writeBuf)); + if (len != strlen(writeBuf)) { + printf("write file failed.\n"); + return LOS_NOK; + } + + /* 将文件内容刷入存储设备中 */ + ret = fsync(fd); + if (ret != LOS_OK) { + printf("fsync failed.\n"); + return LOS_NOK; + } + + /* 将读写指针偏移至文件头 */ + off = lseek(fd, 0, SEEK_SET); + if (off != 0) { + printf("lseek failed.\n"); + return LOS_NOK; + } + + /* 将文件内容读出至readBuf中,读取长度为readBuf大小 */ + len = read(fd, readBuf, sizeof(readBuf)); + if (len != strlen(writeBuf)) { + printf("read file failed.\n"); + return LOS_NOK; + } + printf("%s\n", readBuf); + + /* 关闭文件 */ + ret = close(fd); + if (ret != LOS_OK) { + printf("close failed.\n"); + return LOS_NOK; + } + + /* 删除文件"user/test/file.txt" */ + ret = unlink(fileName); + if (ret != LOS_OK) { + printf("unlink failed.\n"); + return LOS_NOK; + } + + /* 删除目录“user/test” */ + ret = rmdir(dirName); + if (ret != LOS_OK) { + printf("rmdir failed.\n"); + return LOS_NOK; + } + + return LOS_OK; + } + ``` + + +#### 结果验证 + +编译运行得到的结果为: + + +``` +Hello OpenHarmony! +``` +## LittleFS + + +### 基本概念 + +LittleFS是一个小型的Flash文件系统,它结合日志结构(log-structured)文件系统和COW(copy-on-write)文件系统的思想,以日志结构存储元数据,以COW结构存储数据。这种特殊的存储方式,使LittleFS具有强大的掉电恢复能力(power-loss resilience)。分配COW数据块时LittleFS采用了名为统计损耗均衡的动态损耗均衡算法,使Flash设备的寿命得到有效保障。同时LittleFS针对资源紧缺的小型设备进行设计,具有极其有限的ROM和RAM占用,并且所有RAM的使用都通过一个可配置的固定大小缓冲区进行分配,不会随文件系统的扩大占据更多的系统资源。 + +当在一个资源非常紧缺的小型设备上,寻找一个具有掉电恢复能力并支持损耗均衡的Flash文件系统时,LittleFS是一个比较好的选择。 + + +### 开发指导 + +移植LittleFS到新硬件设备上,需要申明lfs_config: + + +``` +const struct lfs_config cfg = { + // block device operations + .read = user_provided_block_device_read, + .prog = user_provided_block_device_prog, + .erase = user_provided_block_device_erase, + .sync = user_provided_block_device_sync, + + // block device configuration + .read_size = 16, + .prog_size = 16, + .block_size = 4096, + .block_count = 128, + .cache_size = 16, + .lookahead_size = 16, + .block_cycles = 500, +}; +``` + +其中.read,.prog,.erase,.sync分别对应该硬件平台上的底层的读写\擦除\同步等接口。 + +read_size 每次读取的字节数,可以比物理读单元大以改善性能,这个数值决定了读缓存的大小,但值太大会带来更多的内存消耗。 + +prog_size 每次写入的字节数,可以比物理写单元大以改善性能,这个数值决定了写缓存的大小,必须是read_size的整数倍,但值太大会带来更多的内存消耗。 + +block_size 每个擦除块的字节数,可以比物理擦除单元大,但此数值应尽可能小因为每个文件至少会占用一个块。必须是prog_size的整数倍。 + +block_count 可以被擦除的块数量,这取决于块设备的容量及擦除块的大小。 + + +### 示例代码 + + 代码实现如下: + +``` +#include "lfs.h" +#include "stdio.h" +lfs_t lfs; +lfs_file_t file; +const struct lfs_config cfg = { + // block device operations + .read = user_provided_block_device_read, + .prog = user_provided_block_device_prog, + .erase = user_provided_block_device_erase, + .sync = user_provided_block_device_sync, + // block device configuration + .read_size = 16, + .prog_size = 16, + .block_size = 4096, + .block_count = 128, + .cache_size = 16, + .lookahead_size = 16, + .block_cycles = 500, +}; +int main(void) { + // mount the filesystem + int err = lfs_mount(&lfs, &cfg); + // reformat if we can't mount the filesystem + // this should only happen on the first boot + if (err) { + lfs_format(&lfs, &cfg); + lfs_mount(&lfs, &cfg); + } + // read current count + uint32_t boot_count = 0; + lfs_file_open(&lfs, &file, "boot_count", LFS_O_RDWR | LFS_O_CREAT); + lfs_file_read(&lfs, &file, &boot_count, sizeof(boot_count)); + // update boot count + boot_count += 1; + lfs_file_rewind(&lfs, &file); + lfs_file_write(&lfs, &file, &boot_count, sizeof(boot_count)); + // remember the storage is not updated until the file is closed successfully + lfs_file_close(&lfs, &file); + // release any resources we were using + lfs_unmount(&lfs); + // print the boot count + printf("boot_count: %d\n", boot_count); +} +``` + + + **结果验证** + +首次编译运行得到的结果为: + + +``` +Say hello 1 times. +``` \ No newline at end of file diff --git a/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md b/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md index 625990100c08618f1beef05b71bf496e67f2d42a..fab4a6266dabae8db627379f1ffb8073961e6d37 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md +++ b/zh-cn/device-dev/kernel/kernel-mini-memory-debug.md @@ -4,8 +4,336 @@ 内存调测方法旨在辅助定位动态内存相关问题,提供了基础的动态内存池信息统计手段,向用户呈现内存池水线、碎片率等信息;提供了内存泄漏检测手段,方便用户准确定位存在内存泄漏的代码行,也可以辅助分析系统各个模块内存的使用情况;提供了踩内存检测手段,可以辅助定位越界踩内存的场景。 -- **[内存信息统计](kernel-mini-memory-debug-mes.md)** +## 内存信息统计 -- **[内存泄漏检测](kernel-mini-memory-debug-det.md)** -- **[踩内存检测](kernel-mini-memory-debug-cet.md)** \ No newline at end of file +### 基础概念 + +内存信息包括内存池大小、内存使用量、剩余内存大小、最大空闲内存、内存水线、内存节点数统计、碎片率等。 + +- 内存水线:即内存池的最大使用量,每次申请和释放时,都会更新水线值,实际业务可根据该值,优化内存池大小; + +- 碎片率:衡量内存池的碎片化程度,碎片率高表现为内存池剩余内存很多,但是最大空闲内存块很小,可以用公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)来度量; + +- 其他参数:通过调用接口(详见[内存管理](../kernel/kernel-mini-basic-memory-basic.md)章节接口说明),扫描内存池的节点信息,统计出相关信息。 + + +### 功能配置 + +LOSCFG_MEM_WATERLINE:开关宏,默认打开;若关闭这个功能,在target_config.h中将这个宏定义为0。如需获取内存水线,需要打开该配置。 + + +### 开发指导 + + +#### 开发流程 + +关键结构体介绍: + + +``` +typedef struct { + UINT32 totalUsedSize; // 内存池的内存使用量 + UINT32 totalFreeSize; // 内存池的剩余内存大小 + UINT32 maxFreeNodeSize; // 内存池的最大空闲内存块大小 + UINT32 usedNodeNum; // 内存池的非空闲内存块个数 + UINT32 freeNodeNum; // 内存池的空闲内存块个数 +#if (LOSCFG_MEM_WATERLINE == 1) // 默认打开,如需关闭,在target_config.h中将该宏设置为0 + UINT32 usageWaterLine; // 内存池的水线值 +#endif +} LOS_MEM_POOL_STATUS; +``` + +- 内存水线获取:调用LOS_MemInfoGet接口,第1个参数是内存池首地址,第2个参数是LOS_MEM_POOL_STATUS类型的句柄,其中字段usageWaterLine即水线值。 + +- 内存碎片率计算:同样调用LOS_MemInfoGet接口,可以获取内存池的剩余内存大小和最大空闲内存块大小,然后根据公式(fragment=100-100\*最大空闲内存块大小/剩余内存大小)得出此时的动态内存池碎片率。 + + +#### 编程实例 + +本实例实现如下功能: + +1.创建一个监控任务,用于获取内存池的信息; + +2.调用LOS_MemInfoGet接口,获取内存池的基础信息; + +3.利用公式算出使用率及碎片率。 + + +#### 示例代码 + + 代码实现如下: + +``` +#include +#include +#include "los_task.h" +#include "los_memory.h" +#include "los_config.h" + + +void MemInfoTaskFunc(void) +{ + LOS_MEM_POOL_STATUS poolStatus = {0}; + + /* pool为要统计信息的内存地址,此处以OS_SYS_MEM_ADDR为例 */ + void *pool = OS_SYS_MEM_ADDR; + LOS_MemInfoGet(pool, &poolStatus); + /* 算出内存池当前的碎片率百分比 */ + unsigned char fragment = 100 - poolStatus.maxFreeNodeSize * 100 / poolStatus.totalFreeSize; + /* 算出内存池当前的使用率百分比 */ + unsigned char usage = LOS_MemTotalUsedGet(pool) * 100 / LOS_MemPoolSizeGet(pool); + printf("usage = %d, fragment = %d, maxFreeSize = %d, totalFreeSize = %d, waterLine = %d\n", usage, fragment, poolStatus.maxFreeNodeSize, + poolStatus.totalFreeSize, poolStatus.usageWaterLine); +} + +int MemTest(void) +{ + unsigned int ret; + unsigned int taskID; + TSK_INIT_PARAM_S taskStatus = {0}; + taskStatus.pfnTaskEntry = (TSK_ENTRY_FUNC)MemInfoTaskFunc; + taskStatus.uwStackSize = 0x1000; + taskStatus.pcName = "memInfo"; + taskStatus.usTaskPrio = 10; + ret = LOS_TaskCreate(&taskID, &taskStatus); + if (ret != LOS_OK) { + printf("task create failed\n"); + return -1; + } + return 0; +} +``` + + +#### 结果验证 + +编译运行输出的结果如下: + + +``` +usage = 22, fragment = 3, maxFreeSize = 49056, totalFreeSize = 50132, waterLine = 1414 +``` +## 内存泄漏检测 + + +### 基础概念 + +内存泄漏检测机制作为内核的可选功能,用于辅助定位动态内存泄漏问题。开启该功能,动态内存机制会自动记录申请内存时的函数调用关系(下文简称LR)。如果出现泄漏,就可以利用这些记录的信息,找到内存申请的地方,方便进一步确认。 + + +### 功能配置 + +1. LOSCFG_MEM_LEAKCHECK:开关宏,默认关闭;若打开这个功能,在target_config.h中将这个宏定义为1。 + +2. LOSCFG_MEM_RECORD_LR_CNT:记录的LR层数,默认3层;每层LR消耗sizeof(void \*)字节数的内存。 + +3. LOSCFG_MEM_OMIT_LR_CNT:忽略的LR层数,默认4层,即从调用LOS_MemAlloc的函数开始记录,可根据实际情况调整。为啥需要这个配置?有3点原因如下: + - LOS_MemAlloc接口内部也有函数调用; + - 外部可能对LOS_MemAlloc接口有封装; + - LOSCFG_MEM_RECORD_LR_CNT 配置的LR层数有限; + +正确配置这个宏,将无效的LR层数忽略,就可以记录有效的LR层数,节省内存消耗。 + + +### 开发指导 + + +#### 开发流程 + +该调测功能可以分析关键的代码逻辑中是否存在内存泄漏。开启这个功能,每次申请内存时,会记录LR信息。在需要检测的代码段前后,调用LOS_MemUsedNodeShow接口,每次都会打印指定内存池已使用的全部节点信息,对比前后两次的节点信息,新增的节点信息就是疑似泄漏的内存节点。通过LR,可以找到具体申请的代码位置,进一步确认是否泄漏。 + +调用LOS_MemUsedNodeShow接口输出的节点信息格式如下:每1行为一个节点信息;第1列为节点地址,可以根据这个地址,使用GDB等手段查看节点完整信息;第2列为节点的大小,等于节点头大小+数据域大小;第3~5列为函数调用关系LR地址,可以根据这个值,结合汇编文件,查看该节点具体申请的位置。 + + +``` +node size LR[0] LR[1] LR[2] +0x10017320: 0x528 0x9b004eba 0x9b004f60 0x9b005002 +0x10017848: 0xe0 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x10017928: 0x50 0x9b008ed0 0x9b068902 0x9b0687c4 +0x10017978: 0x24 0x9b008ed0 0x9b068924 0x9b0687c4 +0x1001799c: 0x30 0x9b02c24e 0x9b02c246 0x9b008ef0 +0x100179cc: 0x5c 0x9b02c24e 0x9b02c246 0x9b008ef0 +``` + +> ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:** +> 开启内存检测会影响内存申请的性能,且每个内存节点都会记录LR地址,内存开销也加大。 + + +#### 编程实例 + +本实例实现如下功能:构建内存泄漏代码段。 + +1. 调用LOS_MemUsedNodeShow接口,输出全部节点信息打印; + +2. 申请内存,但没有释放,模拟内存泄漏; + +3. 再次调用LOS_MemUsedNodeShow接口,输出全部节点信息打印; + +4. 将两次log进行对比,得出泄漏的节点信息; + +5. 通过LR地址,找出泄漏的代码位置; + + +#### 示例代码 + +代码实现如下: + + +``` +#include +#include +#include "los_memory.h" +#include "los_config.h" + +void MemLeakTest(void) +{ + LOS_MemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); + void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); + void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); + LOS_MemUsedNodeShow(LOSCFG_SYS_HEAP_ADDR); +} +``` + + +#### 结果验证 + +编译运行输出log如下: + + +``` +node size LR[0] LR[1] LR[2] +0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc +0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc +0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e +0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a +0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 + +node size LR[0] LR[1] LR[2] +0x20001b04: 0x24 0x08001a10 0x080035ce 0x080028fc +0x20002058: 0x40 0x08002fe8 0x08003626 0x080028fc +0x200022ac: 0x40 0x08000e0c 0x08000e56 0x0800359e +0x20002594: 0x120 0x08000e0c 0x08000e56 0x08000c8a +0x20002aac: 0x56 0x08000e0c 0x08000e56 0x08004220 +0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 +0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +``` + +对比两次log,差异如下,这些内存节点就是疑似泄漏的内存块: + + +``` +0x20003ac4: 0x1d 0x08001458 0x080014e0 0x080041e6 +0x20003ae0: 0x1d 0x080041ee 0x08000cc2 0x00000000 +``` + +部分汇编文件如下: + + +``` + MemLeakTest: + 0x80041d4: 0xb510 PUSH {R4, LR} + 0x80041d6: 0x4ca8 LDR.N R4, [PC, #0x2a0] ; g_memStart + 0x80041d8: 0x0020 MOVS R0, R4 + 0x80041da: 0xf7fd 0xf93e BL LOS_MemUsedNodeShow ; 0x800145a + 0x80041de: 0x2108 MOVS R1, #8 + 0x80041e0: 0x0020 MOVS R0, R4 + 0x80041e2: 0xf7fd 0xfbd9 BL LOS_MemAlloc ; 0x8001998 + 0x80041e6: 0x2108 MOVS R1, #8 + 0x80041e8: 0x0020 MOVS R0, R4 + 0x80041ea: 0xf7fd 0xfbd5 BL LOS_MemAlloc ; 0x8001998 + 0x80041ee: 0x0020 MOVS R0, R4 + 0x80041f0: 0xf7fd 0xf933 BL LOS_MemUsedNodeShow ; 0x800145a + 0x80041f4: 0xbd10 POP {R4, PC} + 0x80041f6: 0x0000 MOVS R0, R0 +``` + +其中,通过查找0x080041ee,就可以发现该内存节点是在MemLeakTest接口里申请的且是没有释放的。 + +## 踩内存检测 + + +### 基础概念 + +踩内存检测机制作为内核的可选功能,用于检测动态内存池的完整性。通过该机制,可以及时发现内存池是否发生了踩内存问题,并给出错误信息,便于及时发现系统问题,提高问题解决效率,降低问题定位成本。 + + +### 功能配置 + +LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK:开关宏,默认关闭;若打开这个功能,在target_config.h中将这个宏定义为1。 + +1. 开启这个功能,每次申请内存,会实时检测内存池的完整性。 + +2. 如果不开启该功能,也可以调用LOS_MemIntegrityCheck接口检测,但是每次申请内存时,不会实时检测内存完整性,而且由于节点头没有魔鬼数字(开启时才有,省内存),检测的准确性也会相应降低,但对于系统的性能没有影响,故根据实际情况开关该功能。 + +由于该功能只会检测出哪个内存节点被破坏了,并给出前节点信息(因为内存分布是连续的,当前节点最有可能被前节点破坏)。如果要进一步确认前节点在哪里申请的,需开启内存泄漏检测功能,通过LR记录,辅助定位。 + +> ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:** +> 开启该功能,节点头多了魔鬼数字字段,会增大节点头大小。由于实时检测完整性,故性能影响较大;若性能敏感的场景,可以不开启该功能,使用LOS_MemIntegrityCheck接口检测。 + + +### 开发指导 + + +#### 开发流程 + +通过调用LOS_MemIntegrityCheck接口检测内存池是否发生了踩内存,如果没有踩内存问题,那么接口返回0且没有log输出;如果存在踩内存问题,那么会输出相关log,详见下文编程实例的结果输出。 + + +#### 编程实例 + +本实例实现如下功能: + +1. 申请两个物理上连续的内存块; + +2. 通过memset构造越界访问,踩到下个节点的头4个字节; + +3. 调用LOS_MemIntegrityCheck检测是否发生踩内存。 + + +#### 示例代码 + +代码实现如下: + + +``` +#include +#include +#include "los_memory.h" +#include "los_config.h" + +void MemIntegrityTest(void) +{ + /* 申请两个物理连续的内存块 */ + void *ptr1 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); + void *ptr2 = LOS_MemAlloc(LOSCFG_SYS_HEAP_ADDR, 8); + /* 第一个节点内存块大小是8字节,那么12字节的清零,会踩到第二个内存节点的节点头,构造踩内存场景 */ + memset(ptr1, 0, 8 + 4); + LOS_MemIntegrityCheck(LOSCFG_SYS_HEAP_ADDR); +} +``` + + +#### 结果验证 + +编译运行输出log如下: + + +``` +[ERR][OsMemMagicCheckPrint], 2028, memory check error! +memory used but magic num wrong, magic num = 0x00000000 /* 提示信息,检测到哪个字段被破坏了,用例构造了将下个节点的头4个字节清零,即魔鬼数字字段 */ + + broken node head: 0x20003af0 0x00000000 0x80000020, prev node head: 0x20002ad4 0xabcddcba 0x80000020 +/* 被破坏节点和其前节点关键字段信息,分别为其前节点地址、节点的魔鬼数字、节点的sizeAndFlag;可以看出被破坏节点的魔鬼数字字段被清零,符合用例场景 */ + + broken node head LR info: /* 节点的LR信息需要开启内存检测功能才有有效输出 */ + LR[0]:0x0800414e + LR[1]:0x08000cc2 + LR[2]:0x00000000 + + pre node head LR info: /* 通过LR信息,可以在汇编文件中查找前节点是哪里申请,然后排查其使用的准确性 */ + LR[0]:0x08004144 + LR[1]:0x08000cc2 + LR[2]:0x00000000 +[ERR]Memory interity check error, cur node: 0x20003b10, pre node: 0x20003af0 /* 被破坏节点和其前节点的地址 */ +``` diff --git a/zh-cn/device-dev/kernel/kernel-small-apx-dll.md b/zh-cn/device-dev/kernel/kernel-small-apx-dll.md index f96563857060e2ef16b2397f22eb760bac77bbee..d13c006214da35581213e47da24e583cb16b861a 100644 --- a/zh-cn/device-dev/kernel/kernel-small-apx-dll.md +++ b/zh-cn/device-dev/kernel/kernel-small-apx-dll.md @@ -18,7 +18,7 @@ | 增加链表 | - LOS_ListAddList:将指定链表的头端插入到双向链表头端
- LOS_ListHeadInsertList:将指定链表的头端插入到双向链表头端
- LOS_ListTailInsertList:将指定链表的尾端插入到双向链表头端 | | 删除节点 | - LOS_ListDelete:将指定节点从链表中删除
- LOS_ListDelInit:将指定节点从链表中删除,并使用该节点初始化链表 | | 判断双向链表 | - LOS_ListEmpty:判断链表是否为空
- LOS_DL_LIST_IS_END:判断指定链表节点是否为链表尾端:LOS_DL_LIST_IS_ON_QUEUE:判断链表节点是否在双向链表里 | -| 获取结构体信息 | - LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量
- LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。
- LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量
- LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。 | +| 获取结构体信息 | - LOS_OFF_SET_OF:获取指定结构体内的成员相对于结构体起始地址的偏移量
- LOS_DL_LIST_ENTRY:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称
- LOS_ListPeekHeadType:获取双向链表中第一个链表节点所在的结构体地址,接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListRemoveHeadType:获取双向链表中第一个链表节点所在的结构体地址,并把第一个链表节点从链表中删除。接口的第一个入参表示的是链表中的头节点,第二个入参是要获取的结构体名称,第三个入参是链表在该结构体中的名称。如果链表为空,返回NULL。
- LOS_ListNextType:获取双向链表中指定链表节点的下一个节点所在的结构体地址。接口的第一个入参表示的是链表中的头节点,第二个入参是指定的链表节点,第三个入参是要获取的结构体名称,第四个入参是链表在该结构体中的名称。如果链表节点下一个为链表头结点为空,返回NULL。| | 遍历双向链表 | - LOS_DL_LIST_FOR_EACH:遍历双向链表
- LOS_DL_LIST_FOR_EACH_SAFE:遍历双向链表,并存储当前节点的后继节点用于安全校验 | | 遍历包含双向链表的结构体 | - LOS_DL_LIST_FOR_EACH_ENTRY:遍历指定双向链表,获取包含该链表节点的结构体地址
- LOS_DL_LIST_FOR_EACH_ENTRY_SAFE:遍历指定双向链表,获取包含该链表节点的结构体地址,并存储包含当前节点的后继节点的结构体地址 | diff --git a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md index a7090aa8cd25de4324897faaa8a89fea9bf36368..a5b14d4169aef58347e9fcc10cb4d894439a66bf 100644 --- a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md +++ b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support-nfs.md @@ -82,7 +82,7 @@ OpenHarmony LiteOS-A内核的NFS文件系统指的是NFS的客户端,NFS客户 [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 --- -3. packets transmitted, 4 received, 0 loss + packets transmitted, 4 received, 0 loss 客户端NFS初始化,运行命令: @@ -124,7 +124,7 @@ OpenHarmony LiteOS-A内核的NFS文件系统指的是NFS的客户端,NFS客户 > > 至此,NFS客户端设置完毕。NFS文件系统已成功挂载。 -4. 利用NFS共享文件 +3. 利用NFS共享文件 在NFS服务器下新建目录dir,并保存。在OpenHarmony内核下运行ls命令: diff --git a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md index 5f2ea549f7be468f4780dd7c4db0c96a8690b4e0..427cc10737c384630f2d0235131c5e7b7c8e5115 100644 --- a/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md +++ b/zh-cn/device-dev/kernel/kernel-small-bundles-fs-support.md @@ -1,13 +1,424 @@ # 支持的文件系统 +## FAT +### 基本概念 -- **[FAT](kernel-small-bundles-fs-support-fat.md)** +FAT文件系统是File Allocation Table(文件配置表)的简称,主要包括DBR区、FAT区、DATA区三个区域。其中,FAT区各个表项记录存储设备中对应簇的信息,包括簇是否被使用、文件下一个簇的编号、是否文件结尾等。FAT文件系统有FAT12、FAT16、FAT32等多种格式,其中,12、16、32表示对应格式中FAT表项的比特数,它们同时也限制了文件系统中的最大文件大小。FAT文件系统支持多种介质,特别在可移动存储介质(U盘、SD卡、移动硬盘等)上广泛使用,使嵌入式设备和Windows、Linux等桌面系统保持很好的兼容性,方便用户管理操作文件。 -- **[JFFS2](kernel-small-bundles-fs-support-jffs2.md)** +OpenHarmony内核支持FAT12、FAT16与FAT32三种格式的FAT文件系统,具有代码量小、资源占用小、可裁切、支持多种物理介质等特性,并且与Windows、Linux等系统保持兼容,支持多设备、多分区识别等功能。OpenHarmony内核支持硬盘多分区,可以在主分区以及逻辑分区上创建FAT文件系统。 -- **[NFS](kernel-small-bundles-fs-support-nfs.md)** -- **[Ramfs](kernel-small-bundles-fs-support-ramfs.md)** +### 运行机制 -- **[Procfs](kernel-small-bundles-fs-support-procfs.md)** \ No newline at end of file +FAT文件系统设计与物理布局的相关文档在互联网上非常丰富,请开发者自行搜索查看。 + +OpenHarmony LiteOS-A内核通过Bcache提升FAT文件系统性能,Bcache是block cache的简称。当发生读写时,Bcache会缓存读写扇区附近的扇区,以减少I/O次数,提高性能。Bcache的基本缓存单位为block,每个block大小一致(默认有28个block,每个block缓存64个扇区的数据)。当Bcache脏块率(脏扇区数/总扇区数)达到阈值时,会触发写回;如果脏块率未达到阈值,则不会将缓存数据写回磁盘。如果需要保证数据写回,开发者应当调用sync和fsync触发写回。FAT文件系统的部分接口也会触发写回操作(如close、umount等),但开发者不应当基于这些接口触发写回。 + + +### 开发指导 + + + **开发流程** + +基本使用流程为挂载→操作→卸载。 + +SD卡或MMC的设备名为mmcblk[x]p[y],文件系统类型为“vfat”。 + +示例: + + +``` +mount("/dev/mmcblk0p0", "/mnt", "vfat", 0, NULL); +``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> - FAT文件系统中,单个文件不能大于4 GiB。 +> +> - 当有两个SD卡插槽时,卡0和卡1不固定,先插上的为卡0,后插上的为卡1。 +> +> - 当多分区功能打开,存在多分区的情况下,卡0注册的设备节点/dev/mmcblk0(主设备)和/dev/mmcblk0p0(次设备)是同一个设备,禁止对主设备进行操作。 +> +> - 为避免SD卡使用异常或内存泄漏,SD卡使用过程中拔卡,用户必须先关闭正处于打开状态的文件和目录,并且卸载挂载节点。 +> +> - 在format操作之前,需要首先umount挂载点。 +> +> - 当Bcache功能生效时,需要注意: +> - 当mount函数的入参为MS_NOSYNC时,FAT不会主动将cache的内容写回存储器件。FAT的如下接口(open、close、 unlink、rename、mkdir、rmdir、truncate)不会自动进行sync操作,速度可以提升,但是需要上层主动调用sync来进行数据同步,否则可能会数据丢失。 +> +> - Bcache有定时写回功能。在menuconfig中开启LOSCFG_FS_FAT_CACHE_SYNC_THREAD选项,打开后系统会创建一个任务定时写回Bcache中的数据,默认每隔5秒检查Bcache中脏数据块比例,超过80%时进行sync操作,将Bcache中的脏数据全部写回磁盘。任务优先级、刷新时间间隔以及脏数据块比例的阈值可分别通过接口LOS_SetSyncThreadPrio、 LOS_SetSyncThreadInterval和LOS_SetDirtyRatioThreshold设置。 +> - 当前cache的默认大小为28个块,每个块64个扇区。 + +## JFFS2 + + +### 基本概念 + +JFFS2是Journalling Flash File System Version 2(日志文件系统)的缩写,是针对MTD设备的日志型文件系统。 + +OpenHarmony内核的JFFS2主要应用于NOR FLASH闪存,其特点是:可读写、支持数据压缩、提供了崩溃/掉电安全保护、提供“写平衡”支持等。闪存与磁盘介质有许多差异,直接将磁盘文件系统运行在闪存设备上,会导致性能和安全问题。为解决这一问题,需要实现一个特别针对闪存的文件系统,JFFS2就是这样一种文件系统。 + + +### 运行机制 + +关于JFFS2文件系统的在存储设备上的实际物理布局,及文件系统本身的规格说明,请参考JFFS2的[官方规格说明文档](https://sourceware.org/jffs2/)。 + +这里仅列举几个对开发者和使用者会有一定影响的JFFS2的重要机制/特征: + +1. Mount机制及速度问题:按照JFFS2的设计,所有的文件会按照一定的规则,切分成大小不等的节点,依次存储到flash设备上。在mount流程中,需要获取到所有的这些节点信息并缓存到内存里。因此,mount速度和flash设备的大小和文件数量的多少成线性比例关系。这是JFFS2的原生设计问题,对于mount速度非常介意的用户,可以在内核编译时开启“Enable JFFS2 SUMMARY”选项,可以极大提升mount的速度。这个选项的原理是将mount需要的信息提前存储到flash上,在mount时读取并解析这块内容,使得mount的速度变得相对恒定。这个实际是空间换时间的做法,会消耗8%左右的额外空间。 + +2. 写平衡的支持:由于flash设备的物理属性,读写都只能基于某个特定大小的“块”进行,为了防止某些特定的块磨损过于严重,在JFFS2中需要对写入的块进行“平衡”的管理,保证所有的块的写入次数都是相对平均的,进而保证flash设备的整体寿命。 + +3. GC(garbage collection)机制:在JFFS2里发生删除动作,实际的物理空间并不会立即释放,而是由独立的GC线程来做空间整理和搬移等GC动作,和所有的GC机制一样,在JFFS2里的GC会对瞬时的读写性能有一定影响。另外,为了有空间能被用来做空间整理,JFFS2会对每个分区预留3块左右的空间,这个空间是用户不可见的。 + +4. 压缩机制:当前使用的JFFS2,底层会自动的在每次读/写时进行解压/压缩动作,实际IO的大小和用户请求读写的大小并不会一样。特别在写入时,不能通过写入大小来和flash剩余空间的大小来预估写入一定会成功或者失败。 + +5. 硬链接机制:JFFS2支持硬链接,底层实际占用的物理空间是一份,对于同一个文件的多个硬连接,并不会增加空间的占用;反之,只有当删除了所有的硬链接时,实际物理空间才会被释放。 + + +### 开发指导 + +对于基于JFFS2和nor flash的开发,总体而言,与其他文件系统非常相似,因为都有VFS层来屏蔽了具体文件系统的差异,对外接口体现也都是标准的POSIX接口。 + +对于整个裸nor flash设备而言,没有集中的地方来管理和记录分区的信息。因此,需要通过其他的配置方式来传递这部分信息(当前使用的方式是在烧写镜像的时候,使用bootargs参数配置的),然后在代码中调用相应的接口来添加分区,再进行挂载动作。 + +**制作JFFS2文件系统镜像** + +使用mkfs.jffs2工具,制作镜像默认命令如下。页大小默认为4KiB,eraseblock大小默认64KiB。若实际参数与下面不同时,修改相应参数。 + + +``` +./mkfs.jffs2 -d rootfs/ -o rootfs.jffs2 +``` + + **表1** 指令含义表(更详细的介绍可以通过mkfs.jffs2 --help来查看) + +| 指令 | 含义 | +| -------- | -------- | +| -s | 页大小,不指定默认为4KiB | +| -e | eraseblock大小,不指定默认为64KiB | +| -p | 镜像大小。在镜像文件后面,用0xFF填充至指定大小,不指定则用0xFF填充至eraseblock对齐。 | +| -d | 要制作成文件系统镜像的源目录 | +| -o | 要制成的镜像名称 | + +**挂载JFFS2分区** + +调用int mount(const char \*source, const char \*target, const char \*filesystemtype, unsigned long mountflags, const void \*data)函数实现设备节点和挂载点的挂载。 + +该函数有五个参数,第一个参数const char \*source,表示设备节点,第二个参数const char \*target表示挂载点。第三个参数 const char \*filesystemtype,表示文件系统类型。 + +最后两个参数unsigned long mountflags和const void \*data表示挂载标志和数据,默认为0和NULL;这一操作也可以在Shell中使用mount命令实现,最后两个参数不需要用户给出。 + +运行命令: + + +``` +OHOS # mount /dev/spinorblk1 /jffs1 jffs2 +``` + +将从串口得到如下回应信息,表明挂载成功。 + + +``` +OHOS # mount /dev/spinorblk1 /jffs1 jffs2 +mount OK +``` + +挂载成功后,用户就能对norflash进行读写操作。 + +**卸载JFFS2分区** + +调用int umount(const char \*target)函数卸载分区,只需要正确给出挂载点即可。 + +运行命令: + + +``` +OHOS # umount /jffs1 +``` + +将从串口得到如下回应信息,表明卸载成功。 + + +``` +OHOS # umount /jffs1 +umount ok +``` +## NFS + + +### 基本概念 + +NFS是Network File System(网络文件系统)的缩写。它最大的功能是可以通过网络,让不同的机器、不同的操作系统彼此分享其他用户的文件。因此,用户可以简单地将它看做是一个文件系统服务,在一定程度上相当于Windows环境下的共享文件夹。 + + +### 运行机制 + +OpenHarmony LiteOS-A内核的NFS文件系统指的是NFS的客户端,NFS客户端能够将远程的NFS服务端分享的目录挂载到本地的机器中,运行程序和共享文件,但不占用当前系统的存储空间,在本地端的机器看起来,远程服务端的目录就好像是自己的一个磁盘一样。 + + +### 开发指导 + +1. 搭建NFS服务器 + + 这里以Ubuntu操作系统为例,说明服务器端设置步骤。 + + - 安装NFS服务器软件。 + + 设置好Ubuntu系统的下载源,保证网络连接好的情况下执行: + + + ``` + sudo apt-get install nfs-kernel-server + ``` + + - 创建用于挂载的目录并设置完全权限 + + + ``` + mkdir -p /home/sqbin/nfs + sudo chmod 777 /home/sqbin/nfs + ``` + + - 设置和启动NFS server。 + + 修改NFS配置文件/etc/exports,添加如下一行: + + + ``` + /home/sqbin/nfs *(rw,no_root_squash,async) + ``` + + 其中/home/sqbin/nfs是NFS共享的根目录。 + + 执行以下命令启动NFS server: + + + ``` + sudo /etc/init.d/nfs-kernel-server start + ``` + + 执行以下命令重启NFS server: + + + ``` + sudo /etc/init.d/nfs-kernel-server restart + ``` + +2. 设置单板为NFS客户端 + + 本指导中的NFS客户端指运行OpenHarmony内核的设备。 + + - 硬件连接设置。 + + OpenHarmony内核设备连接到NFS服务器的网络。设置两者IP,使其处于同一网段。比如,设置NFS服务器的IP为10.67.212.178/24,设置OpenHarmony内核设备IP为 + 10.67.212.3/24,注意:此IP为内网私有IP地址,用户使用时有差异,以用户实际IP为准。 + + OpenHarmony内核设备上的IP信息可通过ifconfig命令查看。 + + - 启动网络,确保单板到NFS服务器之间的网络通畅。 + + 启动以太网或者其他类型网络,使用ping命令检查到服务器的网络是否通畅。 + + + ``` + 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 --- + packets transmitted, 4 received, 0 loss + + 客户端NFS初始化,运行命令: + + + ``` + OHOS # mkdir /nfs + OHOS # mount 10.67.212.178:/home/sqbin/nfs /nfs nfs 1011 1000 + ``` + + 将从串口得到如下回应信息,表明初始化NFS客户端成功。 + + + ``` + 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. + ``` + + 该命令将服务器10.67.212.178上的/home/sqbin/nfs目录挂载到OpenHarmony内核设备上的/nfs上。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > 本例默认nfs server已经配置可用,即示例中服务器10.67.212.178上的/home/sqbin/nfs已配置可访问。 + > + > mount命令的格式为: + > + > + > ``` + > mount nfs + > ``` + > + > 其中“SERVER_IP”表示服务器的IP地址;“SERVER_PATH”表示服务器端NFS共享目录路径;“CLIENT_PATH”表示设备上的NFS路径,“nfs”表示客户端要挂载的路径,可以根据自己需要替换。 + > + > 如果不想有NFS访问权限限制,可以在Linux命令行将NFS根目录权限设置成777: + > + > + > ``` + > chmod -R 777 /home/sqbin/nfs + > ``` + > + > 至此,NFS客户端设置完毕。NFS文件系统已成功挂载。 + +3. 利用NFS共享文件 + + 在NFS服务器下新建目录dir,并保存。在OpenHarmony内核下运行ls命令: + + ``` + OHOS # ls /nfs + ``` + + 则可从串口得到如下回应: + + + ``` + OHOS # ls /nfs + Directory /nfs: + drwxr-xr-x 0 u:0 g:0 dir + ``` + + 可见,刚刚在NFS服务器上新建的dir目录已同步到客户端(OpenHarmony内核系统)的/nfs目录,两者保持同步。 + + 同样地,在客户端(OpenHarmony内核系统)上创建文件和目录,在NFS服务器上也可以访问,读者可自行体验。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > 目前,NFS客户端仅支持NFS v3部分规范要求,因此对于规范支持不全的服务器,无法完全兼容。在开发测试过程中,建议使用Linux的NFS server,其对NFS支持很完善。 + +## Ramfs + + +### 基本概念 + +RAMFS是一个可动态调整大小的基于RAM的文件系统。RAMFS没有后备存储源。向RAMFS中进行的文件写操作也会分配目录项和页缓存,但是数据并不写回到任何其他存储介质上,掉电后数据丢失。 +### 运行机制 +RAMFS文件系统把所有的文件都放在 RAM 中,所以读/写操作发生在RAM中,可以用RAMFS来存储一些临时性或经常要修改的数据,例如/tmp和/var目录,这样既避免了对存储器的读写损耗,也提高了数据读写速度。 +### 开发指导 +挂载: +``` +mount(NULL, "/dev/shm", "ramfs", 0, NULL) +``` +创建目录: +``` +mkdir(pathname, mode) +``` +创建文件: +``` +open(pathname, O_NONBLOCK | O_CREAT | O_RDWR, mode) +``` +读取目录: +``` +dir = opendir(pathname) +ptr = readdir(dir) +closedir(dir) +``` +删除文件: +``` +unlink(pathname) +``` +删除目录: +``` +rmdir(pathname) +``` +去挂载: +``` +umount("/dev/shm") +``` +> ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:** +> - RAMFS只能挂载一次,一次挂载成功后,后面不能继续挂载到其他目录。 +> +> - RAMFS属于调测功能,默认配置为关闭,正式产品中不要使用该功能。 + +## Procfs + + +### 基本概念 + +procfs是进程文件系统的简称,是一种虚拟文件系统,他用文件的形式,展示进程或其他系统信息。相比调用接口的方式获取信息,以文件操作的方式获取系统信息更为方便。 + + +### 运行机制 + +OpenHarmony内核中,procfs在开机时会自动挂载到/proc目录下,仅支持内核模块创建文件节点来提供查询服务。 + + +### 开发指导 + +procfs文件的创建无法使用一般的文件系统接口,需要使用ProcMkdir接口创建目录,使用CreateProcEntry接口创建文件。文件节点功能的开发就是实现read和write函数的钩子挂到CreateProcEntry创建的文件中。当用户使用读写procfs的文件时,就会调用到钩子函数来实现自定义的功能。 + + +编程实例 + +下面我们以创建/proc/hello/world文件为例,实现如下功能: + +1.在/proc/hello/world位置创建一个文件 + +2.当读文件内容时,返回"HelloWorld!" + +3.当写文件内容时,打印写入的内容 + + +``` +#include "proc_fs.h" + +static int TestRead(struct SeqBuf *buf, void *arg) +{ + LosBufPrintf(buf, "Hello World!\n"); /* 将数据打印到buffer中,这个buffer中的数据会返回到read的结果中 */ + return 0; +} + +static int TestWrite(struct ProcFile *pf, const char *buffer, size_t buflen, loff_t *ppos) +{ + if ((buffer == NULL) || (buflen <= 0)) { + return -EINVAL; + } + + PRINTK("your input is: %s\n", buffer); /* 注意和上面的read接口区别,这是对write接口输入命令的反馈,这个打印只会打印到控制台 */ + return buflen; +} +static const struct ProcFileOperations HELLO_WORLD_OPS = { + .read = TestRead, + .write = TestWrite, +}; + +void HelloWorldInit(void) +{ + /* 创建hello目录 */ + struct ProcDirEntry *dir = ProcMkdir("hello", NULL); + if (dir == NULL) { + PRINT_ERR("create dir failed!\n"); + return; + } + + /* 创建world文件 */ + struct ProcDirEntry *entry = CreateProcEntry("world", 0, dir); + if (entry == NULL) { + PRINT_ERR("create entry failed!\n"); + return; + } + + /* 将自定义的read和write钩子挂到文件中 */ + entry->procFileOps = &HELLO_WORLD_OPS; +} +``` + +**结果验证** + +启动后在shell输入如下命令 + + +``` +OHOS # cat /proc/hello/world +OHOS # Hello World! +OHOS # echo "yo" > /proc/hello/world +OHOS # your input is: yo +``` diff --git a/zh-cn/device-dev/kernel/kernel-small-debug-user.md b/zh-cn/device-dev/kernel/kernel-small-debug-user.md index 3a57c7c48ce1b8719a750f8b53bf2a01351b8e4f..cb61d4fe832b15e30df9d1f19963be0a811eb68d 100644 --- a/zh-cn/device-dev/kernel/kernel-small-debug-user.md +++ b/zh-cn/device-dev/kernel/kernel-small-debug-user.md @@ -1,11 +1,552 @@ # 用户态内存调测 +## 基本概念 +Debug版本的musl-libc库为用户提供内存泄漏检测、堆内存统计、踩内存分析以及backtrace功能等维测手段,可以提高用户态内存相关问题的定位效率。 -- **[基本概念](kernel-small-debug-user-concept.md)** -- **[运行机制](kernel-small-debug-user-function.md)** +采用了对malloc/free接口进行插桩,保存关键节点信息,然后程序在申请和释放内存时进行内存节点完整性校验,最后在程序结束时通过统计节点信息得到内存统计信息并根据统计信息判断内存是否泄漏的设计思想 -- **[使用指导](kernel-small-debug-user-guide.md)** +## 运行机制 + + +### 内存泄漏检查 + +对于每个进程,内存调测模块维护了128个链表(当前系统的线程最大数量为128个),每个链表的索引为线程ID。 + +申请内存时:保存关键信息到内存节点控制块,根据当前线程ID将内存节点控制块挂到对应链表; + +释放内存时:根据需要释放的内存地址匹配内存节点控制块并将该控制块删除。 + + **图1** 堆内存节点信息链表 + + ![zh-cn_image_0000001165890158](figures/zh-cn_image_0000001165890158.png) + +申请内存时,返回地址会被保存到LR寄存器中。进程运行过程中,系统会在内存节点控制块中添加疑似泄漏点对应的lr等信息。如下图所示: + + **图2** 堆内存节点信息 + + ![zh-cn_image_0000001165890518](figures/zh-cn_image_0000001165890518.png) + +其中,TID表示线程ID;PID表示进程ID;ptr表示申请的内存地址;size表示申请的内存大小;lr[n]表示函数调用栈地址,变量n可以根据具体场景的需要进行配置。 + +释放内存时,将free等接口的入参指针与node的ptr字段进行匹配,如果相同则删除该内存节点控制块信息。 + +用户通过串口或文件等方式,将各个进程内存调测信息导出,利用addr2line工具将导出的信息转换成导致内存泄漏的代码行,便可以解决内存泄露问题。 + + **图3** 泄漏点代码行定位流程 + + ![zh-cn_image_0000001165730464](figures/zh-cn_image_0000001165730464.png) + + +### 堆内存统计 + +用户态线程堆内存使用统计具有一定的实际意义,统计线程申请的堆内存占比,为用户程序的内存使用优化提供数据支持。用户态堆内存统计模块主要涉及的接口为malloc和free。如上图所示,每个进程维护128个链表,链表索引即线程ID,申请内存时系统将ptr和size信息记录在内存节点控制块中并将节点控制块挂在以线程ID为头信息的链表上,堆内存释放时根据ptr从对应的链表上移除相应的堆内存块信息;同时计算出当前线程所持有的堆内存总的使用量,并更新当前进程的堆内存使用量和堆内存使用峰值。 + + +### 内存完整性检查 + +- 使用malloc申请内存(小于等于0x1c000bytes时通过堆分配算法分配) + 用户程序申请堆内存时,在堆内存节点处添加校验值等信息,如果校验值异常,则很有可能是前一块堆内存使用越界导致的(目前无法识别校验值被野指针破坏的场景)。在内存申请、释放时校验内存节点校验值的正确性,若内存节点被破坏,校验失败时则输出tid、pid及当前被踩节点前一块堆内存申请时保存的调用栈信息,通过addr2line工具可获得具体的代码行信息,辅助用户解决问题。 + + **图4** node节点头信息添加校验值 + + ![zh-cn_image_0000001211449151](figures/zh-cn_image_0000001211449151.png) + + free堆内存时,不会立即把该内存块释放掉,而是在内存中写入魔术数字0xFE,并放到free队列中(保证在一定时间内不会再被malloc函数分配),当有野指针或use-after-free的情况对该内存进行读取的操作时,能够发现数据异常,但是对于写操作则无法判断出来。 + + **图5** free流程图 + + ![zh-cn_image_0000001165890904](figures/zh-cn_image_0000001165890904.png) + +- 使用malloc申请内存(大于0x1c000bytes时通过mmap申请) + 当malloc通过mmap申请大块内存时,在返回给用户使用的内存区间头和尾分别多申请一个页,一个页PAGE_SIZE当前为0x1000,这两个页分别通过mprotect接口设置权限为PROT_NONE(无可读可写权限),可以有效防止内存越界读写问题:越界读写数据时由于无读写权限而导致用户程序异常,根据异常调用栈信息可找到相应的代码逻辑。 + + **图6** malloc通过mmap机制申请内存的内存布局 + + ![zh-cn_image_0000001211130993](figures/zh-cn_image_0000001211130993.png) + +### 使用指导 +#### 接口说明 + + + **表1** 内存调测功能 + +| 接口名 | 描述 | +| -------- | -------- | +| mem_check_init | 初始化内存检测模块。 | +| watch_mem | 获取线程级堆内存使用信息。 | +| check_leak | 检查是否有堆内存泄漏。 | +| check_heap_integrity | 检查堆内存的完整性。 | +| backtrace | 获取调用栈地址信息。 | +| backtrace_symbols | 根据地址信息获取符号信息。 | +| print_trace | 输出函数调用栈信息。 | + + + **表2** 调用栈回溯功能 + +| 接口名 | 描述 | +| -------- | -------- | +| backtrace | 获取调用栈地址信息。 | +| backtrace_symbols | 根据地址信息获取符号信息。 | +| print_trace | 输出函数调用栈信息。 | + +### 使用说明 + + +编译OpenHarmony工程时默认编译的是debug版本,即libc库已经集成内存调测相关的接口实现,用户可以根据具体需要决定是否使能内存调测功能。 + + +堆内存调测功能提供两种方式供用户使用:接口调用及命令行参数。 + + +- 接口调用:优点是可以较精确的检查某一段代码逻辑的堆内存相关信息,缺点是需要修改用户代码。 + +- 命令行参数:优点是无需修改用户代码,缺点是无法精确的校验某一段逻辑的堆内存信息。 + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 内存调测功能使能后,进程退出时会默认进行一次堆内存泄漏和堆内存完整性检查。内存调测功能未使能时,堆内存统计、堆内存泄漏检查、堆内存完整性校验功能不会开启,调用相关调测接口无响应。 + + +- **[接口调用方式](kernel-small-debug-user-guide-use-api.md)** + +- **[命令行参数方式](kernel-small-debug-user-guide-use-cli.md)** + + + + +#### 接口调用方式 + + +##### 示例代码 + +代码功能:显式调用调测模块的相关接口对用户代码进行内存校验。 + + +``` +#include +#include +#include +#include // 包含提供内存调测接口声明的头文件 + +#define MALLOC_LEAK_SIZE 0x300 + +void func(void) { + char *ptr = malloc(MALLOC_LEAK_SIZE); + memset(ptr, '3', MALLOC_LEAK_SIZE); +} + +int main() +{ + mem_check_init(NULL); // 通过串口输出内存调测信息,必须在用户程序第一次申请堆内存之前调用(一般在main函数入口调用),否则调测信息不准确。 + // mem_check_init("/storage/mem_debug.txt"); // 内存调测信息输出到/storage/mem_debug.txt文件中,如果该文件创建失败,则信息通过串口输出。 + char *ptr = malloc(MALLOC_LEAK_SIZE); + memset(ptr, '1', MALLOC_LEAK_SIZE); + + watch_mem(); // 在当前代码逻辑处查看线程级内存统计信息。 + func(); + check_heap_integrity(); // 检查堆内存节点完整性。 + check_leak(); // 在当前代码逻辑处检查堆内存是否泄漏(一般在程序退出之前校验比较准确,若在malloc和free调用逻辑之间做校验,则结果不准确)。 + return 0; +} +``` + + +##### 编译 + + +``` +$ clang -o mem_check mem_check.c -funwind-tables -rdynamic -g -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos --sysroot=/home//directory/out/hispark_taurus/ipcamera_hispark_taurus/sysroot $(clang -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos -print-file-name=libunwind.a) +``` + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> - 本编译示例基于将编译器的路径写入环境变量中,即.bashrc文件中。 +> +> - 编译用户程序及所需的lib库时,需要添加编译选项-funwind-tables,-rdynamic,-g,用于栈回溯。 +> +> - -mfloat-abi=softfp,-mcpu=cortex-a7,-mfpu=neon-vfpv4编译选项用于指定具体的芯片架构、浮点数计算优化、fpu,与具体的libc库使用的编译选项保持一致,否则链接时可能出现找不到libc库文件。 +> +> - -target arm-liteos用于指定编译器相关库文件路径。 +> +> - --sysroot=/home/<user-name>/directory/out/hispark_taurus/ipcamera_hispark_taurus/sysroot用于指定编译器库文件搜索根目录,假设OpenHarmony工程代码存放路径为/home/<user-name>/directory。其中out/hispark_taurus/ipcamera_hispark_taurus路径为在编译时,hb set命令指定的具体产品,本示例选择的是ipcamera_hispark_taurus产品。 +> +> - $(clang -mfloat-abi=softfp -mcpu=cortex-a7 -mfpu=neon-vfpv4 -target arm-liteos -print-file-name=libunwind.a)用于指定相应的unwind库的路径。 + + +##### 调测信息 + + +``` +OHOS # ./mem_check +OHOS # +==PID:4== Heap memory statistics(bytes): // 堆内存统计信息 + [Check point]: // check点调用栈 + #00: [0x86c] -> mem_check + #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + + [TID: 18, Used: 0x320] // 18号线程堆内存占用,当前进程仅一个线程 + +==PID:4== Total heap: 0x320 byte(s), Peak: 0x320 byte(s) + +Check heap integrity ok! // 堆内存完整性检查 + +==PID:4== Detected memory leak(s): // 内存泄漏信息及调用栈 + [Check point]: + #00: [0x2da4c] -> /lib/libc.so + #01: [0x878] -> mem_check + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x850] -> mem_check + #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x810] -> mem_check + #01: [0x870] -> mem_check + #02: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + +==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). + +==PID:4== Detected memory leak(s): + [Check point]: + #00: [0x2da4c] -> /lib/libc.so + #01: [0x111ec] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x850] -> mem_check + #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x810] -> mem_check + #01: [0x870] -> mem_check + #02: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + +==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). + +Check heap integrity ok! +``` + + +##### 调用栈解析 + +提供parse_mem_info.sh脚本可以对调用栈进行解析,解析脚本存放的路径:kernel/liteos_a/tools/scripts/parse_memory/parse_mem_info.sh。利用脚本可以将相应的调测信息转换成具体的源码行号,如下命令所示,mem_debug.txt保存的是内存调测信息,elf1、elf2等文件是需要解析的elf文件。 + + +``` +$ ./parse_mem_info.sh mem_debug.txt elf1 elf2 elf3 ... +``` + +例如: + + +``` +$ ./parse_mem_info.sh mem_debug.txt mem_check +Compiler is [gcc/llvm]: llvm +Now using addr2line ... + +==PID:4== Heap memory statistics(bytes): + [Check point]: + #00: [0x86c] at /usr1/xxx/TEST_ELF/mem_check.c:22 + #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + + [TID: 18, Used: 0x320] + +==PID:4== Total heap: 0x320 byte(s), Peak: 0x320 byte(s) + +Check heap integrity ok! + +==PID:4== Detected memory leak(s): + [Check point]: + #00: [0x2da4c] -> /lib/libc.so + #01: [0x878] at /usr1/xxx/TEST_ELF/mem_check.c:28 + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x850] at /usr1/xxx/TEST_ELF/mem_check.c:17 + #01: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x810] at /usr1/xxx/TEST_ELF/mem_check.c:9 + #01: [0x870] at /usr1/xxx/TEST_ELF/mem_check.c:24 + #02: <(null)+0x24baf9dc>[0x219dc] -> /lib/libc.so + +==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). +``` + +#### 命令行参数方式 + + +对用户态进程进行内存相关的检查时,除了接口调用方式还可以通过命令行方式进行内存统计、内存泄漏或内存完整性检查。 + +``` +--mwatch:初始化内存调测功能,注册信号。内存调测信息将从串口输出; +--mrecord :初始化内存调测功能,注册信号。内存调测信息将保存至f_path文件,若f_path创建失败,则内存调测信息将从串口输出 +``` + + +在待调测的进程未退出时可使用信号机制获取对应信息: + +``` +kill -35 # 查看线程级堆内存占用 +kill -36 # 检查是否存在堆内存泄漏 +kill -37 # 检查堆内存头节点是否完整 +``` + + +##### 示例代码 + +代码功能:构造内存问题利用命令行方式进行内存调测。 + + +``` +#include +#include +#include + +#define MALLOC_LEAK_SIZE 0x300 + +void func(void) { + char *ptr = malloc(MALLOC_LEAK_SIZE); + memset(ptr, '3', MALLOC_LEAK_SIZE); +} + +int main() +{ + char *ptr = malloc(MALLOC_LEAK_SIZE); + memset(ptr, '1', MALLOC_LEAK_SIZE); + func(); + while (1); +} +``` + + +##### 编译 + +参考[接口调用一节](../kernel/kernel-small-debug-user-guide-use-api.md#编译)。 + + +##### 使用mwatch参数命令 + + +``` +OHOS # ./mem_check --mwatch // 利用task命令可以查到mem_check进程的pid为4 +OHOS # +OHOS # kill -35 4 // 查看堆内存统计信息 +OHOS # +==PID:4== Heap memory statistics(bytes): + [Check point]: + #00: [0x58dfc] -> /lib/libc.so + + [TID: 18, Used: 0x640] + +==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) + +OHOS # kill -36 4 // 检查是否存在堆内存泄漏 +OHOS # +==PID:4== Detected memory leak(s): + [Check point]: + #00: [0x2da4c] -> /lib/libc.so + #01: [0x58dfc] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x724] -> mem_check + #01: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x6ec] -> mem_check + #01: [0x740] -> mem_check + #02: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so + +==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). + +OHOS # kill -37 4 // 检查堆内存头节点的完整性 +OHOS # +Check heap integrity ok! +``` + + +##### 调用栈解析 + +将调测信息保存至test.txt文件中,利用脚本进行解析,获取内存泄漏的具体行号。 + + +``` +$ ./parse_mem_info.sh test.txt mem_check +Compiler is [gcc/llvm]: llvm +Now using addr2line ... + +==PID:4== Detected memory leak(s): + [Check point]: + #00: [0x2da4c] -> /lib/libc.so + #01: [0x58dfc] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x724] at /usr1/xxx/TEST_ELF/mem_check.c:14 + #01: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x6ec] at /usr1/xxx/TEST_ELF/mem_check.c:8 + #01: [0x740] at /usr1/xxx/TEST_ELF/mem_check.c:19 + #02: <(null)+0x2555a9dc>[0x219dc] -> /lib/libc.so + +==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). +``` + + +##### 使用mrecord参数命令 + +1. 执行用户程序并指定记录内存调测信息的文件路径 + + ``` + OHOS # ./mem_check --mrecord /storage/check.txt + ``` + +2. 利用kill -35 <pid>统计内存信息,该信息将会输出到文件中,使用cat命令查看 + + ``` + OHOS # kill -35 4 + OHOS # Memory statistics information saved in /storage/pid(4)_check.txt + + OHOS # cat /storage/pid(4)_check.txt + + ==PID:4== Heap memory statistics(bytes): + [Check point]: + #00: [0x5973c] -> /lib/libc.so + + [TID: 18, Used: 0x640] + + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) + ``` + +3. 利用kill -36 <pid>校验内存完整性,该信息将会输出到文件中,使用cat命令查看 + + ``` + OHOS # kill -36 4 + OHOS # Leak check information saved in /storage/pid(4)_check.txt + + OHOS # cat /storage/pid(4)_check.txt + + ==PID:4== Heap memory statistics(bytes): + [Check point]: + #00: [0x5973c] -> /lib/libc.so + + [TID: 18, Used: 0x640] + + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) + + ==PID:4== Detected memory leak(s): + [Check point]: + #00: [0x2e38c] -> /lib/libc.so + #01: [0x5973c] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x724] -> mem_check + #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x6ec] -> mem_check + #01: [0x740] -> mem_check + #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so + + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). + ``` + +4. 利用kill -9 <pid>杀掉当前进程,进程退出后会默认校验内存完整性,该信息将会输出到文件中,使用cat命令查看 + + ``` + OHOS # kill -9 4 + OHOS # Leak check information saved in /storage/pid(4)_check.txt + + Check heap integrity ok! + + OHOS # cat /storage/pid(4)_check.txt + OHOS # + ==PID:4== Heap memory statistics(bytes): + [Check point]: + #00: [0x5973c] -> /lib/libc.so + + [TID: 18, Used: 0x640] + + ==PID:4== Total heap: 0x640 byte(s), Peak: 0x640 byte(s) + + ==PID:4== Detected memory leak(s): + [Check point]: + #00: [0x2e38c] -> /lib/libc.so + #01: [0x5973c] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x724] -> mem_check + #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x6ec] -> mem_check + #01: [0x740] -> mem_check + #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so + + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). + + ==PID:4== Detected memory leak(s): + [Check point]: + #00: [0x2e38c] -> /lib/libc.so + #01: [0x11b2c] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x724] -> mem_check + #01: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so + + [TID:18 Leak:0x320 byte(s)] Allocated from: + #00: [0x6ec] -> mem_check + #01: [0x740] -> mem_check + #02: <(null)+0x1fdd231c>[0x2231c] -> /lib/libc.so + + ==PID:4== SUMMARY: 0x640 byte(s) leaked in 2 allocation(s). + ``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 上述连续记录的信息会逐步追加到初始化时所指定的文件中,故最后cat文件时,文件中还包含历史记录的信息内容。 +## 常见问题 + + +### UAF(Use after free) + +- 申请小块内存(不大于0x1c000字节) + free之后: + + 读操作:读取free之后的内存大概率是魔术数字(0xFEFEFEFE) + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > free之后的堆内存不会立即释放进堆内存池,会先放至固定长度的队列中,并置魔术数字0xFE,队列满后会将先放至队列中的内存块释放进堆内存池 + + 写操作:无法校验。 + + +- 申请大块内存(大于0x1c000) + 堆内存由malloc通过调用mmap接口申请,free之后若仍访问该内存,则用户程序异常(该内存区间已被unmap)。 + + +### Double free + +Double free时,用户程序将会异常退出。 + + +### 堆内存节点被踩 + +- 申请小块内存(不大于0x1c000) + 堆内存节点被踩时,用户程序将会异常退出,并输出破坏被踩节点的可能的堆内存申请调用栈,对于野指针踩内存情况无法校验出来。例如用户程序mem_check中存在堆内存越界踩的情况,利用命令行方式可以获得踩内存的可能的具体位置。 + + + ``` + OHOS # ./mem_check --mwatch + OHOS # + ==PID:6== Memory integrity information: + [TID:28 allocated addr: 0x272e1ea0, size: 0x120] The possible attacker was allocated from: + #00: [0x640e8] -> /lib/libc.so + #01: [0x21d0] -> mem_check + ``` + + 可以通过调用栈解析脚本对调用栈信息进行解析。 + +- 申请大块内存(大于0x1c000) + + 堆内存由malloc通过mmap接口申请,申请得到的堆内存块前后各置一个size为PAGE_SIZE大小的区间,设置无读写权限,读写操作会触发用户程序异常。 -- **[常见问题](kernel-small-debug-user-faqs.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/kernel/kernel-small-overview.md b/zh-cn/device-dev/kernel/kernel-small-overview.md index 5e17f13da79dbf801185ace1e8fe6be946d94c2f..0762afe70e21fa2020f287b687fb091c14eee61c 100644 --- a/zh-cn/device-dev/kernel/kernel-small-overview.md +++ b/zh-cn/device-dev/kernel/kernel-small-overview.md @@ -76,7 +76,7 @@ OpenHarmony 轻量级内核是基于IoT领域轻量级物联网操作系统Huawe **网络协议** -轻量级内核网络协议基于开源LWIP构建,对LWIP的RAM占用进行优化,同时提高LWIP的传输性能。 +轻量级内核网络协议基于开源lwIP(lightweight IP)构建,对lwIP的RAM占用进行优化,同时提高lwIP的传输性能。 - 协议: IP、IPv6、 ICMP、 ND、MLD、 UDP、 TCP、IGMP、ARP、PPPoS、PPPoE diff --git a/zh-cn/device-dev/porting/Readme-CN.md b/zh-cn/device-dev/porting/Readme-CN.md index ae54c69dc6597106a1d5e8a3cc23d0235bdba6da..8d2c217aee92178f6eb562066e5bcac3465bb7f5 100644 --- a/zh-cn/device-dev/porting/Readme-CN.md +++ b/zh-cn/device-dev/porting/Readme-CN.md @@ -67,3 +67,5 @@ repo init -u https://gitee.com/openharmony-sig/manifest.git -b master -m devboar - [Combo解决方案之W800芯片移植案例](porting-w800-combo-demo.md) - 小型系统芯片移植案例 - [小型设备STM32MP1芯片移植案例](porting-stm32mp15xx-on-smallsystem.md) +- 标准系统芯片移植案例 + - [标准系统方案之瑞芯微RK3568移植案例](porting-dayu200-on_standard-demo.md) diff --git a/zh-cn/device-dev/reference/hdi-apis/_credential_info.md b/zh-cn/device-dev/reference/hdi-apis/_credential_info.md index c51b0e7909f75385a521de317311ba46527d5a2c..2d38ca382a44d3e2df74c71b2a33e3dd69ccf44e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_credential_info.md +++ b/zh-cn/device-dev/reference/hdi-apis/_credential_info.md @@ -18,7 +18,7 @@ | [credentialId](#credentialid) | 认证凭据ID。 | | [index](#index) | 用户认证框架的执行器索引。 | | [templateId](#templateid) | 认证凭据模版ID。 | -| [authType](#authtype) | 用户认证凭据类型AuthType。 | +| [authType](#authtype) | 用户认证凭据类型。 | | [executorMatcher](#executormatcher) | 执行器匹配器。 | | [executorSensorHint](#executorsensorhint) | 既定用户认证凭据类型的执行器传感器提示,用于找到对应认证方式的传感器。 | diff --git a/zh-cn/device-dev/reference/hdi-apis/_executor_info.md b/zh-cn/device-dev/reference/hdi-apis/_executor_info.md index b769eeab63507075713a6b68f36eec417577bf81..29f4d116ca581180a4a07be6ffccddbc250ee365 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_executor_info.md +++ b/zh-cn/device-dev/reference/hdi-apis/_executor_info.md @@ -18,12 +18,12 @@ | [sensorId](#sensorid) | 传感器ID,不同传感器在人脸/口令认证驱动内的唯一标识。 | | [executorType](#executortype) | 执行器类型,根据执行器支持的能力/算法类型进行分类。 | | [index](#index) | 用户认证框架的执行器索引。 | -| [executorRole](#executorrole) | 执行器角色ExecutorRole。 | +| [executorRole](#executorrole) | 执行器角色。 | | [authType](#authtype) | 用户认证凭据类型。 | | [esl](#esl) | 执行器安全等级。 | | [publicKey](#publickey) | 执行器公钥,用于校验该执行器私钥签名的信息。 | | [extraInfo](#extrainfo) | 其他相关信息,用于支持信息扩展。 | -| [info](#info) | 执行器注册信息ExecutorRegisterInfo。 | +| [info](#info) | 执行器注册信息。 | ## **详细描述** @@ -63,7 +63,7 @@ enum ExecutorSecureLevel ExecutorInfo::esl **描述:** -执行器安全等级ExecutorSecureLevel。 +执行器安全等级[ExecutorSecureLevel](_hdf_user_auth.md#executorsecurelevel)。 ### executorRole @@ -75,7 +75,7 @@ enum ExecutorRole ExecutorInfo::executorRole **描述:** -执行器角色ExecutorRole。 +执行器角色[ExecutorRole](_hdf_user_auth.md#executorrole)。 ### executorType diff --git a/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md b/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md index 85ba5209010fe793e063d5332cdc5c50a51df27c..ff242ae7d76d8749b458eac663519c3ca30fbb12 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md +++ b/zh-cn/device-dev/reference/hdi-apis/_executor_register_info.md @@ -16,10 +16,10 @@ | Public 属性 | 描述 | | -------- | -------- | | [authType](#authtype) | 用户认证凭据类型。 | -| [executorRole](#executorrole) | 执行器角色ExecutorRole。 | +| [executorRole](#executorrole) | 执行器角色。 | | [executorSensorHint](#executorsensorhint) | 既定用户认证凭据类型的执行器ID。 | | [executorMatcher](#executormatcher) | 执行器类型,根据执行器支持的认证能力进行分类。 | -| [esl](#esl) | 执行器安全等级ExecutorSecureLevel。 | +| [esl](#esl) | 执行器安全等级。 | | [publicKey](#publickey) | 执行器公钥,用于校验该执行器私钥签名的信息。 | @@ -60,7 +60,7 @@ enum ExecutorSecureLevel ExecutorRegisterInfo::esl **描述:** -执行器安全等级ExecutorSecureLevel。 +执行器安全等级[ExecutorSecureLevel](_hdf_user_auth.md#executorsecurelevel)。 ### executorSensorHint @@ -84,7 +84,7 @@ enum ExecutorRole ExecutorRegisterInfo::executorRole **描述:** -执行器角色ExecutorRole。 +执行器角色[ExecutorRole](_hdf_user_auth.md#executorrole)。 ### executorMatcher diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_controller.md b/zh-cn/device-dev/reference/hdi-apis/_input_controller.md index d70cca07b889bad1e44b843adffde4a93db1878f..58ab8b158a18cc045e658f398061460f0ef07b0b 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_controller.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_controller.md @@ -61,7 +61,7 @@ int32_t(* InputController::GetChipInfo) (uint32_t devIndex, char *chipInfo, uint INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### GetChipName @@ -87,7 +87,7 @@ int32_t(* InputController::GetChipName) (uint32_t devIndex, char *chipName, uint INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### GetDeviceType @@ -106,13 +106,13 @@ int32_t(* InputController::GetDeviceType) (uint32_t devIndex, uint32_t *deviceTy | 名称 | 描述 | | -------- | -------- | | devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 | -| deviceType | 输出参数,获取的对应设备索引的设备类型,具体参考**InputDevType**。 | +| deviceType | 输出参数,获取的对应设备索引的设备类型,具体参考[InputDevType](_input.md#inputdevtype)。 | **返回:** INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### GetPowerStatus @@ -139,7 +139,7 @@ int32_t(* InputController::GetPowerStatus) (uint32_t devIndex, uint32_t *status) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus。** +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### GetVendorName @@ -151,7 +151,7 @@ int32_t(* InputController::GetVendorName) (uint32_t devIndex, char *vendorName, **描述:** -获取devIndex对应的模组厂商名 +获取devIndex对应的模组厂商名。 **参数:** @@ -165,7 +165,7 @@ int32_t(* InputController::GetVendorName) (uint32_t devIndex, char *vendorName, Returns INPUT_SUCCESS 表示执行成功。 -Returns 其他值表示执行失败,具体错误码查看**RetSatus**。 +Returns 其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### RunCapacitanceTest @@ -186,7 +186,7 @@ int32_t(* InputController::RunCapacitanceTest) (uint32_t devIndex, uint32_t test | 名称 | 描述 | | -------- | -------- | | devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 | -| testType | 输入参数,容值测试的测试类型,具体参考**CapacitanceTest**。 | +| testType | 输入参数,容值测试的测试类型,具体参考[CapacitanceTest](_input.md#capacitancetest)。 | | result | 输出参数,容值测试的结果,成功则输出“SUCC”,失败则返回对应的错误提示。 | | length | 输入参数,保存容值测试结果的内存长度。 | @@ -194,7 +194,7 @@ int32_t(* InputController::RunCapacitanceTest) (uint32_t devIndex, uint32_t test INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### RunExtraCommand @@ -213,13 +213,13 @@ int32_t(* InputController::RunExtraCommand) (uint32_t devIndex, InputExtraCmd *c | 名称 | 描述 | | -------- | -------- | | devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 | -| cmd | 输入参数,拓展指令数据包,包括指令编码及参数,具体参考**InputExtraCmd**。 | +| cmd | 输入参数,拓展指令数据包,包括指令编码及参数,具体参考[InputExtraCmd](_input_extra_cmd.md)。 | **返回:** INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### SetGestureMode @@ -246,7 +246,7 @@ int32_t(* InputController::SetGestureMode) (uint32_t devIndex, uint32_t gestureM INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### SetPowerStatus @@ -273,4 +273,4 @@ int32_t(* InputController::SetPowerStatus) (uint32_t devIndex, uint32_t status) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_manager.md b/zh-cn/device-dev/reference/hdi-apis/_input_manager.md index a70e520d598b2f89eccd82e8f0facc1d0522e67f..ac0611a28958d35fe31156a134270a7be2c0ba03 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_manager.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_manager.md @@ -18,8 +18,8 @@ | ( [ScanInputDevice](#scaninputdevice) )(DevDesc \*staArr, uint32_t arrLen) | Input服务用于扫描所有在线设备。 [更多...](#scaninputdevice) | | ( [OpenInputDevice](#openinputdevice) )(uint32_t devIndex) | Input服务打开对应设备的设备文件 [更多...](#openinputdevice) | | ( [CloseInputDevice](#closeinputdevice) )(uint32_t devIndex) | Input服务关闭对应设备的设备文件 [更多...](#closeinputdevice) | -| ( [GetInputDevice](#getinputdevice) )(uint32_t devIndex, [DeviceInfo](_device_info.md) \*\*devInfo) | Input服务获取对应ID的设备信息 [更多...](#getinputdevice) | -| ( [GetInputDeviceList](#getinputdevicelist) )(uint32_t \*devNum, [DeviceInfo](_device_info.md) \*\*devList, uint32_t size) | Input服务获取所有Input设备列表的设备信息 [更多...](#getinputdevicelist) | +| ( [GetInputDevice](#getinputdevice) )(uint32_t devIndex, [InputDeviceInfo](_device_info.md) \*\*devInfo) | Input服务获取对应ID的设备信息 [更多...](#getinputdevice) | +| ( [GetInputDeviceList](#getinputdevicelist) )(uint32_t \*devNum, [InputDeviceInfo](_device_info.md) \*\*devList, uint32_t size) | Input服务获取所有Input设备列表的设备信息 [更多...](#getinputdevicelist) | ## **详细描述** @@ -53,7 +53,7 @@ Input服务关闭对应设备的设备文件。 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### GetInputDevice @@ -72,13 +72,13 @@ Input服务获取对应ID的设备信息。 | 名称 | 描述 | | -------- | -------- | | devIndex | 输入参数,Input设备索引,用于标志多个Input设备,取值从0开始,最多支持32个设备。 | -| devInfo | 输出参数,即devIndex对应的设备的设备信息,具体参考**DeviceInfo**。 | +| devInfo | 输出参数,即devIndex对应的设备的设备信息,具体参考[InputDeviceInfo](_device_info.md)。 | **返回:** INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### GetInputDeviceList @@ -97,14 +97,14 @@ Input服务获取所有Input设备列表的设备信息。 | 名称 | 描述 | | -------- | -------- | | devNum | 输出参数,当前已经注册过的所有Input设备的总数。 | -| devInfo | 输出参数,Input设备列表所对应的设备信息,具体参考**DeviceInfo**。 | +| devInfo | 输出参数,Input设备列表所对应的设备信息,具体参考[InputDeviceInfo](_device_info.md)。 | | size | 输入参数,即指定deviceList数组对应的元素个数。| 返回: INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### OpenInputDevice @@ -128,7 +128,7 @@ Input服务打开对应设备的设备文件。 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### ScanInputDevice @@ -153,4 +153,4 @@ Input服务用于扫描所有在线设备。 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md b/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md index cb5424095a877c82857f3e693823bb85a1e50155..fb4feb386c944bed951b37290c8711af10e4d28f 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md @@ -54,7 +54,7 @@ Input服务通过此接口注册回调函数到hdi中,所有Input设备由此 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### RegisterReportCallback @@ -81,7 +81,7 @@ Input服务通过此接口注册数据回调函数到hdi中,hdi通过此回调 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### UnregisterHotPlugCallback @@ -99,7 +99,7 @@ int32_t(* InputReporter::UnregisterHotPlugCallback) (void) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 ### UnregisterReportCallback @@ -123,4 +123,4 @@ int32_t(* InputReporter::UnregisterReportCallback) (uint32_t devIndex) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看**RetSatus**。 +其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md index 955b58092baa386c07225ccf5cd317e2cf6195ed..73ab78e3a96dd2462352ba188d74bb550375939d 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md +++ b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_ended_info.md @@ -21,4 +21,4 @@ ## **详细描述** -捕获结束相关信息,用于捕获结束回调 **OnCaptureEnded**。 +捕获结束相关信息,用于捕获结束回调[OnCaptureEnded](_camera.md#oncaptureended)。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md index d37ee91131ecde1979a36b9df4fddcca26378762..ed436019406bf6e0646d37c6a78cc3996d993b0e 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md +++ b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_camera_1_1_capture_info.md @@ -17,7 +17,7 @@ | -------- | -------- | | [streamIds_](_camera.md#streamids) | 捕获的流ID集合。 | | [captureSetting_](_camera.md#capturesetting) | 捕获的配置信息。 | -| [enableShutterCallback_](_camera.md#enableshuttercallback) | 使能捕获回调,每一次捕获后都会触发 **OnFrameShutter**。 | +| [enableShutterCallback_](_camera.md#enableshuttercallback) | 使能捕获回调,每一次捕获后都会触发 [OnFrameShutter](_camera.md#onframeshutter)。 | ## **详细描述** diff --git a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md index ed579509cd197d9ba69c4aee835edeaee5d04967..9bc4102d6e28c072dee510f953bb241cf9413766 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md +++ b/zh-cn/device-dev/reference/hdi-apis/_o_h_o_s_1_1_u_s_b_1_1_usbd_client.md @@ -54,7 +54,7 @@ | 静态 Public 成员函数 | 描述 | | -------- | -------- | -| [GetInstance](\_u\_s\_b.md#getinstance) () | 获取实例。 | +| [GetInstance](_u_s_b.md#getinstance) () | 获取实例。 | ## 详细描述 diff --git a/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md b/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md index e99f63e78499847569f19217ddfc009f6b9a99de..0b3aea7ea7efe0a9d32a357d6432cc438d455b36 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md +++ b/zh-cn/device-dev/reference/hdi-apis/_video_port_cap.md @@ -101,7 +101,7 @@ int32_t VideoPortCap::supportPixFmts[PIX_FORMAT_NUM] **描述:** -支持的像素格式,详见**OMX_COLOR_FORMATTYPE** +支持的像素格式 ### whAlignment diff --git a/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md b/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md index 435ef85b8d72485145cff125169a1efc4b03cf62..9471fe3dcd50cd9a9eb64b937221e654fb0d024a 100644 --- a/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md +++ b/zh-cn/device-dev/reference/hdi-apis/interface_i_user_auth_interface.md @@ -150,7 +150,7 @@ IUserAuthInterface::BeginIdentification([in] unsigned long contextId, [in] enum | 名称 | 描述 | | -------- | -------- | | contextId | 上下文索引。 | -| authType | 用户身份识别类型AuthType}。 | +| authType | 用户身份识别类型[AuthType](_hdf_user_auth.md#authtype)。 | | challenge | 随机挑战值,用于生成用户身份识别令牌,防止重放。 | | executorSensorHint | 执行器传感器提示,用于找到对应认证方式的传感器。 | | scheduleInfo | 调度信息[ScheduleInfo](_schedule_info.md)。 | diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 4f55d86f3a01808c7631404f134d6c8af3a7f7e8..d93db2c101cf19d4e158414e257abb588ee14953 100755 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -74,7 +74,13 @@ - [设备安全等级管理开发指导](subsys-security-devicesecuritylevel.md) - 启动恢复 - [启动恢复子系统概述](subsys-boot-overview.md) - - [init启动引导组件](subsys-boot-init.md) + - init启动引导组件 + - [引导启动配置文件](subsys-boot-init-cfg.md) + - [jobs管理](subsys-boot-init-jobs.md) + - [服务管理](subsys-boot-init-service.md) + - [系统参数](subsys-boot-init-sysparam.md) + - [沙盒管理](subsys-boot-init-sandbox.md) + - [插件](subsys-boot-init-plugin.md) - [appspawn应用孵化组件](subsys-boot-appspawn.md) - [bootstrap服务启动组件](subsys-boot-bootstrap.md) - [常见问题](subsys-boot-faqs.md) diff --git a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md index 598a744eb0f8694ad238415e23d324fda3fda055..d082cc359fab9b9cb72cc9f521192c6ad1c71ea0 100644 --- a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md +++ b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-plugin.md @@ -13,12 +13,12 @@ AI引擎框架规定了一套算法插件接入规范,各插件需实现规定 | -------- | -------- | -------- | | const long long GetVersion() const; | **作用**:获取插件版本信息。
**返回值**:版本号(long long) | - | | const char \*GetInferMode() const; | **作用**:获取算法推理类型。
**返回值**:"SYNC" or "ASYNC"; | - | -| int SyncProcess(IRequest \*request,
IResponse \*&response); | **作用**:执行插件同步算法。
**返回值**:0为成功,其他返回值失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道;
**response**(NOT NULL):作为出参用于接收算法插件发回的同步算法执行结果,引擎服务端与插件的数据通道; | -| int AsyncProcess(IRequest \*request,
IPluginAlgorithmCallback \*callback); | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道。
**callback**(NOT NULL):算法插件异步执行结果通过此回调返回引擎服务端; | -| int Prepare(long long transactionId,
const DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:加载算法插件。
**返回值**:0为成功,其他返回值失败。 | **transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息;
**inputInfo**(可为NULL):加载算法插件传入的一些信息;
**outputInfo**(可为NULL):调用加载接口时的出参,返回相关执行结果; | -| int Release(bool isFullUnload, long long
transactionId, const DataInfo &inputInfo); | **作用**:卸载相关算法插件。
**返回值**:0为成功,其他返回值失败。 | **isFullUnload**(NOT NULL):表示此插件是否只剩一个client调用,否则不能直接卸载插件,需等最后一个client来进行卸载;
**transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息;
**inputInfo**(可为NULL):卸载算法插件传入的一些信息; | -| int SetOption(int optionType, const
DataInfo &inputInfo); | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值失败。 | **optionType** (NOT NULL):算法配置项,算法插件可根据需要利用此状态位;
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息; | -| int GetOption(int optionType, const
DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值失败。 | **optionType**(NOT NULL):所获取配置项信息的对应算法状态位;
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息;
**outputInfo**(可为NULL):所要获取的配置项信息返回结果; | +| int SyncProcess(IRequest \*request,
IResponse \*&response); | **作用**:执行插件同步算法。
**返回值**:0为成功,其他返回值为失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道。
**response**(NOT NULL):作为出参用于接收算法插件发回的同步算法执行结果,引擎服务端与插件的数据通道。 | +| int AsyncProcess(IRequest \*request,
IPluginAlgorithmCallback \*callback); | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值为失败。 | **request**(NOT NULL):用于向算法插件传递请求内容;引擎服务端与插件的数据通道。
**callback**(NOT NULL):算法插件异步执行结果通过此回调返回引擎服务端。 | +| int Prepare(long long transactionId,
const DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:加载算法插件。
**返回值**:0为成功,其他返回值为失败。 | **transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息。
**inputInfo**(可为NULL):加载算法插件传入的一些信息。
**outputInfo**(可为NULL):调用加载接口时的出参,返回相关执行结果。 | +| int Release(bool isFullUnload, long long
transactionId, const DataInfo &inputInfo); | **作用**:卸载相关算法插件。
**返回值**:0为成功,其他返回值为失败。 | **isFullUnload**(NOT NULL):表示此插件是否只剩一个client调用,否则不能直接卸载插件,需等最后一个client来进行卸载。
**transactionId**(NOT NULL):事务ID,用于标记客户端+会话信息。
**inputInfo**(可为NULL):卸载算法插件传入的一些信息。 | +| int SetOption(int optionType, const
DataInfo &inputInfo); | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值为失败。 | **optionType** (NOT NULL):算法配置项,算法插件可根据需要利用此状态位。
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息。 | +| int GetOption(int optionType, const
DataInfo &inputInfo, DataInfo
&outputInfo); | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值为失败。 | **optionType**(NOT NULL):所获取配置项信息的对应算法状态位。
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息。
**outputInfo**(可为NULL):所要获取的配置项信息返回结果。 | 算法插件类接口:Prepare、SyncProcess、AsyncProcess、Release、SetOption、GetOption分别于客户端接口AieClientPrepare、AieClientSyncProcess、AieClientAsyncProcess、AieClientRelease、AieClientSetOption、AieClientGetOption一一对应;GetInferMode接口用于返回算法执行类型——同步或异步。 @@ -31,10 +31,10 @@ AI引擎框架规定了一套算法插件接入规范,各插件需实现规定 | 接口名 | 接口说明 | 参数要求 | | -------- | -------- | -------- | -| void OnEvent(PluginEvent event,
IResponse \*response); | 作用:插件通过此回调返回异步算法执行结果。 | **event**:算法执行结果枚举,‘ON_PLUGIN_SUCCEED’或 ‘ON_PLUGIN_FAIL’(成功或者失败);
**response**:算法执行结果封装; | +| void OnEvent(PluginEvent event,
IResponse \*response); | 作用:插件通过此回调返回异步算法执行结果。 | **event**:算法执行结果枚举,‘ON_PLUGIN_SUCCEED’或 ‘ON_PLUGIN_FAIL’(成功或者失败)。
**response**:算法执行结果封装。 | -Request、Response是ai引擎服务端与算法插件进行通信的对象。Request封装了调用方的请求、输入数据等,而插件主要通过Response将运算之后的结果返回给AI引擎服务端。 +Request、Response是AI引擎服务端与算法插件进行通信的对象。Request封装了调用方的请求、输入数据等,而插件主要通过Response将运算之后的结果返回给AI引擎服务端。 Request类的属性如下表所示。 @@ -46,7 +46,7 @@ Request类的属性如下表所示。 | -------- | -------- | -------- | | innerSequenceId_ | 类型:long long
作用:暂未启用。 | 0 | | requestId_ | 类型:int
作用:标识请求序列,用于绑定返回运算结果。 | 0 | -| operationId_ | 类型:int
作用:目前暂未启用。 | 0 | +| operationId_ | 类型:int
作用:暂未启用。 | 0 | | transactionId_ | 类型:long long
作用:事务ID,唯一标识clientId+sessionId。 | 0 | | algoPluginType_ | 类型:int
作用:引擎框架根据插件加载顺序分配的算法类型的ID。 | 0 | | msg_ | 类型:DataInfo
作用:存放调用算法接口的输入数据。 | .data = nullptr
.length = 0 | diff --git a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md index 54b413dd6cc5cffb4ecc358c368f1ef593520851..83150d465bf78878ad6b1cabe6716d2c14c95cd6 100644 --- a/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md +++ b/zh-cn/device-dev/subsystems/subsys-aiframework-devguide-sdk.md @@ -1,21 +1,21 @@ # SDK开发过程 -SDK头文件的功能实现是基于对SDK的调用映射到对客户端的调用。客户端端提供的接口如下表所示。 +SDK头文件的功能实现是基于对SDK的调用映射到对客户端的调用。Client端提供的接口如下表所示。 **表1** Client端提供的接口 | 接口名 | 接口说明 | 参数要求 | | -------- | -------- | -------- | -| int **AieClientInit**(const ConfigInfo &configInfo,
 ClientInfo &clientInfo, const AlgorithmInfo
 &algorithmInfo, IServiceDeadCb \*cb) | **作用**:链接并初始化引擎服务,激活跨进程调用。
**返回值**:0为成功,其他返回值失败。 | **configInfo**(NOT NULL):引擎相关初始化配置数据;
**clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**cb**(可为NULL):死亡回调 对象; | -| int **AieClientPrepare**(const ClientInfo &clientInfo
, const AlgorithmInfo &algorithmInfo, const DataInfo
 &inputInfo, DataInfo &outputInfo, IClientCb \*cb) | **作用**:加载算法插件。
**返回值**: 0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**inputInfo**(可为NULL):加载算法插件时输入所需信息;
**outputInfo**(可为NULL):加载算法插件之后如需返回信息则通过此出参返回;
**cb**:异步算法通过此回调返回运算结果,因此**异步算法此结构体不能为空**;若为同步算法,传入空值即可; | -| int **AieClientAsyncProcess**(const ClientInfo &clientInfo,
 const AlgorithmInfo &algorithmInfo, const DataInfo
 &inputInfo) | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**inputInfo**(可为NULL):算法运算入参; | -| int **AieClientSyncProcess**(const ClientInfo &clientInfo,
 const AlgorithmInfo &algorithmInfo, const
 DataInfo &inputInfo, DataInfo &outputInfo) | **作用**:执行同步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):调用算法信息;
**inputInfo**(可为NULL):算法运算入参;
**outputInfo**(可为NULL):同步算法运算结果出参; | -| int **AieClientRelease**(const ClientInfo &clientInfo,
 const AlgorithmInfo &algorithmInfo, const
 DataInfo &inputInfo) | **作用**:卸载算法插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**algorithmInfo**(NOT NULL):卸载算法插件的相关信息;
**inputInfo**(可为NULL):调用卸载接口时的输入信息; | -| int **AieClientDestroy**(ClientInfo &clientInfo) | **作用**:断开与服务端的链接,释放相关缓存。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):所要销毁的引擎客户端信息; | -| int **AieClientSetOption**(const ClientInfo &clientInfo,
 int optionType, const DataInfo &inputInfo) | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**optionType** (NOT NULL):算法配置项,算法插件可根据需要利用此状态位;
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息; | -| int **AieClientGetOption**(const ClientInfo &clientInfo,
 int optionType, const DataInfo &inputInfo,
 DataInfo &outputInfo) | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(NOT NULL):引擎客户端信息;
**optionType**(NOT NULL):所获取配置项信息的对应算法状态位;
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息;
**outputInfo**(可为NULL):所要获取的配置项信息返回结果; | +| int **AieClientInit**(const ConfigInfo &configInfo,
 ClientInfo &clientInfo, const AlgorithmInfo
 &algorithmInfo, IServiceDeadCb \*cb) | **作用**:链接并初始化引擎服务,激活跨进程调用。
**返回值**:0为成功,其他返回值失败。 | **configInfo**(不能为NULL):引擎相关初始化配置数据
**clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**cb**(可为NULL):死亡回调对象 | +| int **AieClientPrepare**(const ClientInfo &clientInfo
, const AlgorithmInfo &algorithmInfo, const DataInfo
 &inputInfo, DataInfo &outputInfo, IClientCb \*cb) | **作用**:加载算法插件。
**返回值**: 0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**inputInfo**(可为NULL):加载算法插件时输入所需信息
**outputInfo**(可为NULL):加载算法插件之后如需返回信息则通过此出参返回
**cb**:异步算法通过此回调返回运算结果,因此**异步算法此结构体不能为空** 若为同步算法,传入空值即可 | +| int **AieClientAsyncProcess**(const ClientInfo &clientInfo,
 const AlgorithmInfo &algorithmInfo, const DataInfo
 &inputInfo) | **作用**:执行异步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**inputInfo**(可为NULL):算法运算入参 | +| int **AieClientSyncProcess**(const ClientInfo &clientInfo,
 const AlgorithmInfo &algorithmInfo, const
 DataInfo &inputInfo, DataInfo &outputInfo) | **作用**:执行同步算法。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):调用算法信息
**inputInfo**(可为NULL):算法运算入参
**outputInfo**(可为NULL):同步算法运算结果出参 | +| int **AieClientRelease**(const ClientInfo &clientInfo,
 const AlgorithmInfo &algorithmInfo, const
 DataInfo &inputInfo) | **作用**:卸载算法插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**algorithmInfo**(不能为NULL):卸载算法插件的相关信息
**inputInfo**(可为NULL):调用卸载接口时的输入信息 | +| int **AieClientDestroy**(ClientInfo &clientInfo) | **作用**:断开与服务端的链接,释放相关缓存。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):所要销毁的引擎客户端信息 | +| int **AieClientSetOption**(const ClientInfo &clientInfo,
 int optionType, const DataInfo &inputInfo) | **作用**:设置配置项,可将一些算法的拓展信息通过此接口传入插件。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**optionType** (不能为NULL):算法配置项,算法插件可根据需要利用此状态位
**inputInfo**(可为NULL):插件可根据需要通过此入参设置算法参数信息 | +| int **AieClientGetOption**(const ClientInfo &clientInfo,
 int optionType, const DataInfo &inputInfo,
 DataInfo &outputInfo) | **作用**:给定特定的optionType和inputInfo,获取其对应的配置项信息。
**返回值**:0为成功,其他返回值失败。 | **clientInfo**(不能为NULL):引擎客户端信息
**optionType**(不能为NULL):所获取配置项信息的对应算法状态位
**inputInfo**(可为NULL):所获取配置项信息的对应算法参数信息
**outputInfo**(可为NULL):所要获取的配置项信息返回结果 | 其中,ConfigInfo,ClientInfo,AlgorithmInfo,DataInfo的数据结构如下表所示。 @@ -25,10 +25,10 @@ SDK头文件的功能实现是基于对SDK的调用映射到对客户端的调 | 结构体名称 | 说明 | 属性 | | -------- | -------- | -------- | -| ConfigInfo | 算法配置项信息。 | **const char \*description**:配置项信息主体; | -| ClientInfo | 客户端信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用);
**int clientId**:客户端ID;
**int sessionId:**会话ID;
**uid_t serverUid**:server端UID;
**uid_t clientUid:**client端UID;
**int extendLen**:拓展信息(extendMsg)长度;
**unsigned char \*extendMsg**:拓展信息主体; | -| AlgorithmInfo | 算法信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用);
**bool isAsync**:是否为异步执行;
**int algorithmType:**引擎框架根据插件加载顺序分配的算法类型ID;
**long long algorithmVersion**:算法版本号;
**bool isCloud**:是否上云(当前还未启用);
**int operateId**:执行ID(当前还未启用);
**int requestId**:请求ID,标识每次request,以对应执行结果;
**int extendLen**:拓展信息(extendMsg)长度;
**unsigned char \*extendMsg**:拓展信息主体; | -| DataInfo | 算法数据入参(inputInfo)、
接口调用结果出参(outputInfo)。 | **unsigned char \*data:**数据主体;
**int length**:数据(data)长度; | +| ConfigInfo | 算法配置项信息。 | **const char \*description**:配置项信息主体 | +| ClientInfo | 客户端信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用)
**int clientId**:客户端ID
**int sessionId**:会话ID
**uid_t serverUid**:server端UID
**uid_t clientUid**:client端UID
**int extendLen**:拓展信息(extendMsg)长度
**unsigned char \*extendMsg**:拓展信息主体 | +| AlgorithmInfo | 算法信息。 | **long long clientVersion**:客户端设备版本号(当前还未启用)
**bool isAsync**:是否为异步执行
**int algorithmType**:引擎框架根据插件加载顺序分配的算法类型ID
**long long algorithmVersion**:算法版本号
**bool isCloud**:是否上云(当前还未启用)
**int operateId**:执行ID(当前还未启用)
**int requestId**:请求ID,标识每次request,以对应执行结果
**int extendLen**:拓展信息(extendMsg)长度
**unsigned char \*extendMsg**:拓展信息主体 | +| DataInfo | 算法数据入参(inputInfo)、
接口调用结果出参(outputInfo)。 | **unsigned char \*data**:数据主体
**int length**:数据(data)长度 | 具体开发过程可参考[唤醒词识别SDK开发示例](../subsystems/subsys-aiframework-demo-sdk.md)。 diff --git a/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md b/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md index 659600d23bd24647f465f3e50c528c3393057e0d..8d0c3224f4dd2758f4b9479f998421414c56602e 100644 --- a/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md +++ b/zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @@ -17,14 +17,16 @@ AI引擎框架各模块之间的代码依赖关系如下图所示: 在AI引擎框架的整体规划中,北向SDK属于client端的一部分,插件由server端调用,属于server端的一部分,因此AI引擎框架为接入的插件与北向SDK规划的路径: - SDK代码路径://foundation/ai/engine/services/client/algorithm_sdk - e.g. //foundation/ai/engine/services/client/algorithm_sdk/cv + + 示例1://foundation/ai/engine/services/client/algorithm_sdk/cv - e.g. //foundation/ai/engine/services/client/algorithm_sdk/nlu + 示例2://foundation/ai/engine/services/client/algorithm_sdk/nlu - 插件代码路径://foundation/ai/engine/services/server/plugin - e.g. //foundation/ai/engine/services/server/plugin/cv + + 示例1://foundation/ai/engine/services/server/plugin/cv - e.g. //foundation/ai/engine/services/server/plugin/nlu + 示例2://foundation/ai/engine/services/server/plugin/nlu ## 规则:插件提供的全部对外接口,统一存放在AI业务子系统interfaces/kits目录 diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md b/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md index a01d244546c32e94498b6b0271dcefb4c4df8801..52e2fe1650974d7011378f267ee15acc3bad192f 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-jobs.md @@ -160,6 +160,20 @@ job就是命令集合,jobs管理就是对要执行的一组命令集合进行 小型系统和标准系统 + + + write + + + write filename value
如:write /data/testfile 0 + + + 写文件命令。后面跟两个参数,第一个参数是文件的绝对路径,第二个参数是要写入文件的字符串。 + + + 标准系统 + + stop @@ -300,6 +314,20 @@ job就是命令集合,jobs管理就是对要执行的一组命令集合进行 小型系统和标准系统 + + + syncexec + + + syncexec 可执行文件路径 可执行文件传的参数
如:syncexec /system/bin/udevadm trigger + + + 同步执行,syncexec 会调用wait等待子进程结束。参数个数不超过10个。 + + + 标准系统 + + mknode diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-service.md b/zh-cn/device-dev/subsystems/subsys-boot-init-service.md index 29d88d97fe509c7f1676c566032db0f0d1b204ef..36dcceb2d73a601de2bbcc06815e66e5eba44236 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-service.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-service.md @@ -208,11 +208,11 @@ importance - 当前服务优先级 + 标准系统:当前服务优先级
小型系统:标记服务重要性 标准系统中: 服务优先级取值范围 [-20, 19],超出为无效设置。
- 小型系统中:0 : 非重要进程;非0 : 重要进程 + 小型系统中:0 :不重启系统 ;非0 : 重启系统。 小型系统和标准系统 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md index 8be5fe23e2c375fc01002165aff65ce1530e665e..4c8ed67988e5d30c5adcc5532fef02e2b376c0ea 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md @@ -8,7 +8,7 @@ HiSysEvent打点提供了事件埋点功能,开发者可以通过在关键路 ### 运作机制 -在进行HiSysEvent事件埋点之前,需要先完成HiSysEvent打点配置,具体配置方法请参考[《HiSysEvent打点配置指导》](subsys-dfx-hisysevent-logging-config.md)。 +在进行HiSysEvent事件埋点之前,需要先完成HiSysEvent打点配置,具体配置方法请参考[HiSysEvent打点配置指导](subsys-dfx-hisysevent-logging-config.md)。 ## 开发指导 @@ -18,28 +18,29 @@ HiSysEvent打点提供了事件埋点功能,开发者可以通过在关键路 ### 接口说明 -#### c++接口说明 +#### C++接口说明 -c++事件埋点开发能力如下:HiSysEvent类,具体的API详见接口文档 。 +C++事件埋点开发能力如下:HiSysEvent类,具体的API详见接口文档 。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 在OpenHarmony-3.2-Beta3版本中,为避免打点风暴事件引发性能问题,对HiSysEvent打点进行了管控,表1中的HiSysEvent::Write打点API接口被表2中的HiSysEventWrite宏接口取代。HiSysEvent::Write接口已废弃,请使用HiSysEventWrite宏完成HiSysEvent事件打点。 +> +> 在OpenHarmony-3.2-Beta3版本中,为避免打点风暴事件引发性能问题,对HiSysEvent打点进行了管控。表1中的HiSysEvent::Write打点API接口被表2中的HiSysEventWrite宏接口取代。HiSysEvent::Write接口已废弃,请使用HiSysEventWrite宏完成HiSysEvent事件打点。 -**表1** c++事件埋点API接口功能介绍(已废弃) +**表1** C++事件埋点API接口功能介绍(已废弃) | 接口名 | 描述 | -| ------------------------------------------------------------ | ---------------------- | +| ------------------------------------------------------------ | --------------------- | | template<typename... Types> 
static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | 将打点事件数据进行落盘 | -**表2** c++事件埋点API接口功能介绍 +**表2** C++事件埋点API接口功能介绍 | 接口名 | 描述 | -| ------------------------------------------------------------ | ---------------------- | -| HiSysEventWrite(domain, eventName, type, ...) | 将打点事件数据进行落盘| +| ------------------------------------------------------------ | --------------------- | +| HiSysEventWrite(domain, eventName, type, ...) | 将打点事件数据进行落盘 | - **表3** c++事件类型API接口介绍 + **表3** C++事件类型介绍 -| 接口名 | 描述 | -| --------- | ------------ | +| 事件类型 | 描述 | +| --------- | ----------- | | FAULT | 故障类型事件 | | STATISTIC | 统计类型事件 | | SECURITY | 安全类型事件 | @@ -52,17 +53,17 @@ kernel事件埋点开发能力如下: **表4** kernel事件埋点API接口功能介绍 | 接口名 | 描述 | -| ------------------------------------------------------------ | ------------------------------------ | -| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | 创建一个事件对象 | -| void hisysevent_destroy(struct hiview_hisysevent *event); | 销毁一个事件对象 | -| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | 将整数类型的事件参数添加到事件对象 | +| ------------------------------------------------------------ | ----------------------------------- | +| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | 创建一个事件对象 | +| void hisysevent_destroy(struct hiview_hisysevent *event); | 销毁一个事件对象 | +| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | 将整数类型的事件参数添加到事件对象 | | int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | 将字符串类型的事件参数添加到事件对象 | -| int hisysevent_write(struct hiview_hisysevent *event); | 将事件对象数据进行落盘 | +| int hisysevent_write(struct hiview_hisysevent *event); | 将事件对象数据进行落盘 | -**表5** kernel事件类型API接口介绍 +**表5** kernel事件类型介绍 -| 接口名 | 描述 | -| --------- | ------------ | +| 事件类型 | 描述 | +| --------- | ----------- | | FAULT | 故障类型事件 | | STATISTIC | 统计类型事件 | | SECURITY | 安全类型事件 | @@ -70,9 +71,9 @@ kernel事件埋点开发能力如下: ### 开发步骤 -#### c++埋点开发步骤 +#### C++埋点开发步骤 -1. 在需要埋点的地方直接调用埋点接口,并传入相应事件参数即可: +1. 在需要埋点的地方直接调用埋点接口,并传入相应事件参数。 ```c++ HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo"); @@ -80,13 +81,13 @@ kernel事件埋点开发能力如下: #### kernel埋点开发步骤 -1. 根据事件领域、事件名称、事件类型参数,创建一个基础的事件对象: +1. 根据事件领域、事件名称、事件类型参数,创建一个基础的事件对象。 ```c struct hiview_hisysevent *event = hisysevent_create("KERNEL", "BOOT", BEHAVIOR); ``` -2. 将自定义的事件参数,传入到事件对象里: +2. 将自定义的事件参数,传入到事件对象里。 ```c // 添加整数类型参数 @@ -96,13 +97,13 @@ kernel事件埋点开发能力如下: hisysevent_put_string(event, "MSG", "This is a test message"); ``` -3. 在事件对象构建完成后,将事件进行上报: +3. 在事件对象构建完成后,将事件进行上报。 ```c hisysevent_write(event); ``` -4. 事件上报完成后,需要手动将对象销毁: +4. 事件上报完成后,需要手动将对象销毁。 ```c hisysevent_destroy(&event); @@ -110,7 +111,7 @@ kernel事件埋点开发能力如下: #### 事件领域屏蔽的步骤 -1. 在相应的文件中定义名称为“DOMAIN_MASKS”,内容形如“DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n”,共有三种屏蔽场景: +1. 在相应的文件中定义名称为“DOMAIN_MASKS”,内容形如“DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n”。共有三种屏蔽场景: - 只屏蔽当前源码文件中的相应事件领域的HiSysEvent打点,在该cpp文件引入hisysevent.h头文件之前定义宏DOMAIN_MASKS即可。 ```c++ @@ -125,7 +126,7 @@ kernel事件埋点开发能力如下: } ``` -- 全局屏蔽相应事件领域的HiSysEvent打点,则在/build/config/compiler/BUILD.gn中定义宏DIMAIN_MASKS即可。 +- 全局屏蔽相应事件领域的HiSysEvent打点,则在/build/config/compiler/BUILD.gn中定义宏DOMAIN_MASKS即可。 ```gn cflags_cc += ["-DDOMAIN_MASKS=\"DOMAIN_NAME_1|DOMAIN_NAME_2|...|DOMAIN_NAME_n\""] ``` @@ -140,17 +141,17 @@ kernel事件埋点开发能力如下: ### 开发实例 -#### c++埋点开发实例 +#### C++埋点开发实例 假设业务模块需要在应用启动时进行埋点来记录应用启动事件,且需要记录应用的包名信息,完整使用示例如下所示: -1. 首先,需要在业务模块的在BUILD.gn里增加HiSysEvent部件依赖: +1. 首先,需要在业务模块的在BUILD.gn里增加HiSysEvent部件依赖。 ```c++ external_deps = [ "hisysevent_native:libhisysevent" ] ``` -2. 在业务模块的应用启动函数StartAbility()中,调用埋点接口并传入对应事件参数: +2. 在业务模块的应用启动函数StartAbility()中,调用埋点接口并传入对应事件参数。 ```c++ #include "hisysevent.h" diff --git a/zh-cn/device-dev/subsystems/subsys-xts-guide.md b/zh-cn/device-dev/subsystems/subsys-xts-guide.md index 991972c0d7f3684aea0dbf703cf7129a11434030..36f1f7ab87265f684f24487de5b107332ef05c15 100644 --- a/zh-cn/device-dev/subsystems/subsys-xts-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-xts-guide.md @@ -143,18 +143,15 @@ XTS子系统当前包括acts与tools软件包: 4. 使用宏定义LITE_TEST_CASE写测试用例 包括三个参数:测试套件名称,测试用例名称,用例属性(测试类型、用例粒度、用例级别)。 - - ``` LITE_TEST_CASE(IntTestSuite, TestCase001, Function | MediumTest | Level1) { //do something }; ``` - 5. 使用宏定义 RUN_TEST_SUITE注册测试套件 - + ``` RUN_TEST_SUITE(IntTestSuite); ``` @@ -258,16 +255,16 @@ XTS子系统当前包括acts与tools软件包: // 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() - { + // Preset action of the test case + virtual void SetUp() + { + } + // Cleanup action of the test case + virtual void TearDown() + { } }; - ``` + ``` 3. 使用宏定义HWTEST或HWTEST_F写测试用例 @@ -288,8 +285,7 @@ XTS子系统当前包括acts与tools软件包: 每个测试模块目录下新建BUILD.gn编译文件,用于指定编译后可执行文件的名称、依赖的头文件、依赖的库等;具体写法如下。每个测试模块将独立编译成.bin可执行文件, 该文件可直接push到单板上进行测试。 举例: - - + ``` import("//test/xts/tools/lite/build/suite_lite.gni") hcpptest_suite("ActsDemoTest") { diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index 89c636ed0e58c696b02b80e8b5f0ce508cc753ba..3554669de0f544e90530523f64e038ffcfad7b69 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -390,6 +390,7 @@ - [Audio](driver/driver-peripherals-audio-des.md) - [Camera](driver/driver-peripherals-camera-des.md) - [Face_auth](driver/driver-peripherals-face_auth-des.md) + - [Fingerprint_auth](driver/driver-peripherals-fingerprint_auth-des.md) - [LCD](driver/driver-peripherals-lcd-des.md) - [Light](driver/driver-peripherals-light-des.md) - [Pin_auth](driver/driver-peripherals-pinauth-des.md) diff --git a/zh-cn/glossary.md b/zh-cn/glossary.md index 6bf069541423e98103d141d6bb7142d54ac565ce..f165d1f467caffacb153d9af265a4a22fa4bfccc 100644 --- a/zh-cn/glossary.md +++ b/zh-cn/glossary.md @@ -99,6 +99,6 @@ 两种Ability框架模型结构的其中一种。从API 9开始支持。Stage模型将Ability分为Ability和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等等一系列ExtensionAbility。 - ### System Type,系统类型 - - Mini System,轻量系统:面向MCU类处理器,例如ARM Cortex-M、RISC-V 32位的设备,资源极其有限,参考内存≥128KiB,提供丰富的近距连接能力以及丰富的外设总线访问能力。典型产品有智能家居领域的联接类模组、传感器设备等。 + - MiniSystem,轻量系统:面向MCU(Microcontroller Unit,微控制单元)类处理器,例如ARM Cortex-M、RISC-V 32位的设备,资源极其有限,参考内存≥128KiB,提供丰富的近距连接能力以及丰富的外设总线访问能力。典型产品有智能家居领域的联接类模组、传感器设备等。 - Small System,小型系统:面向应用处理器,例如Arm Cortex-A的设备,参考内存≥1MiB,提供更高的安全能力,提供标准的图形框架,提供视频编解码的多媒体能力。典型产品有智能家居领域的IPCamera、电子猫眼、路由器以及智慧出行域的行车记录仪等。 - Standard System,标准系统:面向应用处理器,例如Arm Cortex-A的设备,参考内存≥128MiB,提供增强的交互能力,提供3D GPU以及硬件合成能力,提供更多控件以及动效更丰富的图形能力,提供完整的应用框架。典型产品有高端的冰箱显示屏等。 diff --git a/zh-cn/readme/ARK-Runtime-Subsystem-zh.md b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md index 6016dc3a7fcc079661d1c2b64f8b4f7656f75a9f..ed7dadfeebf8e3b6d52151abf6331bcb7eb13035 100644 --- a/zh-cn/readme/ARK-Runtime-Subsystem-zh.md +++ b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md @@ -39,7 +39,7 @@ JS Runtime主要由四个子系统组成: 编译子系统包含Stub编译器、基于Circuit IR的优化编译框架和代码生成器。 - JS Runtime subsystem - + 运行时子系统包含了各种JS运行相关的模块: - 内存管理:对象分配器与垃圾回收器\(并发标记和部分内存压缩的CMS-GC和Partial-Compressing-GC\) - 分析工具:DFX工具、cpu和heap的profiling工具 @@ -49,15 +49,25 @@ JS Runtime主要由四个子系统组成: **ArkCompiler-JS的设计特点:** -- ArkCompiler JS Runtime的主要设计目标,是为OpenHarmony操作系统提供JavaScript/TypeScript应用程序执行引擎,而不是作为浏览器中的JavaScript执行引擎。 +- ArkCompiler JS Runtime的主要设计目标: + + 为OpenHarmony操作系统提供JavaScript/TypeScript应用程序执行引擎,而不是作为浏览器中的JavaScript执行引擎。 + +- 为了提升应用的执行性能和安全性: + + ArkCompiler JS Runtime选择将JavaScript/TypeScript程序预先静态编译为方舟字节码(带上静态类型信息),从而减少运行时的编译和类型信息收集开销。另外出于安全性和性能的考虑,ArkCompiler JS Runtime选择不支持eval和只支持strict模式的代码。 + +- 原生支持TypeScript: + + 目前业界通用的执行方式是把TS转化为JS,再通过JS运行时来执行。ArkJS规划在ts2abc编译TS源码时,会推导分析TS的类型信息并传递给ArkCompiler JS运行时。运行时直接利用类型信息静态生成内联缓存(inline caching)从而加速字节码执行。另外,ArkJS规划中的TSAOT \(Ahead-of-Time\) Compiler,可以利用ts2abc传递的类型信息,直接编译生成高质量的机器码,使得应用可以直接以机器码形式运行,提升运行性能。 -- 为了提升应用的执行性能和安全性,ArkCompiler JS Runtime选择将JavaScript/TypeScript程序预先静态编译为方舟字节码(带上静态类型信息),从而减少运行时的编译和类型信息收集开销。另外出于安全性和性能的考虑,ArkCompiler JS Runtime选择不支持eval和只支持strict模式的代码。 +- 轻量级Actor并发模型: -- 原生支持TypeScript:目前业界通用的执行方式是把TS转化为JS,再通过JS运行时来执行。ArkJS规划在ts2abc编译TS源码时,会推导分析TS的类型信息并传递给ArkCompiler JS运行时。运行时直接利用类型信息静态生成内联缓存(inline caching)从而加速字节码执行。另外,ArkJS规划中的TSAOT \(Ahead-of-Time\) Compiler,可以利用ts2abc传递的类型信息,直接编译生成高质量的机器码,使得应用可以直接以机器码形式运行,提升运行性能。 + ECMAScript没有提供并发规范,业界JS引擎的实现中常用Actor并发模型。此模型下执行体之间不共享任何数据,通过消息机制进行通信。业界当前实现的JS Actor模型(web-worker)有启动速度慢、内存占用高这些缺陷。为了利用设备的多核能力获得更好的性能提升,ArkCompiler JS Runtime需要提供启动快、内存占用少的Actor实现。目前ArkCompiler JS运行时已经实现在Actor内存隔离模型的基础上,共享actor实例中的不可变或者不易变的对象(方法和字节码),后续继续共享内建代码块、常量字符串等等,来提升JS Actor的启动性能和节省内存开销,达到实现轻量级Actor并发模型的目标。 -- 轻量级Actor并发模型:ECMAScript没有提供并发规范,业界JS引擎的实现中常用Actor并发模型。此模型下执行体之间不共享任何数据,通过消息机制进行通信。业界当前实现的JS Actor模型(web-worker)有启动速度慢、内存占用高这些缺陷。为了利用设备的多核能力获得更好的性能提升,ArkCompiler JS Runtime需要提供启动快、内存占用少的Actor实现。目前ArkCompiler JS运行时已经实现在Actor内存隔离模型的基础上,共享actor实例中的不可变或者不易变的对象(方法和字节码),后续继续共享内建代码块、常量字符串等等,来提升JS Actor的启动性能和节省内存开销,达到实现轻量级Actor并发模型的目标。 +- TypeScript/C++的跨语言交互: -- TypeScript/C++的跨语言交互:在OpenHarmony操作系统平台API实现中,通常需要面临C/C++代码访问和操作TS对象的场景。对这个业务场景,Ark-JS规划可以根据TS程序中的class声明和运行时约定,静态生成包含TS对象布局描述的C/C++头文件,以及操作这些TS对象的C/C++实现库。在C/C++代码中,通过包含TS对象描述头文件以及链接对应实现库,实现直接操作TS对象的效果。由于TS类型或其内在布局并非总是固定不变的,因此在TS对象操作的代码实现中,会插入类型检查,如果对象类型或布局在运行时发生变化,则回退执行通用的慢速路径。 + 在OpenHarmony操作系统平台API实现中,通常需要面临C/C++代码访问和操作TS对象的场景。对这个业务场景,Ark-JS规划可以根据TS程序中的class声明和运行时约定,静态生成包含TS对象布局描述的C/C++头文件,以及操作这些TS对象的C/C++实现库。在C/C++代码中,通过包含TS对象描述头文件以及链接对应实现库,实现直接操作TS对象的效果。由于TS类型或其内在布局并非总是固定不变的,因此在TS对象操作的代码实现中,会插入类型检查,如果对象类型或布局在运行时发生变化,则回退执行通用的慢速路径。 ## 目录 diff --git "a/zh-cn/readme/JS-UI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/JS-UI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" index 0ee5cca3c762178585c6a8a6d8cb2c95e58407c5..b44cb671f9334b51ea49543429ab472a8734c795 100644 --- "a/zh-cn/readme/JS-UI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/JS-UI\346\241\206\346\236\266\345\255\220\347\263\273\347\273\237.md" @@ -114,7 +114,7 @@ JS UI开发框架源代码在/foundation/ace下,目录结构如下图所示: [arkui\_ace\_engine](https://gitee.com/openharmony/arkui_ace_engine) -[arkui\\_ace\_engine\_lite](https://gitee.com/openharmony/arkui_ace_engine_lite) +[arkui\_ace\_engine\_lite](https://gitee.com/openharmony/arkui_ace_engine_lite) [ace\_napi](https://gitee.com/openharmony/ace_napi) diff --git "a/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" index 6f352ec9e419614174605f57a0920b70e105e828..b28f930b1bda7d024df928465943d587126dc544 100755 --- "a/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\345\205\250\347\220\203\345\214\226\345\255\220\347\263\273\347\273\237.md" @@ -7,7 +7,7 @@ ## 简介 -当OpenHarmony设备或应用在全球不同区域使用时,系统和应用需要满足不同市场用户关于语言、文化习俗的需求。全球化子系统提供支持多语言、多文化的能力,包括: +当OpenHarmony系统/应用在全球不同区域使用时,系统/应用需要满足不同市场用户关于语言、文化习俗的需求。全球化子系统提供支持多语言、多文化的能力,包括: - **资源管理能力** diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md index 7a47c2fc202195039a512d4cfc6b7ed6e687a61f..695fb424302d0db3cae0c99475b6f71a7ce0db9b 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md +++ b/zh-cn/release-notes/OpenHarmony-v3.1.1-release.md @@ -163,4 +163,4 @@ repo forall -c 'git lfs pull' | ------------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------- | ------------ | | [I4Z3G9](https://gitee.com/openharmony/graphic_graphic_2d/issues/I4Z3G9) | 【RK3568】打开沉浸式主窗口和在主窗口上打开辅助窗口出现闪屏 | 影响开发者体验。 | 2022-06-15 | | [I58GFY](https://gitee.com/openharmony/communication_wifi/issues/I58GFY) | 【RK3568】 2.4G/5G频段WPA+TKIP/AES加密方式均连接失败 | TP-Link AX50型号路由器无法正常连接WiFi。 | 2022-06-30 | -| [I59P32](https://gitee.com/openharmony/device_manager/issues/I59P32) | 【RK3568】设备信任周期超期后无法重新PIN码认证 | 长时间不输入PIN码导致超时后触发,重启设备可恢复。 | 2022-06-15 | +| [I59P32](https://gitee.com/openharmony/distributedhardware_device_manager/issues/I59P32) | 【RK3568】设备信任周期超期后无法重新PIN码认证 | 长时间不输入PIN码导致超时后触发,重启设备可恢复。 | 2022-06-15 | diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md index 3eb8da4befa96166c8a54de10b512f504ecfcc05..27f8d8ffcd02f187c1af8cc722dffa2ff4f84777 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md @@ -19,7 +19,7 @@ **标准系统应用程序框架能力增强** -元能力支持卡片提供方添加静态和动态卡片、组件支持本地免安装启动、系统SA启动和访问组件、支持单实例Ability迁移、运行管理支持打开沙箱应用、系统应用ability不在最新任务列表显示。 +元能力支持卡片提供方添加静态和动态卡片、组件支持本地免安装启动、系统SA启动和访问组件、支持单实例Ability迁移、运行管理支持打开沙箱应用、系统应用Ability不在最新任务列表显示。 包管理支持获取当前包的包名和证书指纹信息NDK接口能力、查询指定应用的PackInfo信息、原子化服务老化卸载。 @@ -148,7 +148,7 @@ | 泛Sensor服务子系统 | - 支持更多类型的传感器上报。
- 支持SELinux。
主要涉及如下需求:
I53SFI 【DFX打点】【泛Sensor服务子系统】提供系统事件、SA dump、trace打点
I537CB 【新增规格】泛Sensor能力持续集成-旋转矢量传感器
I537AN 【新增规格】泛Sensor能力持续集成-重力传感器
I5379T 【新增规格】泛Sensor能力持续集成-地磁传感器
I5379C 【新增规格】泛Sensor能力持续集成-方向传感器
I53784 【新增规格】泛Sensor能力持续集成-环境光传感器
I53SFS 【新增规格】【泛Sensor服务】SELinux策略配置 | NA | | 分布式数据管理子系统 | data_share支持多种数据类型。
主要涉及如下需求:
I5EHGF 【DataShare】DataShare支持多种数据储存类型 | NA | | web子系统 | - 新增支持JS相关交互能力。
- 新增支持网络、键鼠、webstorage、SELinux策略等能力。
主要涉及如下需求:
I5DM1E 【新增规格】web组件的JS窗口管理
I5DNG2 【新增规格】JS侧提供全量hittest接口以及DefaultUserAgent获取
I5EK53 【新增规格】【web子系统】web组件http验证管理
I5EGBB 【新增规格】【web子系统】【web部件】web子系统的SELinux策略配置
I5EBG1 【新增规格】【web子系统】web子系统适配w3c network information api
I5EVEC 【新增规格】【web子系统】web内核对接鼠标、键盘等外设能力
I5FF2L 【新增规格】【web子系统】web组件支持webstorage | NA | -| 驱动子系统 | - 支持内核态驱动动态加载及DFX能力。
- 提供Codec2.0接口及codec驱动模型。
- Camera、Display、Audio、Sensor、Wlan等模块驱动能力增强。
主要涉及如下需求:
I536FN 【新增特性】【驱动子系统】支持HDI passthrougt模式
I5DJE5 【增强特性】兼容Linux uevent事件上报机制,增强设备即插即用功能
I550OL 【新增特性】提供DFX跟踪定位,获取信息能力
I544XP 【新增特性】支持HDF服务SELinux权限检查 标准系统
I528DG 【新增特性】支持Codec 2.0参考实现,简化适配难度
I50I6S 【新增特性】Audio新增IPC模式与直调模式接口调用统一
I5A6H6 【增强特性】增强显示设备管理,支持多屏显示能力
I5B0C5 【新增特性】Camera支持实现Mate类型的流
I5B0BR 【新增特性】录像模式自拍镜像功能
I5AJW1 【新增特性】支持Linux libALSA音频接口兼容
I56V2N 【新增特性】HDF WLAN DAL HDI功率模式相关接口的定义与开发
I5F411 【增强特性】马达效果能力增强 | NA | +| 驱动子系统 | - 支持内核态驱动动态加载及DFX能力。
- 提供Codec2.0接口及codec驱动模型。
- Camera、Display、Audio、Sensor、WLAN等模块驱动能力增强。
主要涉及如下需求:
I536FN 【新增特性】【驱动子系统】支持HDI passthrough模式
I5DJE5 【增强特性】兼容Linux uevent事件上报机制,增强设备即插即用功能
I550OL 【新增特性】提供DFX跟踪定位,获取信息能力
I544XP 【新增特性】支持HDF服务SELinux权限检查 标准系统
I528DG 【新增特性】支持Codec 2.0参考实现,简化适配难度
I50I6S 【新增特性】Audio新增IPC模式与直调模式接口调用统一
I5A6H6 【增强特性】增强显示设备管理,支持多屏显示能力
I5B0C5 【新增特性】Camera支持实现Mate类型的流
I5B0BR 【新增特性】录像模式自拍镜像功能
I5AJW1 【新增特性】支持Linux libALSA音频接口兼容
I56V2N 【新增特性】HDF WLAN DAL HDI功率模式相关接口的定义与开发
I5F411 【增强特性】马达效果能力增强 | NA | | USB服务子系统 | - 支持USB服务广播消息。
- 增加SELinux安全策略。
主要涉及如下需求:
I59MYK 【新增特性】USB服务广播消息
I5AR8N 【新增规格】【USB服务子系统】USB服务子系统的SELinux策略配置 | NA | | 内核子系统 | - 新增支持内存精细化管控特性。
- 新增支持关联服务adj调整机制。
主要涉及如下需求:
I58LOD 【新增特性】支持关联服务adj调整机制
I54Y5J 【新增特性】支持memtrack内存占用和进程维度adj查询接口特性
I56B3Q 【新增特性】支持OnMemoryLevel特性
I5B694 【新增特性】支持新型内存精细化管控特性
I59O8H 【新增特性】支持purgable memory特性
I5CXOK 【新增特性】支持hyperhold可靠性提升特性 | NA | @@ -200,8 +200,8 @@ | ISSUE单 | 问题描述 | | -------- | -------- | -| [I4Z3G9](https://e.gitee.com/open_harmony/issues/list?issue=I4Z3G9) | 【RK3568】打开沉浸式主窗口和在主窗口上打开辅助窗口出现闪屏 | -| [I59M4Q](https://gitee.com/openharmony/developtools_hdc/issues/I59M4Q?from=project-issue) | API9 hdc_std连接设备低概率断连 | +| [I4Z3G9](https://gitee.com/openharmony/graphic_graphic_2d/issues/I4Z3G9) | 【RK3568】打开沉浸式主窗口和在主窗口上打开辅助窗口出现闪屏 | +| [I59M4Q](https://gitee.com/openharmony/developtools_hdc/issues/I59M4Q) | API9 hdc_std连接设备低概率断连 | | [I54D32](https://gitee.com/openharmony/multimedia_camera_standard/issues/I54D32) | 【RK3568】【必现】相机连续多次录像出现黑屏 | diff --git a/zh-cn/release-notes/api-change/template/changelog-x-x.md b/zh-cn/release-notes/api-change/template/changelog-x-x.md index abf59c77cba59f171efbb6121e24f238516ad50e..b20dbfc1fc13ba0dc94a8044119ac0ae2473cfb7 100644 --- a/zh-cn/release-notes/api-change/template/changelog-x-x.md +++ b/zh-cn/release-notes/api-change/template/changelog-x-x.md @@ -1,14 +1,17 @@ -# ChangeLog -## xxx子系统(该段落为示例,请不要修改或删除) -已经release的版本发生了影响契约兼容性(契约兼容:也称语义兼容,指版本演进后,开发者原有程序行为不发生变化)的变更(包括不限于接口名、参数、返回值、所需要的权限、调用顺序、枚举值、配置参数、路径等),则需要在ChangeLog中对变更进行阐述。 -### cl.subsystemname.x xxx功能变更, 例:DeviceType属性变更、相机权限变更(尽量概括,不要超过15个字) -每个变更标题前需要附加编号:cl.subsystemname.x。cl为ChangeLog首字母缩写,subsystemname请填写子系统英文标准名称,x表示变更序号(从低到高逐位增加)。 +# xxx子系统ChangeLog + +相比最近一个发布版本(包括不限于LTS、Release、Beta、monthly版本)发生了影响契约兼容性(契约兼容:也称语义兼容,指版本演进后,开发者原有程序行为不发生变化)的变更(包括不限于接口名、参数、返回值、所需要的权限、调用顺序、枚举值、配置参数、路径等),则需要在ChangeLog中对变更进行阐述。 + +## cl.subsystemname.x xxx功能变更, 例:DeviceType属性变更、相机权限变更(尽量概括,不要超过15个字) + +每个变更标题前需要附加编号:cl.subsystemname.x。cl为ChangeLog首字母缩写,subsystemname请填写子系统英文标准名称,x表示变更序号(从低到高逐位增加,起始为1)。 以功能维度对变更点进行概括描述。例如:xxx功能的xxx、xxx等发生了xxx变化,开发者需要根据以下说明对应用进行适配。 如果有此变更有对应的需求或设计文档,可以在描述中附上对应的设计文档编号。 **变更影响** -是否影响已release的接口或者接口行为发生变更等;影响的是JS接口、Java接口还是Native接口。 +是否影响已发布的接口或者接口行为发生变更,影响的是JS接口还是Native接口。 +是否影响在此前版本已开发的应用,即应用是否需要进行适配动才可以在新版本SDK环境正常编译通过。 **关键的接口/组件变更** @@ -16,15 +19,13 @@ **适配指导(可选,不涉及则可以删除)** -(前面空一行)提供指导,帮助开发者针对相关变更进行适配,使应用可以与新版本兼容。例: +提供指导,帮助开发者针对相关变更进行适配,使应用可以与新版本兼容。 +例: 在xxx文件中将xxx参数修改为xxx。 + ``` sample code ``` -### cl.subsystemname.x xxx功能变更 -每个功能变更点在自己的子系统章节内新增一个功能变更章节。 -## xxx子系统 -每个子系统有且只能有一个子系统章节。 diff --git a/zh-cn/release-notes/api-change/v3.2-beta2/native-apidiff-v3.2-beta2.md b/zh-cn/release-notes/api-change/v3.2-beta2/native-apidiff-v3.2-beta2.md new file mode 100644 index 0000000000000000000000000000000000000000..b8e6c8a45ece7f1c7b9ea6d3c58297678af3a17d --- /dev/null +++ b/zh-cn/release-notes/api-change/v3.2-beta2/native-apidiff-v3.2-beta2.md @@ -0,0 +1,13 @@ +# Native API 差异报告 + +OpenHarmony 3.2 Beta2相较于OpenHarmony 3.2 Beta1版本的API变更如下: + +## 标准系统接口变更 + +| 模块名称 | 接口名称 | 变更类型 | 变更说明 | +| -------- | ------------------------------------------------------------ | -------- | ----------------------------------------------- | +| 包管理-BundleFramework | OH_NativeBundle_ApplicationInfo OH_NativeBundle_GetCurrentApplicationInfo() | 新增 | 获取当前应用的包名和指纹信息 | +| 图形-NativeWindow | int32_t OH_NativeWindow_NativeWindowSetScalingMode(OHNativeWindow *window, uint32_t sequence, OHScalingMode scalingMode) | 新增 | 新增通过NativeWindow设置缩放模式的接口 | +| 图形-NativeWindow | int32_t OH_NativeWindow_NativeWindowSetMetaData(OHNativeWindow *window, uint32_t sequence, int32_t size, const OHHDRMetaData *metaData) | 新增 | 新增通过NativeWindow设置HDR元数据的接口 | +| 图形-NativeWindow | int32_t OH_NativeWindow_NativeWindowSetMetaDataSet(OHNativeWindow *window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t *metaData) | 新增 | 新增通过NativeWindow设置HDR元数据集的接口 | +| 图形-NativeWindow | int32_t OH_NativeWindow_NativeWindowSetTunnelHandle(OHNativeWindow *window, const OHExtDataHandle *handle) | 新增 | 新增通过NativeWindow设置tunnelhandle的接口 | \ No newline at end of file