diff --git a/CODEOWNERS b/CODEOWNERS index 5b847d685a149d302ba349ea93f6329c32d1cd12..a98eba13b7b574232201efd76d84579561a42ccd 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -23,11 +23,17 @@ zh-cn/device-dev/quick-start/ @li-yan339 zh-cn/device-dev/driver/ @li-yan339 zh-cn/device-dev/get-code/ @li-yan339 zh-cn/device-dev/hpm-part/ @duangavin123_admin -zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 -zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 +zh-cn/device-dev/reference/hdi-apis/ @li-yan339 +zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md @li-yan339 @chenmudan +zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @li-yan339 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-overview.md @Austin23 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-makefile.md @Austin23 @chenmudan +zh-cn/device-dev/porting/porting-thirdparty-cmake.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin @@ -45,7 +51,7 @@ zh-cn/device-dev/subsystems/subsys-utils-overview.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-utils-faqs.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-guide.md @Austin23 -zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 +zh-cn/device-dev/subsystems/subsys-aiframework-envbuild.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-codemanage.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-name.md @Austin23 zh-cn/device-dev/subsystems/subsys-aiframework-tech-interface.md @Austin23 @@ -79,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/README_zh.md b/README_zh.md index 3c65434aac3acaee899db2e1eba85e61c03de5a5..ebf1bc8d7557d35f99eaacf8fd1427972d61d3b0 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,7 +18,7 @@ - master:最新开发版本。 - - OpenHarmony 3.2 Beta1版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta1.md)了解版本详情。 + - OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 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/Readme-EN.md b/en/application-dev/Readme-EN.md index fdc79edbcb58a00729b62b5e9f7d239b52cdbf59..8e42633391269303e5e8d888561281f57d1718ae 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -15,7 +15,6 @@ - Development Fundamentals - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - - [Resource File Categories](quick-start/basic-resource-file-categories.md) - [SysCap](quick-start/syscap.md) - Development - [Ability Development](ability/Readme-EN.md) @@ -45,8 +44,5 @@ - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - APIs - [JS and TS APIs](reference/apis/Readme-EN.md) - - Native APIs - - [Standard Library](reference/native-lib/third_party_libc/musl.md) - - [Node_API](reference/native-lib/third_party_napi/napi.md) - Contribution - [How to Contribute](../contribute/documentation-contribution.md) 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/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index 5b61bcec4b25312f994ed94362339e601df5cd55..e1d67a295b673453d7340fb20a40c81d8c7a7855 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -78,29 +78,29 @@ To create Page abilities for an application in the stage model, you must impleme onCreate(want, launchParam) { console.log("MainAbility onCreate") } - + onDestroy() { console.log("MainAbility onDestroy") } - + onWindowStageCreate(windowStage) { console.log("MainAbility onWindowStageCreate") - + windowStage.loadContent("pages/index").then((data) => { console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) }).catch((error) => { console.error("MainAbility load content failed with error: " + JSON.stringify(error)) }) } - + onWindowStageDestroy() { console.log("MainAbility onWindowStageDestroy") } - + onForeground() { console.log("MainAbility onForeground") } - + onBackground() { console.log("MainAbility onBackground") } @@ -300,7 +300,7 @@ export default class MainAbility extends Ability { Obtain the `want` parameter that contains the page information from the custom component and process the route based on the URI. ```ts -import router from '@system.router' +import router from '@ohos.router' @Entry @Component diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index 753b706605487dbe2cf5ebe0ce961b19d94e7ee0..e60f2c01333c1bef7324b3ef6cfe2c83821a95cd 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -54,8 +54,10 @@ 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: + +- [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) -- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - APIs - [JS and TS APIs](reference/apis/Readme-EN.md) - Native APIs 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/ipc-rpc-overview.md b/en/application-dev/connectivity/ipc-rpc-overview.md index 19bbe8dc26871bec8b2f6f48273d90dacc148d70..e75536863b1ae1b5c5371f51b0d7e26e4db97ed6 100755 --- a/en/application-dev/connectivity/ipc-rpc-overview.md +++ b/en/application-dev/connectivity/ipc-rpc-overview.md @@ -19,4 +19,4 @@ In OpenHarmony documents, proxy represents the service requester, and stub repre ## Related Modules -[Distributed Scheduler](https://gitee.com/openharmony/distributedschedule_dms_fwk) +[Distributed Scheduler](https://gitee.com/openharmony/ability_dmsfwk) diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md index 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/device/device-location-info.md b/en/application-dev/device/device-location-info.md index dce40ff38546fe1b86a60bf670cb18adf9e15968..a32decd05ac0ba0d6db06749c18dcd31d3a7645b 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -14,49 +14,49 @@ The following table describes APIs available for obtaining device location infor **Table 1** APIs for obtaining device location information -| API | Description | -| -------- | -------- | -| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Registers a listener for location changes with a location request initiated. | -| off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted. | -| on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events. | -| off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events. | -| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports. | -| off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports. | -| on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events. | -| off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events. | -| on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Registers a listener for GNSS NMEA message change events. | -| off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unregisters the listener for GNSS NMEA message change events. | -| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence. | -| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence. | -| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtains the current location. This function uses an asynchronous callback to return the result. | -| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This function uses a promise to return the result. | -| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This function uses an asynchronous callback to return the result. | -| getLastLocation() : Promise<Location> | Obtains the previous location. This function uses a promise to return the result. | -| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This function uses an asynchronous callback to return the result. | -| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This function uses a promise to return the result. | -| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This function uses an asynchronous callback to return the result. | -| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This function uses a promise to return the result. | -| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This function uses an asynchronous callback to return the result. | -| enableLocation() : Promise<boolean> | Enables the location service. This function uses a promise to return the result. | -| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This function uses an asynchronous callback to return the result. | -| disableLocation() : Promise<boolean> | Disables the location service. This function uses a promise to return the result. | -| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This function uses an asynchronous callback to return the result. | -| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This function uses a promise to return the result. | -| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses an asynchronous callback to return the result. | -| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses a promise to return the result. | -| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This function uses an asynchronous callback to return the result. | -| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This function uses a promise to return the result. | -| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | Checks whether a user agrees with the privacy statement of the location service. This function uses an asynchronous callback to return the result. | -| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | Checks whether a user agrees with the privacy statement of the location service. This function uses a promise to return the result. | -| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Sets the user confirmation status for the privacy statement of the location service. This function uses an asynchronous callback to return the result. | -| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Sets the user confirmation status for the privacy statement of the location service. This function uses a promise to return the result. | +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Registers a listener for location changes with a location request initiated. | +| off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted. | +| on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events. | +| off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events. | +| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports. | +| off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports. | +| on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events. | +| off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events. | +| on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Registers a listener for GNSS NMEA message change events. | +| off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unregisters the listener for GNSS NMEA message change events. | +| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence. | +| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence. | +| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtains the current location. This API uses an asynchronous callback to return the result. | +| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This API uses a promise to return the result. | +| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This API uses an asynchronous callback to return the result. | +| getLastLocation() : Promise<Location> | Obtains the previous location. This API uses a promise to return the result. | +| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. | +| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This API uses a promise to return the result. | +| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result. | +| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This API uses a promise to return the result. | +| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This API uses an asynchronous callback to return the result. | +| enableLocation() : Promise<boolean> | Enables the location service. This API uses a promise to return the result. | +| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This API uses an asynchronous callback to return the result. | +| disableLocation() : Promise<boolean> | Disables the location service. This API uses a promise to return the result. | +| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This API uses an asynchronous callback to return the result. | +| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This API uses a promise to return the result. | +| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses an asynchronous callback to return the result.| +| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses a promise to return the result.| +| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This API uses an asynchronous callback to return the result.| +| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This API uses a promise to return the result. | +| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | Checks whether a user agrees with the privacy statement of the location service. This API uses an asynchronous callback to return the result.| +| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | Checks whether a user agrees with the privacy statement of the location service. This API uses a promise to return the result.| +| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Sets the user confirmation status for the privacy statement of the location service. This API uses an asynchronous callback to return the result.| +| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Sets the user confirmation status for the privacy statement of the location service. This API uses a promise to return the result.| ## How to Develop To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md). -1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user. For details, see the following section. +1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. The system provides the following location permissions: - ohos.permission.LOCATION @@ -64,9 +64,9 @@ To learn more about the APIs for obtaining device location information, see [Geo The **ohos.permission.LOCATION** permission is a must if your application needs to access the device location information. - If your application needs to access the device location information when running on the background, it must be allowed to run on the background in the configuration file and also granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information even when your application moves to the background. + If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. - To allow your application to access device location information, you can declare the required permissions in the **config.json** file of your application. The sample code is as follows: + To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows: ``` @@ -83,8 +83,8 @@ To learn more about the APIs for obtaining device location information, see [Geo } } ``` - - For details about the fields, see . + + For details about the fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. @@ -92,7 +92,7 @@ To learn more about the APIs for obtaining device location information, see [Geo import geolocation from '@ohos.geolocation'; ``` -3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information. +3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.
**Method 1:** To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported. @@ -112,15 +112,15 @@ To learn more about the APIs for obtaining device location information, see [Geo **Table 2** Common use cases of the location function - | Use Case | Constant | Description | - | -------- | -------- | -------- | - | Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization. | - | Trajectory tracking | TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization. | - | Ride hailing | CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization. | - | Life service | DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization. | - | Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization. | - - The following example instantiates the **RequestParam** object for navigation: + | Use Case | Constant | Description | + | ------------ | ------------------- | ------------------------------------------------------------ | + | Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + + Sample code for initializing **requestInfo** for navigation: ``` var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; @@ -143,20 +143,20 @@ To learn more about the APIs for obtaining device location information, see [Geo **Table 3** Location priority policies - | Policy | Constant | Description | - | -------- | -------- | -------- | - | Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization. | - | Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization. | - | Power efficiency priority | LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization. | + | Policy | Constant | Description | + | ------------------ | -------------- | ------------------------------------------------------------ | + | Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.| - The following example instantiates the **RequestParam** object for the location accuracy priority policy: + Sample code for initializing **requestInfo** for the location accuracy priority policy: ``` var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` 4. Instantiate the **Callback** object for the system to report location results. - Your application needs to implement the callback interface defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic. + Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic. ``` var locationChange = (location) => { @@ -176,8 +176,8 @@ To learn more about the APIs for obtaining device location information, see [Geo geolocation.off('locationChange', locationChange); ``` - If your application does not need the real-time device location, it can use the last known device location cached in the system instead. - +If your application does not need the real-time device location, it can use the last known device location cached in the system instead. + ``` geolocation.getLastLocation((err, data) => { if (err) { 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 e7e97631c240bb42358d3b0b630a92094f34bcfc..316ee1b07898a24721b81625c2e9193ae08aa85f 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-guidelines.md @@ -6,9 +6,9 @@ HiTraceMeter provides APIs for system performance tracing. You can call the APIs ## Available APIs -The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md). +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 09bc3b733346db921cd04b76aff04b41d60af0b9..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"}); ``` - 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/Readme-EN.md b/en/application-dev/media/Readme-EN.md index b9f7b63d5b451da5213a8c282d52865d48c4e3eb..677e70f6e3b7eee215530cd15e7ab1b42676866c 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -1,7 +1,6 @@ # Media - Audio - - [Audio Overview](audio-overview.md) - [Audio Playback Development](audio-playback.md) - [Audio Recording Development](audio-recorder.md) @@ -15,9 +14,9 @@ - [Video Playback Development](video-playback.md) - [Video Recording Development](video-recorder.md) -- Image +- Image - [Image Development](image.md) -- Camera +- Camera - [Camera Development](camera.md) 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/media/audio-playback.md b/en/application-dev/media/audio-playback.md index 2b0f260908c9e2986269601e588659ce6ce119fc..d65d0abfc4d4649f7f1847abdbe6fb0a832e194e 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -39,38 +39,38 @@ function printfDescription(obj) { // Set the player callbacks. function setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. + audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. }); - audioPlayer.on('play', () => { // Set the 'play' event callback. + audioPlayer.on('play', () => { // Set the `play` event callback. console.info('audio play success'); - audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. + audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. }); - audioPlayer.on('pause', () => { // Set the 'pause' event callback. + audioPlayer.on('pause', () => { // Set the `pause` event callback. console.info('audio pause success'); - audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. + audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. }); - audioPlayer.on('stop', () => { // Set the 'stop' event callback. + audioPlayer.on('stop', () => { // Set the `stop` event callback. console.info('audio stop success'); - audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. + audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. }); - audioPlayer.on('reset', () => { // Set the 'reset' event callback. + audioPlayer.on('reset', () => { // Set the `reset` event callback. console.info('audio reset success'); - audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); - audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. + audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the `timeUpdate` event callback. if (typeof(seekDoneTime) == 'undefined') { console.info('audio seek fail'); return; } console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. + audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. }); - audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + audioPlayer.on('volumeChange', () => { // Set the `volumeChange` event callback. console.info('audio volumeChange success'); - audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. + audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. if (typeof (arrlist) != 'undefined') { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); @@ -78,13 +78,13 @@ function setCallBack(audioPlayer) { } else { console.log(`audio getTrackDescription fail, error:${error.message}`); } - audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback. + audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback. }); }); - audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); }); - audioPlayer.on('error', (error) => { // Set the 'error' event callback. + audioPlayer.on('error', (error) => { // Set the 'error' event callback. console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); @@ -94,7 +94,7 @@ function setCallBack(audioPlayer) { async function audioPlayerDemo() { // 1. Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); - setCallBack(audioPlayer); // Set the event callbacks. + setCallBack(audioPlayer); // Set the event callbacks. // 2. Set the URI of the audio file. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "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" command. @@ -107,7 +107,7 @@ async function audioPlayerDemo() { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. } ``` @@ -119,23 +119,23 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the 'play' event callback. + audioPlayer.on('play', () => { // Set the `play` event callback. console.info('audio play success'); }); - audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); - audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); } async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. + let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. + this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "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" command. let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; @@ -147,7 +147,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. } } ``` @@ -161,20 +161,20 @@ export class AudioDemo { // Set the player callbacks. private isNextMusic = false; setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the 'play' event callback. + audioPlayer.on('play', () => { // Set the `play` event callback. console.info('audio play success'); - audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. + audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. }); - audioPlayer.on('reset', () => { // Set the 'reset' event callback. + audioPlayer.on('reset', () => { // Set the `reset` event callback. console.info('audio play success'); - if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. - this.nextMusic(audioPlayer); // Changing songs is implemented. + if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. + this.nextMusic(audioPlayer); // Changing songs is implemented. } else { - audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; } }); @@ -197,8 +197,8 @@ export class AudioDemo { } async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. + let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. + this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "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" command. let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; @@ -223,19 +223,19 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.loop = true; // Set the loop playback attribute. - audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. + audioPlayer.loop = true; // Set the loop playback attribute. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback. + audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback. console.info('audio play success'); }); } async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. + let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. + this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "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" command. let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; @@ -247,7 +247,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. } } ``` diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index f44905cb2c2d33a8efb52f80d01e199e674e2c5b..77038cc101186059e9377c85d8e5b880784c2b9e 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -9,6 +9,5 @@ - Development Fundamentals - [Application Package Structure Configuration File (FA Model)](package-structure.md) - [Application Package Structure Configuration File (Stage Model)](stage-structure.md) - - [Resource File Categories](basic-resource-file-categories.md) - [SysCap](syscap.md) - [HarmonyAppProvision Configuration File](app-provision-structure.md) diff --git a/en/application-dev/quick-start/basic-resource-file-categories.md b/en/application-dev/quick-start/basic-resource-file-categories.md deleted file mode 100644 index e37a24074d5396103b9204f3c6ab20a745de2616..0000000000000000000000000000000000000000 --- a/en/application-dev/quick-start/basic-resource-file-categories.md +++ /dev/null @@ -1,79 +0,0 @@ -# Resource File Categories - - -## resources Directory - -All the application resource files, such as strings, images, and audio files, are stored in the **resources** directory, allowing you to easily access, use, and maintain them. The **resources** directory consists of two types of sub-directories: the **base** sub-directory and qualifiers sub-directories, and the **rawfile** sub-directory. For details, see Categories of the **resources** directory. - -Example of the **resources** directory: - -``` -resources -|---base // Default sub-directory -| |---element -| | |---string.json -| |---media -| | |---icon.png -|---en_GB-vertical-car-mdpi // Example of a qualifiers sub-directory, which needs to be created on your own -| |---element -| | |---string.json -| |---media -| | |---icon.png -|---rawfile // Default sub-directory -``` - -**Table 1** Categories of the **resources** directory - -| Category | base and Qualifiers Sub-directories | rawfile Sub-directory | -| ----------- | ---------------------------------------- | ---------------------------------------- | -| Structure | Sub-directories are structured in two levels. The directory name must comply with specified naming conventions so that its target resource file in the correct directory can be matched based on the device status.
The **base** sub-directory and qualifiers sub-directories are the first level of sub-directories under **resources**.
- The **base** sub-directory is generated by default. If no qualifiers sub-directories in the **resources** directory of the application match the device status, the resource file in the **base** sub-directory will be automatically referenced.
- You need to create qualifiers sub-directories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Sub-directories](#qualifiers-sub-directories).
Resource group sub-directories are located at the second level of sub-directories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Sub-directories](#resource-group-sub-directories). | You can create multiple levels of sub-directories with custom directory names. They can be used to store various resource files.
However, resource files in the **rawfile** sub-directory will not be matched based on the device status. | -| Compilation | Resource files in the sub-directories are compiled into binary files, and each resource file is assigned an ID. | Resource files in the sub-directory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. | -| Reference | Resource files in the sub-directories are referenced based on the resource type and resource name. | Resource files in the sub-directories are referenced based on the specified file path and file name. | - - -## Qualifiers Sub-directories - -The name of a qualifiers sub-directory consists of one or more qualifiers that represent the application scenarios or device characteristics, covering the mobile country code (MCC), mobile network code (MNC), language, script, country or region, screen orientation, device type, color mode, and screen density. The qualifiers are separated using underscores (_) or hyphens (-). When creating a qualifiers sub-directory, you need to understand the directory naming conventions and the rules for matching qualifiers sub-directories and the device status. - -**Naming Conventions for Qualifiers Sub-directories** - -- Qualifiers are ordered in the following sequence: _MCC_MNC-language_script_country/region-screen orientation-device type-color mode-screen density_. You can select one or multiple qualifiers to name your sub-directory based on your application scenarios and device characteristics. - -- Separation between qualifiers: The language, script, and country/region qualifiers are separated using underscores (\_); the MNC and MCC qualifiers are also separated using underscores (\_); other qualifiers are separated using hyphens (-). For example, **zh_Hant_CN** and **zh_CN-car-ldpi**. - -- Value range of qualifiers: The value of each qualifier must meet the requirements. Otherwise, the resource files in the sub-directory cannot be matched. - - **Table 2** Requirements for qualifier values - - | Qualifier Type | Description and Value Range | - | ------------------ | ---------------------------------------- | - | MCC&MNC | Indicates the MCC and MNC, which are obtained from the network where the device is registered. The MCC can be either followed by the MNC with an underscore (_) in between or be used independently. For example, **mcc460** represents China, and **mcc460_mnc00** represents China Mobile.
For details about the value range, refer to **ITU-T E.212** (the international identification plan for public networks and subscriptions). | - | Language | Indicates the language used by the device. The value consists of two or three lowercase letters, for example, **zh** indicates Chinese, **en** indicates English, and **mai** indicates Maithili.
For details about the value range, refer to **ISO 639** (codes for the representation of names of languages). | - | Script | Indicates the script type used by the device. The value starts with one uppercase letter followed by three lowercase letters, for example, **Hans** indicates simplified Chinese and **Hant** indicates traditional Chinese.
For details about the value range, refer to **ISO 15924** (codes for the representation of names of scripts). | - | Country/Region | Indicates the country or region where a user is located. The value consists of two or three uppercase letters or three digits, for example, **CN** indicates China and **GB** indicates the United Kingdom.
For details about the value range, refer to **ISO 3166-1** (codes for the representation of names of countries and their subdivisions). | - | Screen orientation | Indicates the screen orientation of the device. The value can be:
- **vertical**: portrait orientation
- **horizontal**: landscape orientation | - | Device type | Indicates the device type. The value can be:
- **car**: head units
- **tv**: smart TVs
- **wearable**: wearables | - | Color mode | Indicates the color mode of the device. The value can be:
- **dark**: dark mode
- **light**: light mode | - | Screen density | Indicates the screen density of the device, in dpi. The value can be:
- **sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].
- **mdpi**: screen density with medium-scale dots per inch (MDPI). This value is applicable for devices with a DPI range of (120, 160].
- **ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].
- **xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].
- **xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].
- **xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640]. | - -**Rules for Matching Qualifiers Sub-directories and Device Resources** - -- Qualifiers are matched with the device resources in the following priorities: MCC&MNC > locale (options: language, language_script, language_country/region, and language_script_country/region) > screen orientation > device type > color mode > screen density - -- If the qualifiers sub-directories contain the **MCC, MNC, language, script, screen orientation, device type, and color mode** qualifiers, their values must be consistent with the current device status so that the sub-directories can be used for matching the device resources. For example, the qualifiers sub-directory **zh_CN-car-ldpi** cannot be used for matching the resource files labeled **en_US**. - - -## Resource Group Sub-directories - -You can create resource group sub-directories (including element, media, animation, layout, graphic, and profile) in the **base** and qualifiers sub-directories to store resource files of specific types. For details, see Resource group sub-directories. - -**Table 3** Resource group sub-directories - -| Resource Group Sub-directory | Description | Resource File | -| ---------------------------- | ---------------------------------------- | ---------------------------------------- | -| element | Indicates element resources. Each type of data is represented by a JSON file. The options are as follows:
- **boolean**: boolean data
- **color**: color data
- **float**: floating-point data
- **intarray**: array of integer
- **integer**: integer data
- **pattern**: pattern data
- **plural**: plural form data
- **strarray**: array of strings
- **string**: string data | It is recommended that files in the **element** sub-directory be named the same as the following files, each of which can contain only data of the same type:
- boolean.json
- color.json
- float.json
- intarray.json
- integer.json
- pattern.json
- plural.json
- strarray.json
- string.json | -| media | Indicates media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. | -| animation | Indicates animation resources, in XML format. | The file name can be customized, for example, **zoom_in.xml**. | -| layout | Indicates layout resources, in XML format. | The file name can be customized, for example, **home_layout.xml**. | -| graphic | Indicates graphic resources, in XML format. | The file name can be customized, for example, **notifications_dark.xml**. | -| profile | Indicates other types of files, which are stored in their raw formats. | The file name can be customized. | 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/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 30bb3aacd85d9e11012fb66dc276a88476139126..f2ee2ee4ab190bcd3487aaca974a153c0aed914e 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -1,9 +1,9 @@ # Development References -- [JavaScript-based Web-like Development Paradigm](arkui-js/Readme-EN.md) -- [TypeScript-based Declarative Development Paradigm](arkui-ts/Readme-EN.md) +- [Component Reference(TypeScript-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) +- [Component Reference(JavaScript-based Web-like Development Paradigm)](arkui-js/Readme-EN.md) - [APIs](apis/Readme-EN.md) - + - [JS (eTS Included) APIs](apis/Readme-EN.md) - Native APIs - [Standard Library](native-lib/third_party_libc/musl.md) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 7a7288f485c659e1ec964584865d346b4c297064..6b5bbc8aa3d671c4cf0b01316db441d33c0f189f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -4,53 +4,58 @@ - Ability Framework - - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) - - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) - - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) - - [@ohos.application.Ability](js-apis-application-ability.md) - - [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md) - - [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md) - - [@ohos.application.AbilityStage ](js-apis-application-abilitystage.md) - - [@ohos.application.abilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) - - [@ohos.application.appManager](js-apis-appmanager.md) - - [@ohos.application.Configuration](js-apis-configuration.md) - - [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md) - - [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md) - - [@ohos.ability.featureAbility](js-apis-featureAbility.md) - - [@ohos.application.formBindingData](js-apis-formbindingdata.md) - - [@ohos.application.FormExtension](js-apis-formextension.md) - - [@ohos.application.formError](js-apis-formerror.md) - - [@ohos.application.formHost](js-apis-formhost.md) - - [@ohos.application.formInfo](js-apis-formInfo.md) - - [@ohos.application.missionManager](js-apis-missionManager.md) - - [@ohos.application.formProvider](js-apis-formprovider.md) - - [@ohos.ability.particleAbility](js-apis-particleAbility.md) - - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - - [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) - - [@ohos.application.uriPermissionManager](js-apis-uripermissionmanager.md) - - [@ohos.application.Want](js-apis-application-Want.md) - - [@ohos.wantAgent](js-apis-wantAgent.md) - - ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md) - - app/[context](js-apis-Context.md) - - application/[AbilityContext](js-apis-ability-context.md) - - application/[ApplicationContext](js-apis-application-applicationContext.md) - - application/[abilityDelegator](js-apis-application-abilityDelegator.md) - - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) - - application/[abilityMonitor](js-apis-application-abilityMonitor.md) - - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) - - application/[AbilityStageContext](js-apis-abilitystagecontext.md) - - application/[Context](js-apis-application-context.md) - - application/[ExtensionContext](js-apis-extension-context.md) - - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) - - application/[FormExtensionContext](js-apis-formextensioncontext.md) - - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - - application/[ProcessRunningInfo](js-apis-processrunninginfo.md) - - application/[ServiceExtensionContext](js-apis-service-extension-context.md) - - application/[shellCmdResult](js-apis-application-shellCmdResult.md) - - application/[MissionInfo](js-apis-application-missionInfo.md) - + - FA Model + - [@ohos.ability.featureAbility](js-apis-featureAbility.md) + - [@ohos.ability.particleAbility](js-apis-particleAbility.md) + - ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md) + - app/[context](js-apis-Context.md) + - Stage Model + - [@ohos.application.Ability](js-apis-application-ability.md) + - [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md) + - [@ohos.application.AbilityStage](js-apis-application-abilitystage.md) + - [@ohos.application.abilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) + - [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md) + - [@ohos.application.FormExtension](js-apis-formextension.md) + - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) + - [@ohos.application.StartOptions](js-apis-application-StartOptions.md) + - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) + - application/[AbilityContext](js-apis-ability-context.md) + - application/[ApplicationContext](js-apis-application-applicationContext.md) + - application/[AbilityStageContext](js-apis-abilitystagecontext.md) + - application/[Context](js-apis-application-context.md) + - application/[ExtensionContext](js-apis-extension-context.md) + - application/[FormExtensionContext](js-apis-formextensioncontext.md) + - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) + - application/[ServiceExtensionContext](js-apis-service-extension-context.md) + - FA and Stage Models + - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) + - [@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) + - [@ohos.application.EnvironmentCallback](js-apis-application-EnvironmentCallback.md) + - [@ohos.application.formBindingData](js-apis-formbindingdata.md) + - [@ohos.application.formError](js-apis-formerror.md) + - [@ohos.application.formHost](js-apis-formhost.md) + - [@ohos.application.formInfo](js-apis-formInfo.md) + - [@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) + - application/[abilityMonitor](js-apis-application-abilityMonitor.md) + - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) + - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) + - 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) @@ -58,7 +63,7 @@ - [@ohos.notification](js-apis-notification.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md) - application/[EventHub](js-apis-eventhub.md) - + - Bundle Management - [@ohos.bundle](js-apis-Bundle.md) @@ -69,26 +74,30 @@ - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) - bundle/[CustomizeData](js-apis-bundle-CustomizeData.md) + - bundle/[ElementName](js-apis-bundle-ElementName.md) - bundle/[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) - bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md) - bundle/[Metadata](js-apis-bundle-Metadata.md) - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - + - UI Page - [@ohos.animator](js-apis-animator.md) - [@ohos.mediaquery](js-apis-mediaquery.md) - [@ohos.prompt](js-apis-prompt.md) - [@ohos.router](js-apis-router.md) - + - [@ohos.uiAppearance](js-apis-uiappearance.md) + - Graphics - [@ohos.display ](js-apis-display.md) + - [@ohos.effectKit](js-apis-effectKit.md) + - [@ohos.screen](js-apis-screen.md) - [@ohos.screenshot](js-apis-screenshot.md) - [@ohos.window](js-apis-window.md) - [webgl](js-apis-webgl.md) - [webgl2](js-apis-webgl2.md) - + - Media - [@ohos.multimedia.audio](js-apis-audio.md) @@ -96,32 +105,33 @@ - [@ohos.multimedia.image](js-apis-image.md) - [@ohos.multimedia.media](js-apis-media.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - + - Resource Management - [@ohos.i18n](js-apis-i18n.md) - [@ohos.intl](js-apis-intl.md) - [@ohos.resourceManager](js-apis-resource-manager.md) - + - Resource Scheduling - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.workScheduler ](js-apis-workScheduler.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - + - Custom Management - [@ohos.configPolicy](js-apis-config-policy.md) - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - + - Security - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) + - [@ohos.privacyManager](js-apis-privacyManager.md) - [@ohos.security.huks ](js-apis-huks.md) - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@system.cipher](js-apis-system-cipher.md) - + - Data Management - [@ohos.data.dataAbility ](js-apis-data-ability.md) @@ -134,7 +144,7 @@ - [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) - data/rdb/[resultSet](js-apis-data-resultset.md) - + - File Management - [@ohos.document](js-apis-document.md) @@ -145,7 +155,7 @@ - [@ohos.storageStatistics](js-apis-storage-statistics.md) - [@ohos.volumeManager](js-apis-volumemanager.md) - [@ohos.securityLabel](js-apis-securityLabel.md) - + - Telephony Service - [@ohos.contact](js-apis-contact.md) @@ -155,7 +165,7 @@ - [@ohos.telephony.sim](js-apis-sim.md) - [@ohos.telephony.sms](js-apis-sms.md) - [@ohos.telephony.data](js-apis-telephony-data.md) - + - Network Management - [@ohos.net.connection](js-apis-net-connection.md) @@ -163,7 +173,7 @@ - [@ohos.request](js-apis-request.md) - [@ohos.net.socket](js-apis-socket.md) - [@ohos.net.webSocket](js-apis-webSocket.md) - + - Connectivity - [@ohos.bluetooth](js-apis-bluetooth.md) @@ -174,7 +184,7 @@ - [@ohos.rpc](js-apis-rpc.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - + - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) @@ -193,7 +203,7 @@ - [@ohos.systemTime](js-apis-system-time.md) - [@ohos.wallpaper](js-apis-wallpaper.md) - [Timer](js-apis-timer.md) - + - Device Management - [@ohos.batteryInfo ](js-apis-battery-info.md) @@ -219,13 +229,13 @@ - [@ohos.update](js-apis-update.md) - [@ohos.usb](js-apis-usb.md) - [@ohos.vibrator](js-apis-vibrator.md) - + - Account Management - [@ohos.account.appAccount](js-apis-appAccount.md) - [@ohos.account.distributedAccount](js-apis-distributed-account.md) - [@ohos.account.osAccount](js-apis-osAccount.md) - + - Language Base Class Library - [@ohos.convertxml](js-apis-convertxml.md) @@ -249,12 +259,12 @@ - [@ohos.util.Vector](js-apis-vector.md) - [@ohos.worker](js-apis-worker.md) - [@ohos.xml](js-apis-xml.md) - + - Test - [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.uitest](js-apis-uitest.md) - + - APIs No Longer Maintained - [@ohos.bytrace](js-apis-bytrace.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 20e8f1573b48402b5561e69c1a67ac0c6a1dd9ea..409cb84c143a04dc46ec010fe9323f009b66c7ab 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1,14 +1,14 @@ # Bundle -The **Bundle** module provides APIs for querying bundle information, application information, abilities, Extension abilities, and application states. +The **Bundle** module provides APIs for querying the information about bundles, applications, abilities, Extension abilities, and application states. > **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. > API version 9 is a canary version for trial use. The APIs of this version may be unstable. ## Modules to Import -``` +```js import bundle from '@ohos.bundle'; ``` @@ -23,8 +23,9 @@ SystemCapability.BundleManager.BundleFramework | ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified application. | | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all applications.| | ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall applications. | +| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status. | -For details, see “Permission Levels” in [Access Control Overview](../../security/accesstoken-overview.md). +For details, see "Permission Levels" in [Access Control Overview](../../security/accesstoken-overview.md). ## bundle.getApplicationInfo @@ -44,7 +45,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | @@ -68,8 +69,6 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId) }) ``` - - ## bundle.getApplicationInfo getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\): void @@ -88,7 +87,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | @@ -108,7 +107,6 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId, (err, data) => { }) ``` - ## bundle.getApplicationInfo getApplicationInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void @@ -127,7 +125,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | @@ -145,7 +143,6 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { }) ``` - ## bundle.getAllBundleInfo getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> @@ -186,8 +183,6 @@ bundle.getAllBundleInfo(bundleFlag, userId) }) ``` - - ## bundle.getAllBundleInfo getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void @@ -222,7 +217,6 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { }) ``` - ## bundle.getAllBundleInfo getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void @@ -259,8 +253,6 @@ bundle.getAllBundleInfo(bundleFlag, userId, (err, data) => { }) ``` - - ## bundle.getBundleInfo getBundleInfo(bundleName: string, bundleFlags: number, options?: BundleOptions): Promise\ @@ -279,7 +271,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | @@ -305,8 +297,6 @@ bundle.getBundleInfo(bundleName, bundleFlags, options) }) ``` - - ## bundle.getBundleInfo getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void @@ -325,7 +315,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | @@ -362,7 +352,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | @@ -384,6 +374,466 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { }) ``` +## bundle.getBundleInstaller + +getBundleInstaller(): Promise<BundleInstaller>; + +Obtains the installation package information. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | -------------------------------------------- | +| Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Promise used to return the installation package information.| + +## bundle.getBundleInstaller + +getBundleInstaller(callback: AsyncCallback<BundleInstaller>): void; + +Obtains the installation package information. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------- | +| callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Yes | Callback used to return the installation package information.| + +## bundle.cleanBundleCacheFiles8+ + +cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback<void>): void; + +Clears the cache data of an application. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.REMOVE_CACHE_FILES + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------- | ---- | ------------------------------------- | +| bundleName | string | Yes | Bundle name of an application.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +## bundle.cleanBundleCacheFiles8+ + +cleanBundleCacheFiles(bundleName: string): Promise<void> + +Clears the cache data of an application. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.REMOVE_CACHE_FILES + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------------------------------- | +| bundleName | string | Yes | Bundle name of an application.| + +**Return value** + +| Type | Description | +| ------------- | ------------------------------------ | +| Promise\ | Promise that returns no value.| + +## bundle.setApplicationEnabled8+ + +setApplicationEnabled(bundleName: string, isEnable: boolean, callback: AsyncCallback<void>): void; + +Sets whether to enable an application. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------- | ---- | ----------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +## bundle.setApplicationEnabled8+ + +setApplicationEnabled(bundleName: string, isEnable: boolean): Promise<void> + +Sets whether to enable an application. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ----------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------- | ------------------------------------ | +| Promise\ | Promise that returns no value.| + +## bundle.setAbilityEnabled8+ + +setAbilityEnabled(info: AbilityInfo, isEnable: boolean, callback: AsyncCallback<void>): void; + +Sets whether to enable an ability. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ----------------------------------------------- | +| info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. | +| isEnable | boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +## bundle.setAbilityEnabled8+ + +setAbilityEnabled(info: AbilityInfo, isEnable: boolean): Promise<void> + +Sets whether to enable an ability. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ----------------------------------------------- | +| info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. | +| isEnable | boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------- | ------------------------------------ | +| Promise\ | Promise that returns no value.| + +## bundle.getPermissionDef8+ + +getPermissionDef(permissionName: string, callback: AsyncCallback<PermissionDef>): void; + +Obtains the permission details by permission name. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| permissionName | string | Yes | Name of the permission. | +| callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef)> | Yes | Callback used to return the permission details.| + +## bundle.getPermissionDef8+ + +getPermissionDef(permissionName: string): Promise<PermissionDef> + +Obtains the permission details by permission name. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ---------------- | +| permissionName | string | Yes | Name of the permission.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------------ | +| Promise<[PermissionDef](js-apis-bundle-PermissionDef)> | Promise used to return the permission details.| + +## bundle.setModuleUpgradeFlag9+ + +setModuleUpgradeFlag(bundleName: string, moduleName: string, upgradeFlag: UpgradeFlag, callback: AsyncCallback<void>):void; + +Sets whether the module needs an upgrade. This API uses an asynchronous callback to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ---------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| moduleName | string | Yes | Module name of the application. | +| upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is used only by the internal system. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +## bundle.setModuleUpgradeFlag9+ + +setModuleUpgradeFlag(bundleName: string, moduleName: string, upgradeFlag: UpgradeFlag): Promise<void> + +Sets whether the module needs an upgrade. This API uses a promise to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ---------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| moduleName | string | Yes | Module name of the application. | +| upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is used only by the internal system.| + +**Return value** + +| Type | Description | +| ------------- | ------------------------------------ | +| Promise\ | Promise that returns no value.| + +## bundle.isModuleRemovable9+ + +isModuleRemovable(bundleName: string, moduleName: string, callback: AsyncCallback<boolean>): void; + +Checks whether a module is removable. This API uses an asynchronous callback to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | --------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| moduleName | string | Yes | Module name of the application. | +| callback | AsyncCallback | Yes | Callback used to return the result. If the module is removable, **true** is returned. Otherwise, **false** is returned.| + +## bundle.isModuleRemovable9+ + +isModuleRemovable(bundleName: string, moduleName: string): Promise<boolean> + +Checks whether a module is removable. This API uses a promise to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| moduleName | string | Yes | Module name of the application.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------------------- | +| Promise | Promise used to return the result. If the module is removable, **true** is returned. Otherwise, **false** is returned.| + +## bundle.getBundlePackInfo9+ + +getBundlePackInfo(bundleName: string, bundlePackFlag : pack.BundlePackFlag, callback: AsyncCallback<pack.BundlePackInfo>): void; + +Obtains the bundle package information based on a given bundle name and bundle flags. This API uses an asynchronous callback to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------- | ---- | ---------------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package. | +| callback | AsyncCallback | Yes | Callback used to return the bundle package information.| + +## bundle.getBundlePackInfo9+ + +getBundlePackInfo(bundleName: string, bundlePackFlag : pack.BundlePackFlag): Promise<pack.BundlePackInfo>; + +Obtains the bundle package information based on a given bundle name and bundle flags. This API uses a promise to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------- | ---- | ---------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package.| + +**Return value** + +| Type | Description | +| ---------------------------- | ----------------------------------- | +| Promise | Promise used to return the bundle package information.| + +## bundle.getDispatcherVersion9+ + +getDispatcherVersion(callback: AsyncCallback<DispatchInfo>): void; + +Obtains the dispatcher version. This API uses an asynchronous callback to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[DispatchInfo](js-apis-dispatchInfo.md)> | Yes | Callback used to return the [DispatchInfo](js-apis-dispatchInfo.md).| + +## bundle.getDispatcherVersion9+ + +getDispatcherVersion(): Promise<DispatchInfo>; + +Obtains the dispatcher version. This API uses a promise to return the result. + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type | Description | +| ------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[DispatchInfo](js-apis-dispatchInfo.md)> | Promise used to return the [DispatchInfo](js-apis-dispatchInfo.md).| ## bundle.getAllApplicationInfo @@ -584,7 +1034,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| **Return value** @@ -624,7 +1074,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| @@ -659,7 +1109,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | moduleName | string | Yes | Module name of the application. | | abilityName | string | Yes | Ability name.| @@ -701,7 +1151,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | moduleName | string | Yes | Module name of the application. | | abilityName | string | Yes | Ability name.| | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| @@ -739,7 +1189,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| **Return value** @@ -779,7 +1229,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ---------------------- | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| | callback | AsyncCallback\ | Yes | Callback used to return the application name. | @@ -814,7 +1264,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | moduleName | string | Yes | Module name of the application. | | abilityName | string | Yes | Ability name.| @@ -856,7 +1306,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ---------------------- | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | moduleName | string | Yes | Module name of the application. | | abilityName | string | Yes | Ability name.| | callback | AsyncCallback\ | Yes | Callback used to return the application name. | @@ -959,7 +1409,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name of an application.| **Return value** @@ -993,7 +1443,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ----------------------- | ---- | --------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -1156,7 +1606,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name of an application.| **Return value** | Type | Description | @@ -1193,7 +1643,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | -------------------- | ---- | ------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the **Want** object.| **Example** @@ -1278,7 +1728,7 @@ bundle.getNameForUid(uid, (err, data) => { getAbilityIcon(bundleName: string, abilityName: string): Promise\; -Obtains the [PixelMap](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses a promise to return the result. +Obtains the [pixel map](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** @@ -1298,7 +1748,7 @@ SystemCapability.BundleManager.BundleFramework **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the [PixelMap](js-apis-image.md).| +| Promise\ | Promise used to return the [pixel map](js-apis-image.md).| **Example** @@ -1317,7 +1767,7 @@ bundle.getAbilityIcon(bundleName, abilityName) getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void; -Obtains the [PixelMap](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses an asynchronous callback to return the result. +Obtains the [pixel map](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -1333,7 +1783,7 @@ SystemCapability.BundleManager.BundleFramework | ----------- | ---------------------------------------- | ---- | ---------------------------------------- | | bundleName | string | Yes | Bundle name based on which the pixel map is to obtain. | | abilityName | string | Yes | Ability name based on which the pixel map is to obtain. | -| callback | AsyncCallback\ | Yes | Callback used to return the [PixelMap](js-apis-image.md).| +| callback | AsyncCallback\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| **Example** @@ -1353,11 +1803,11 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { getAbilityIcon(bundleName: string, moduleName: string, abilityName: string): Promise\; -Obtains the [PixelMap](js-apis-image.md) of the icon corresponding to a given bundle name, module name, and ability name. This API uses a promise to return the result. +Obtains the [pixel map](js-apis-image.md) of the icon corresponding to a given bundle name, module name, and ability name. This API uses a promise to return the result. **Required permissions** -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO **System capability** @@ -1374,7 +1824,7 @@ SystemCapability.BundleManager.BundleFramework **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the [PixelMap](js-apis-image.md).| +| Promise\ | Promise used to return the [pixel map](js-apis-image.md).| **Example** @@ -1394,11 +1844,11 @@ bundle.getAbilityIcon(bundleName, moduleName, abilityName) getAbilityIcon(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\): void; -Obtains the [PixelMap](js-apis-image.md) of the icon corresponding to a given bundle name, module name, and ability name. This API uses an asynchronous callback to return the result. +Obtains the [pixel map](js-apis-image.md) of the icon corresponding to a given bundle name, module name, and ability name. This API uses an asynchronous callback to return the result. **Required permissions** -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO **System capability** @@ -1411,7 +1861,7 @@ SystemCapability.BundleManager.BundleFramework | bundleName | string | Yes | Bundle name based on which the pixel map is to obtain. | | moduleName | string | Yes | Module name based on which the pixel map is to obtain. | | abilityName | string | Yes | Ability name based on which the pixel map is to obtain. | -| callback | AsyncCallback\ | Yes | Callback used to return the [PixelMap](js-apis-image.md).| +| callback | AsyncCallback\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| **Example** @@ -1528,7 +1978,7 @@ Obtains the Extension ability information based on a given want. This API uses a **Required permissions** -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO **System capability** @@ -1693,6 +2143,142 @@ bundle.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataNa }) ``` +## bundle.setDisposedStatus9+ + +setDisposedStatus(bundleName: string, status: number, callback: AsyncCallback\): void; + +Sets the disposal status for an application based on a given bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| status | number | Yes | Disposal status to set. This parameter is reserved for the application market. The default value is **0**, indicating that no disposal is performed. | +| callback | AsyncCallback\ | Yes | Callback that returns no value. | + +**Example** + +```js +let bundleName = 'com.ohos.camera'; +let status = 1; +const caller = function callback(err, data) { + console.error('Operation err is: ' + err); + console.error('Operation result is: ' + data); +} +bundle.setDisposedStatus(bundleName, status, caller) +``` + +## bundle.setDisposedStatus9+ + +setDisposedStatus(bundleName: string, status: number): Promise\; + +Sets the disposal status for an application based on a given bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| status | number | Yes | Disposal status to set. This parameter is reserved for the application market. The default value is **0**, indicating that no disposal is performed. | + +**Return value** + +| Type | Description | +| ------------------------------------- | ------------------------------ | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +let bundleName = 'com.ohos.camera'; +let status = 1; + +bundle.setDisposedStatus(bundleName, status).then(data=>{ + console.error('Operation result is: ' + data); +}).catch(err=>{ + console.error('Operation err is: ' + err); +}) +``` + +## bundle.getDisposedStatus9+ + +getDisposedStatus(bundleName: string, callback: AsyncCallback\): void; + +Obtains the disposal status of an application based on a given bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| callback | AsyncCallback\ | Yes | Callback used to return the disposal status. | + +**Example** + +```js +let bundleName = 'com.ohos.camera'; +const caller = function callback(err, data) { + console.error('Operation err is: ' + err); + console.error('Operation result is: ' + data); +} +bundle.getDisposedStatus(bundleName, caller) +``` + +## bundle.getDisposedStatus9+ + +getDisposedStatus(bundleName: string): Promise\; + +Obtains the disposal status of an application based on a given bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_DISPOSED_APP_STATUS + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | + +**Return value** + +| Type | Description | +| ------------------------------------- | ------------------------------ | +| Promise\ | Promise used to return the disposal status.| + +**Example** + +```js +let bundleName = 'com.ohos.camera'; + +bundle.getDisposedStatus(bundleName).then(data=>{ + console.error('Operation result is: ' + data); +}).catch(err=>{ + console.error('Operation err is: ' + err); +}) +``` + ## InstallErrorCode **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1779,15 +2365,15 @@ Enumerates display orientations. | LANDSCAPE | None | Landscape orientation. | | PORTRAIT | None | Portrait orientation. | | FOLLOW_RECENT | None | Orientation same as that of the nearest ability in the stack.| -| LANDSCAPE_INVERTED |None | Reverse landscape orientation. | -| PORTRAIT_INVERTED |None | Reverse portrait orientation. | -| AUTO_ROTATION |None | Orientation determined by the sensor. | -| AUTO_ROTATION_LANDSCAPE |None | Orientation determined by the sensor in the horizontal direction, including landscape and reverse landscape. | -| AUTO_ROTATION_PORTRAIT |None | Orientation determined by the sensor in the vertical direction, including portrait and reverse portrait. | -| AUTO_ROTATION_RESTRICTED |None | Orientation determined by the sensor when the sensor switch is enabled. | -| AUTO_ROTATION_LANDSCAPE_RESTRICTED |None | Orientation determined by the sensor in the horizontal direction, including landscape and reverse landscape, when the sensor switch is enabled. | -| AUTO_ROTATION_PORTRAIT_RESTRICTED |None | Orientation determined by the sensor in the vertical direction, including portrait and reverse portrait, when the sensor switch is enabled. | -| LOCKED |None | Auto rotate locked. | +| LANDSCAPE_INVERTED9+ |None | Reverse landscape orientation. | +| PORTRAIT_INVERTED9+ |None | Reverse portrait orientation. | +| AUTO_ROTATION9+ |None | Orientation determined by the sensor. | +| AUTO_ROTATION_LANDSCAPE9+ |None | Orientation determined by the sensor in the horizontal direction, including landscape and reverse landscape. | +| AUTO_ROTATION_PORTRAIT9+ |None | Orientation determined by the sensor in the vertical direction, including portrait and reverse portrait. | +| AUTO_ROTATION_RESTRICTED9+ |None | Orientation determined by the sensor when the sensor switch is enabled. | +| AUTO_ROTATION_LANDSCAPE_RESTRICTED9+ |None | Orientation determined by the sensor in the horizontal direction, including landscape and reverse landscape, when the sensor switch is enabled. | +| AUTO_ROTATION_PORTRAIT_RESTRICTED9+ |None | Orientation determined by the sensor in the vertical direction, including portrait and reverse portrait, when the sensor switch is enabled. | +| LOCKED9+ |None | Auto rotate disabled. | ## LaunchMode Enumerates launch modes. @@ -1827,9 +2413,12 @@ Enumerates Extension ability types. | FILE_SHARE9+ | 6 | File sharing included.| | STATIC_SUBSCRIBER9+ | 7 | Subscribers included. | | WALLPAPER9+ | 8 | Wallpaper included. | -| BACKUP9+ | 9 | Data backup and restore included.| +| BACKUP9+ | 9 | Data backup and restore included.| +| WINDOW9+ | 10 | Window type extension information included.| | ENTERPRISE_ADMIN9+ | 11 | Enterprise administrators included. | -| UNSPECIFIED9+ | 20 | Unspecified type. | +| THUMBNAIL9+ | 13 | Thumbnails included.| +| PREVIEW9+ | 14 | Preview included.| +| UNSPECIFIED9+ | 255 | Unspecified type. | ## ExtensionFlag9+ @@ -1876,6 +2465,20 @@ Enumerates window modes. | Name | Type | Description | | ------------------ | ---- | ---- | -| FULLSCREEN | None | Full screen.| -| SPLIT | None | Split-screen. | -| FLOATING | None | Floating. | +| FULL_SCREEN9+ | 0 | Full screen.| +| SPLIT9+ | 1 | Split-screen. | +| FLOATING9+ | 2 | Floating. | + +## UpgradeFlag + +Enumerates the upgrade flags, which are for internal use only. + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Value | Description | +| ----------------------------- | ---- | ---------------- | +| NOT_UPGRADE9+ | 0 | No module needs an upgrade. | +| SINGLE_UPGRADE9+ | 1 | A single module needs an upgrade.| +| RELATION_UPGRADE9+ | 2 | The module that has a relationship with the current one needs an upgrade.| diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index 7e947ddbe0194fabeb31d1c10c44eab0dcfe1550..ce415ad942510c481755380bdd90adb7eb1c75ae 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -1,19 +1,16 @@ # Context +The **Context** module provides context for abilities or applications. It allows access to application-specific resources, as well as permission requests and verification. + > **NOTE** -> -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the FA model. -## Modules to Import - -```js -import featureAbility from '@ohos.ability.featureAbility' -``` - ## Usage -The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the Context module. An example is as follows: +The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: ```js import featureAbility from '@ohos.ability.featureAbility' @@ -91,7 +88,7 @@ Verifies whether a specific PID and UID have the given permission. This API uses | ---------- | --------------------------------------- | ---- | ------------------------------------- | | permission | string | Yes | Name of the permission to verify. | | options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -119,7 +116,7 @@ Verifies whether the current PID and UID have the given permission. This API use | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | ------------------------------------- | | permission | string | Yes | Name of the permission to verify. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -148,7 +145,7 @@ Verifies whether a specific PID and UID have the given permission. This API uses | Type | Description | | ---------------- | ----------------------------------------------------------- | -| Promise\ | Promise used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| +| Promise\ | Promise used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -255,7 +252,7 @@ context.getApplicationInfo().then((data) => { getBundleName(callback: AsyncCallback\): void -Obtains the bundle name of the current ability. This API uses an asynchronous callback to return the result. +Obtains the bundle name of this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -279,7 +276,7 @@ context.getBundleName() getBundleName(): Promise\ -Obtains the bundle name of the current ability. This API uses a promise to return the result. +Obtains the bundle name of this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -300,6 +297,225 @@ context.getBundleName().then((data) => { }); ``` +## Context.getDisplayOrientation7+ + +getDisplayOrientation(callback: AsyncCallback\): void + +Obtains the display orientation of this ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------- | +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getDisplayOrientation() +``` + +## Context.getDisplayOrientation7+ + +getDisplayOrientation(): Promise\; + +Obtains the display orientation of this ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------- | ------------------------- | +| Promise\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Promise used to return the display orientation.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getDisplayOrientation().then((data) => { + console.info("=======================>getDisplayOrientationCallback====================>"); + console.info("====>data====>" + JSON.stringify(data)); +}); +``` + +## Context.setDisplayOrientation7+ + +setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback\): void + +Obtains the display orientation for this ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------- | +| orientation | [bundle.DisplayOrientation](js-apis-bundle.md#displayorientation) | Yes | Display orientation to set.| +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +import bundle from '@ohos.bundle' +var context = featureAbility.getContext(); +var orientation=bundle.DisplayOrientation.UNSPECIFIED +context.setDisplayOrientation(orientation, (err) => { + console.log('---------- setDisplayOrientation fail, err: -----------', err); +}); +``` + +## Context.setDisplayOrientation7+ + +setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise\; + +Obtains the display orientation for this ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------- | ------------------------- | +| orientation | [bundle.DisplayOrientation](js-apis-bundle.md#displayorientation) | Yes | Display orientation to set.| +| Promise\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Promise used to return the display orientation.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +import bundle from '@ohos.bundle' +var context = featureAbility.getContext(); +var orientation=bundle.DisplayOrientation.UNSPECIFIED +context.setDisplayOrientation(orientation).then((data) => { + console.info("=======================>setDisplayOrientationCallback====================>"); + console.info("====>data====>" + JSON.stringify(data)); +}); +``` + +## Context.setShowOnLockScreen7+ + +setShowOnLockScreen(show: boolean, callback: AsyncCallback\): void + +Sets whether to show this feature at the top of the lock screen each time the lock screen is displayed so that the feature remains activated. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------- | +| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +var show=true +context.setShowOnLockScreen(show, (err) => { + console.log('---------- setShowOnLockScreen fail, err: -----------', err); +}); +``` + +## Context.setShowOnLockScreen7+ + +setShowOnLockScreen(show: boolean): Promise\; + +Sets whether to show this feature at the top of the lock screen each time the lock screen is displayed so that the feature remains activated. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------- | +| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------- | +| Promise\| Promise used to return the result.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +var show=true +context.setShowOnLockScreen(show).then((data) => { + console.info("=======================>setShowOnLockScreenCallback====================>"); + console.info("====>data====>" + JSON.stringify(data)); +}); +``` + +## Context.setWakeUpScreen7+ + +setWakeUpScreen(wakeUp: boolean, callback: AsyncCallback\): void + +Sets whether to wake up the screen when this feature is restored. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +var wakeUp=true +context.setWakeUpScreen(wakeUp, (err) => { + console.log('---------- setWakeUpScreen fail, err: -----------', err); +}); +``` + +## Context.setWakeUpScreen7+ + +setWakeUpScreen(wakeUp: boolean): Promise\; + +Sets whether to wake up the screen when this feature is restored. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------- | +| Promise\| Promise used to return the result.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +var wakeUp=true +context.setWakeUpScreen(wakeUp).then((data) => { + console.info("=======================>setWakeUpScreenCallback====================>"); + console.info("====>data====>" + JSON.stringify(data)); +}); +``` + + ## Context.getProcessInfo7+ @@ -357,7 +573,7 @@ context.getProcessInfo().then((data) => { getElementName(callback: AsyncCallback\): void -Obtains the **ohos.bundle.ElementName** object of the current ability. This API uses an asynchronous callback to return the result. +Obtains the **ohos.bundle.ElementName** object of this ability. This API uses an asynchronous callback to return the result. This API is available only to Page abilities. @@ -383,7 +599,7 @@ context.getElementName() getElementName(): Promise\ -Obtains the **ohos.bundle.ElementName** object of the current ability. This API uses a promise to return the result. +Obtains the **ohos.bundle.ElementName** object of this ability. This API uses a promise to return the result. This API is available only to Page abilities. @@ -510,7 +726,7 @@ context.getCallingBundle().then((data) => { getCacheDir(callback: AsyncCallback\): void -Obtains the cache directory of the application on the internal storage. This API uses an asynchronous callback to return the result. +Obtains the cache directory of the application in the internal storage. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -538,7 +754,7 @@ context.getCacheDir((err, data) => { getCacheDir(): Promise\ -Obtains the cache directory of the application on the internal storage. This API uses a promise to return the result. +Obtains the cache directory of the application in the internal storage. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -563,7 +779,7 @@ context.getCacheDir().then((data) => { getFilesDir(callback: AsyncCallback\): void -Obtains the file directory of the application on the internal storage. This API uses an asynchronous callback to return the result. +Obtains the file directory of the application in the internal storage. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -591,7 +807,7 @@ context.getFilesDir((err, data) => { getFilesDir(): Promise\ -Obtains the file directory of the application on the internal storage. This API uses a promise to return the result. +Obtains the file directory of the application in the internal storage. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -732,7 +948,7 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[HapModuleInfo](#hapmoduleinfo)> | Yes | Callback used to return the **ModuleInfo** object.| +| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| **Example** @@ -760,7 +976,7 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to | Type | Description | | --------------- | ------------------------- | -| Promise\<[HapModuleInfo](#hapmoduleinfo)> | Promise used to return the **ModuleInfo** object.| +| Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| **Example** @@ -774,9 +990,9 @@ context.getHapModuleInfo().then((data) => { ## Context.getAppVersionInfo7+ -getAppVersionInfo(callback: AsyncCallback\): void +getAppVersionInfo(callback: AsyncCallback\): void -Obtains the version information of the application. This API uses an asynchronous callback to return the result. +Obtains the version information of this application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -804,7 +1020,7 @@ context.getAppVersionInfo((err, data) => { getAppVersionInfo(): Promise\ -Obtains the version information of the application. This API uses a promise to return the result. +Obtains the version information of this application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -828,7 +1044,7 @@ context.getAppVersionInfo().then((data) => { getAbilityInfo(callback: AsyncCallback\): void -Obtains information of the current ability. This API uses an asynchronous callback to return the result. +Obtains information about this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -856,7 +1072,7 @@ context.getAbilityInfo((err, data) => { getAbilityInfo(): Promise\ -Obtains information of the current ability. This API uses a promise to return the result. +Obtains information about this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -897,6 +1113,111 @@ import featureAbility from '@ohos.ability.featureAbility' var context = featureAbility.getContext().getApplicationContext(); ``` +## Context.isUpdatingConfigurations7+ + +isUpdatingConfigurations(callback: AsyncCallback\): void; + +Checks whether the configuration of this ability is being changed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the configuration of the capability is being changed; returns **false** otherwise.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.isUpdatingConfigurations((err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. Data:' + JSON.stringify(data)); +}); +``` + +## Context.isUpdatingConfigurations7+ + +isUpdatingConfigurations(): Promise\; + +Checks whether the configuration of this ability is being changed. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| --------------- | ------------------------- | +|Promise\ | Returns **true** if the configuration of the capability is being changed; returns **false** otherwise.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.isUpdatingConfigurations().then((data) => { + console.info("====>data====>" + JSON.stringify(data)); +}); +``` + +## Context.printDrawnCompleted7+ + +printDrawnCompleted(callback: AsyncCallback\): void; + +Notifies the system of the time required to draw this page function. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.printDrawnCompleted((err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. Data:' + JSON.stringify(data)); +}); +``` + +## Context.printDrawnCompleted7+ + +printDrawnCompleted(): Promise\; + +Notifies the system of the time required to draw this page function. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| --------------- | ------------------------- | +|Promise\ | Promise used to return the result.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.printDrawnCompleted().then((data) => { + console.info("====>data====>" + JSON.stringify(data)); +}); +``` + + ## PermissionOptions7+ **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -916,31 +1237,10 @@ var context = featureAbility.getContext().getApplicationContext(); | permissions | Read-only | Array\ | Yes | Permissions requested. | | authResults | Read-only | Array\ | Yes | Permission request result. | -## HapModuleInfo7+ - -Describes the HAP module information. - -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | No | Module name. | -| description | string | Yes | No | Module description. | -| descriptionId | number | Yes | No | Module description ID. | -| icon | string | Yes | No | Module icon. | -| label | string | Yes | No | Module label. | -| labelId | number | Yes | No | Module label ID. | -| iconId | number | Yes | No | Module icon ID. | -| backgroundImg | string | Yes | No | Module background image. | -| supportedModes | number | Yes | No | Running modes supported by the module. | -| reqCapabilities | Array\ | Yes | No | Capabilities required for module running.| -| deviceTypes | Array\ | Yes | No | Device types supported by the module.| -| abilityInfo | Array\ | Yes | No | Ability information. | -| moduleName | string | Yes | No | Module name. | -| mainAbilityName | string | Yes | No | Name of the main ability. | -| installationFree | boolean | Yes | No | Whether installation-free is supported. | -| mainElementName | string | Yes| No| Information about the main ability.| - ## AppVersionInfo7+ +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + | Name | Type| Readable | Writable | Description| | ------ | ------ | ------| ------ | ------ | | appName | string | Yes | No | Module name. | diff --git a/en/application-dev/reference/apis/js-apis-DataUriUtils.md b/en/application-dev/reference/apis/js-apis-DataUriUtils.md index 584b7e1285c0087bc1109bd32d50eb1143360df1..18cfa0cdc0c54ea8e8aa85fc43fcf61b3d63fc7a 100644 --- a/en/application-dev/reference/apis/js-apis-DataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-DataUriUtils.md @@ -1,4 +1,6 @@ -# DataUriUtils Module +# DataUriUtils + +The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index 5b7866478f7f527ceb806b2aec083bd21835800a..06cac3878b46d62fdc09e6a342bdcc9340714c4f 100644 --- a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -1,18 +1,22 @@ -# EnterpriseAdminExtentionAbility +# EnterpriseAdminExtensionAbility -The **EnterpriseAdminExtentionAbility** module provides APIs for Extension abilities of enterprise administrators. +The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators. + +To have the capabilities provided by the module, for example, receiving the application activation or deactivation notification sent by the system, an enterprise administrator application must have an **EnterpriseAdminExtensionAbility** instance and override the APIs in it. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the stage model. + ## Modules to Import ```ts -import EnterpriseAdminExtentionAbility from '@ohos.EnterpriseAdminExtentionAbility' +import EnterpriseAdminExtensionAbility from '@ohos.EnterpriseAdminExtensionAbility' ``` -## EnterpriseAdminExtentionAbility.onAdminEnabled +## EnterpriseAdminExtensionAbility.onAdminEnabled onAdminEnabled(): void @@ -22,14 +26,14 @@ Called when an enterprise administrator is enabled. **Example** - ```ts +```ts export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { - onAdminEnabled() { - } + onAdminEnabled() { + } }; - ``` +``` -## EnterpriseAdminExtentionAbility.onAdminDisabled +## EnterpriseAdminExtensionAbility.onAdminDisabled onAdminDisabled(): void @@ -38,11 +42,10 @@ Called when an enterprise administrator is disabled. **System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Example** - - ```ts +```ts export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { - onAdminDisabled() { - } + onAdminDisabled() { + } }; - ``` +``` diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index b858d93cbd061d4f1df583ac9d4045e152105b7a..e2333a523a918e229c6a35c4e341df9383bfb26a 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -1,17 +1,14 @@ # AbilityContext +The **AbilityContext** module, inherited from **Context**, implements the context for abilities. + +This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a pop-up window. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Implements the ability context. This module is inherited from **Context**. - -## Modules to Import - -```js -import Ability from '@ohos.application.Ability' -``` ## Usage Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. @@ -25,7 +22,6 @@ class MainAbility extends Ability { } ``` - ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -34,16 +30,18 @@ class MainAbility extends Ability { | -------- | -------- | -------- | -------- | -------- | | abilityInfo | AbilityInfo | Yes| No| Ability information.| | currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| - +| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration information.| ## AbilityContext.startAbility startAbility(want: Want, callback: AsyncCallback<void>): void -Starts an ability. This API uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -69,10 +67,12 @@ Starts an ability. This API uses a callback to return the result. startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void -Starts an ability. This API uses a callback to return the result. +Starts an ability with start options specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -106,6 +106,8 @@ Starts an ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -143,7 +145,7 @@ Starts an ability. This API uses a promise to return the result. startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses a callback to return the result when the ability is terminated. +Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -171,7 +173,7 @@ Starts an ability. This API uses a callback to return the result when the abilit startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses a callback to return the result when the ability is terminated. +Starts an ability with start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -235,12 +237,134 @@ Starts an ability. This API uses a promise to return the result when the ability }) ``` +## AbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback): void; + +Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startAbilityWithAccount(want, accountId, (err, data) => { + console.log('---------- startAbilityWithAccount fail, err: -----------', err); + console.log('---------- startAbilityWithAccount success, data: -----------', data); + }); + ``` + + +## AbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; + +Starts an ability with start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0, + }; + this.context.startAbilityForResultWithAccount(want, accountId, options, (err) => { + console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); + }); + ``` + + + ## AbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; + +Starts an ability with start options specified. This API uses a promise to return the result when the account of the ability is destroyed. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<AbilityResult> | Promise used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0, + }; + this.context.startAbilityForResultWithAccount(want, accountId, options) + .then((data) => { + console.log('---------- startAbilityForResultWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); + }) + ``` + ## AbilityContext.terminateSelf terminateSelf(callback: AsyncCallback<void>): void; -Terminates this ability. This API uses a callback to return the result. +Terminates this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -248,7 +372,7 @@ Terminates this ability. This API uses a callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -271,12 +395,12 @@ Terminates this ability. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result indicating whether the API is successfully called.| +| Promise<void> | Promise used to return the result.| **Example** ```js - this.context.terminateSelf(want).then((data) => { + this.context.terminateSelf().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); @@ -288,7 +412,7 @@ Terminates this ability. This API uses a promise to return the result. terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses a callback to return the information to the caller of **startAbilityForResult**. +Terminates this ability. This API uses an asynchronous callback to return the information to the caller of **startAbilityForResult**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -346,6 +470,149 @@ Terminates this ability. This API uses a promise to return information to the ca ) ``` +## AbilityContext.connectAbility + +connectAbility(want: Want, options: ConnectOptions): number; + +Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Remote object instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Result code of the ability connection.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var options = { + onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, + onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, + onFailed(code) { console.log('----------- onFailed -----------') } + } + const result = this.context.connectAbility(want, options); + console.log('----------- connectAbilityResult: ------------', result); + ``` + + +## AbilityContext.connectAbilityWithAccount + +connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; + +Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Parameters for the connection.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Result code of the ability connection.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, + onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, + onFailed(code) { console.log('----------- onFailed -----------') } + } + const result = this.context.connectAbilityWithAccount(want, accountId, options); + console.log('----------- connectAbilityResult: ------------', result); + ``` + +## AbilityContext.disconnectAbility + +disconnectAbility(connection: number): Promise\; + +Disconnects a connection. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Result code of the ability connection.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```js + var connectionNumber = 0; + this.context.disconnectAbility(connectionNumber).then((data) => { + console.log('disconnectAbility success, data: ', data); + }).catch((err) => { + console.log('disconnectAbility fail, err: ', err); + }); + ``` + +## AbilityContext.disconnectAbility + +disconnectAbility(connection: number, callback:AsyncCallback\): void; + +Disconnects a connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Result code of the ability connection.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var connectionNumber = 0; + this.context.disconnectAbility(connectionNumber, (err) => { + console.log('---------- disconnectAbility fail, err: -----------', err); + }); + ``` ## AbilityContext.startAbilityByCall @@ -388,12 +655,126 @@ Obtains the caller interface of the specified ability, and if the specified abil } ``` +## AbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startAbilityWithAccount(want, accountId, (err) => { + console.log('---------- startAbilityWithAccount fail, err: -----------', err); + }); + ``` + + +## AbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; + +Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0, + }; + this.context.startAbilityWithAccount(want, accountId, options, (err) => { + console.log('---------- startAbilityWithAccount fail, err: -----------', err); + }); + ``` + + +## AbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; + +Starts an ability with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0, + }; + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + console.log('---------- startAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startAbilityWithAccount fail, err: -----------', err); + }) + ``` ## AbilityContext.requestPermissionsFromUser requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; -Requests permissions from the user by displaying a pop-up window. This API uses a callback to return the result. +Requests permissions from the user by displaying a pop-up window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -402,7 +783,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result indicating whether the API is successfully called.| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the permission request result.| **Example** @@ -433,7 +814,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses | Type| Description| | -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result indicating whether the API is successfully called.| +| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the permission request result.| **Example** @@ -452,7 +833,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses setMissionLabel(label: string, callback:AsyncCallback<void>): void; -Sets the label of the ability in the mission. This API uses an asynchronous callback to return the result. +Sets a label for this ability in the mission. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -461,7 +842,7 @@ Sets the label of the ability in the mission. This API uses an asynchronous call | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | label | string | Yes| Label of the ability to set.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -476,7 +857,7 @@ Sets the label of the ability in the mission. This API uses an asynchronous call setMissionLabel(label: string): Promise<void> -Sets the label of the ability in the mission. This API uses a promise to return the result. +Sets a label for this ability in the mission. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -490,7 +871,7 @@ Sets the label of the ability in the mission. This API uses a promise to return | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result indicating whether the API is successfully called.| +| Promise<void> | Promise used to return the result.| **Example** @@ -501,6 +882,117 @@ Sets the label of the ability in the mission. This API uses a promise to return console.log('failed:' + JSON.stringify(error)); }); ``` +## AbilityContext.setMissionIcon + +setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; + +Sets an icon for this ability in the mission. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | image.PixelMap | Yes| Icon of the ability to set.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + import image from '@ohos.multimedia.image' + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; + }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap, (err) => { + console.log('---------- setMissionIcon fail, err: -----------', err); + }) + ``` + + +## AbilityContext.setMissionIcon + +setMissionIcon(icon: image.PixelMap): Promise\; + +Sets an icon for this ability in the mission. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | image.PixelMap | Yes| Icon of the ability to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** + + ```js + import image from '@ohos.multimedia.image' + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; + }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap) + .then((data) => { + console.log('-------------- setMissionIcon success, data: -------------', data); + }) + .catch((err) => { + console.log('-------------- setMissionIcon fail, err: -------------', err); + }); + ``` +## AbilityContext.restoreWindowStage + +restoreWindowStage(localStorage: LocalStorage) : void; + +Restores the window stage data for this ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| localStorage | image.LocalStorage | Yes| Storage used to store the restored window stage.| + +**Example** + + ```js + var storage = new LocalStorage(); + this.context.restoreWindowStage(storage); + ``` ## AbilityContext.isTerminating diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md index cc0197f022957aadb0dd784c1d4ae8c6e0c50005..6a131521d3c447cfb2df65b53a592c5be89678be 100644 --- a/en/application-dev/reference/apis/js-apis-ability-errorCode.md +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -1,8 +1,10 @@ # ErrorCode +The **ErrorCode** module defines the error codes that can be used when the ability is started. + > **NOTE** > -> The initial APIs of this module are supported since API 6. 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 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -12,7 +14,7 @@ import errorCode from '@ohos.ability.errorCode' ## ErrorCode -Defines the error code used when the ability is started. +Defines the error codes used when the ability is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index e1d57d47b1b77f1695f8ec79ac49bfbb22422d05..c2bb08c5314a44dcf6f4ad9246e6ee08a313ecd8 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -1,8 +1,10 @@ # wantConstant +The **wantConstant** module provides the action, entity, and flags used in **Want** objects. + > **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -12,73 +14,75 @@ import wantConstant from '@ohos.ability.wantConstant' ## wantConstant.Action -**System capability**: SystemCapability.Ability.AbilityBase +Enumerates the action constants of the **Want** object. -Lists the permissions. +**System capability**: SystemCapability.Ability.AbilityBase -| Common Event Macro | Common Event Name | Subscriber Permission | +| Name | Value | Description | | ------------ | ------------------ | ---------------------- | -| ACTION_HOME | ohos.want.action.home | None | -| ACTION_DIAL | ohos.want.action.dial | None | -| ACTION_SEARCH | ohos.want.action.search | None | -| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | None | -| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | None | -| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None | -| ACTION_SET_ALARM | ohos.want.action.setAlarm | None | -| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | None | -| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | None | -| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | None | -| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | None | -| ACTION_SEND_SMS | ohos.want.action.sendSms | None | -| ACTION_CHOOSE | ohos.want.action.choose | None | -| ACTION_IMAGE_CAPTURE8+ | ohos.want.action.imageCapture | None | -| ACTION_VIDEO_CAPTUR8+ | ohos.want.action.videoCapture | None | -| ACTION_SELECT | ohos.want.action.select | None | -| ACTION_SEND_DATA | ohos.want.action.sendData | None | -| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | None | -| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | None | -| ACTION_VIEW_DATA | ohos.want.action.viewData | None | -| ACTION_EDIT_DATA | ohos.want.action.editData | None | -| INTENT_PARAMS_INTENT | ability.want.params.INTENT | None | -| INTENT_PARAMS_TITLE | ability.want.params.TITLE | None | -| ACTION_FILE_SELECT7+ | ohos.action.fileSelect | None | -| PARAMS_STREAM7+ | ability.params.stream | None | -| ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | None | +| ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | +| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | +| ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | +| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides radio network settings, for example, Wi-Fi option. | +| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | +| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. | +| ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. | +| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all clock alarms. | +| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. | +| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | +| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | +| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS. | +| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. | +| ACTION_IMAGE_CAPTURE8+ | ohos.want.action.imageCapture | Action of launching the UI for photographing. | +| ACTION_VIDEO_CAPTURE8+ | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | +| ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. | +| ACTION_SEND_DATA | ohos.want.action.sendData | Action of launching the UI for sending a single data record. | +| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | Action of launching the UI for sending multiple data records. | +| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | Action of requesting a media scanner to scan a file and add the file to the media library. | +| ACTION_VIEW_DATA | ohos.want.action.viewData | Action of viewing data. | +| ACTION_EDIT_DATA | ohos.want.action.editData | Action of editing data. | +| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | +| INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. | +| ACTION_FILE_SELECT7+ | ohos.action.fileSelect | Action of selecting a file. | +| PARAMS_STREAM7+ | ability.params.stream | URI of the data stream associated with the target when the data is sent. | +| ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | +| ACTION_MARKER_DOWNLOAD 9+ | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | ## wantConstant.Entity -**System capability**: SystemCapability.Ability.AbilityBase +Enumerates the entity constants of the **Want** object. -Lists the permissions. +**System capability**: SystemCapability.Ability.AbilityBase -| Common Event Macro | Common Event Name | Subscriber Permission | +| Name | Value | Description | | ------------ | ------------------ | ---------------------- | -| ENTITY_DEFAULT | entity.system.default | None | -| ENTITY_HOME | entity.system.homel | None | -| ENTITY_VOICE | ENTITY_VOICE | None | -| ENTITY_BROWSABLE | entity.system.browsable | None | -| ENTITY_VIDEO | entity.system.video | None | -| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None | +| ENTITY_DEFAULT | entity.system.default | Default entity. The default entity is used if no entity is specified. | +| ENTITY_HOME | entity.system.home | Home screen entity. | +| ENTITY_VOICE | entity.system.voice | Voice interaction entity. | +| ENTITY_BROWSABLE | entity.system.browsable | Browser type entity. | +| ENTITY_VIDEO | entity.system.video | Video type entity. | + +## wantConstant.Flags -## flags +Describes flags. **System capability**: SystemCapability.Ability.AbilityBase | Name | Value | Description | | ------------------------------------ | ---------- | ------------------------------------------------------------ | | FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | | FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | | FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | | FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| | FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | | FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | -| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible. | +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | | FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 5a21d564110cdf922e344c52ded3bd8d44604b2f..2b17d252af9d09d5519f36ece4306834e8085c5a 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -1,6 +1,6 @@ # Ability Access Control -Provides program permission management capabilities, including authentication, authorization, and revocation. +The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation. > **NOTE** > @@ -69,6 +69,36 @@ promise.then(data => { }); ``` +### verifyAccessTokenSync9+ + +verifyAccessTokenSync(tokenID: number, permissionName: string): GrantStatus + +Checks whether an application has been granted the specified permission. This API synchronously returns the result. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | ID of the application. | +| permissionName | string | Yes | Name of the permission to verify.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| [GrantStatus](#grantstatus) | Permission grant state.| + +**Example** + +```js +var AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; +let data = verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +console.log(`data->${JSON.stringify(data)}`); +``` + ### grantUserGrantedPermission grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> diff --git a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md index a609e0df688e7a9cc5b32ea25907eda95ab14c47..d30dce2a75e700019c9f44ce1c918a9574f3cea7 100644 --- a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @@ -1,5 +1,7 @@ # AbilityDelegatorRegistry +The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. + > **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. @@ -24,8 +26,6 @@ Enumerates the ability lifecycle states. | BACKGROUND | 3 | The ability is running in the background. | | DESTROY | 4 | The ability is destroyed.| - - ## AbilityDelegatorRegistry.getAbilityDelegator getAbilityDelegator(): AbilityDelegator diff --git a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md index 508463e3a428fffe336de4ae2c986623fb54d3b1..098f4ebba840a13d1f37d6e14256fcc9695f2a8d 100644 --- a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md @@ -1,17 +1,11 @@ # AbilityRunningInfo +The **AbilityRunningInfo** module implements ability running information and ability states. + > **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. -Provides ability running information. - -## Modules to Import - -```js -import abilitymanager from '@ohos.application.abilityManager'; -``` - ## Usage The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**. @@ -27,26 +21,13 @@ abilitymanager.getAbilityRunningInfos((err,data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + | 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](#abilitymanagerabilitystate) | Yes| No| Ability state. | - - -## abilityManager.AbilityState - -Enumerates the ability states. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Value| Description| -| -------- | -------- | -------- | -| INITIAL | 0 | The ability is in the initial state.| -| FOREGROUND | 9 | The ability is in the foreground state. | -| BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding 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-abilitystagecontext.md b/en/application-dev/reference/apis/js-apis-abilitystagecontext.md index 65705aae3936cc2c9e9643f6142be6de6564124b..5475dc51466d01d8eadef472248cce237f1b6241 100644 --- a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md +++ b/en/application-dev/reference/apis/js-apis-abilitystagecontext.md @@ -1,18 +1,14 @@ # AbilityStageContext +The **AbilityStageContext** module, inherited from [Context](js-apis-application-context.md), implements the context of an ability stage. + +This module provides APIs for accessing a specific ability stage. You can use the APIs to obtain the **ModuleInfo** object and environment configuration of an ability stage. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md). - -## Modules to Import - -```js -import AbilityStage from '@ohos.application.AbilityStage'; -``` - ## Usage The ability stage context is obtained through an **AbilityStage** instance. 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-DataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md index c3dd60f0e942f6666ea4023bca50c0cef7e75fa5..3289f1d2efc43a5af0a8fa3266f41b1ff3139aaa 100644 --- a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @@ -1,6 +1,6 @@ # Data Share Extension Ability -**DataShareExtensionAbility** provides extension abilities for data share services based on the ExtensionAbility framework. +The **DataShareExtensionAbility** module provides Extension abilities for data share services. >**NOTE** > @@ -17,11 +17,19 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility' ``` +## Attributes + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [ExtensionContext](js-apis-extension-context.md) | Yes| No|Context of the DataShare Extension ability.| + ## onCreate onCreate?(want: Want, callback: AsyncCallback<void>): void -Called to initialize service logic of the server when the DataShare client connects to the DataShareExtensionAbility server. This API can be overridden as required. +Called by the server to initialize service logic when the DataShare client connects to the DataShareExtensionAbility server. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -45,7 +53,7 @@ let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { - onCreate(want: Want, callback: AsyncCallback) { + onCreate(want, callback) { rdb.getRdbStore(this.context, { name: DB_NAME }, 1, function (err, data) { @@ -66,7 +74,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void -Called by the server to obtain the Multipurpose Internet Mail Extensions (MIME) types supported by a file. This API can be overridden as required. +Obtains the Multipurpose Internet Mail Extensions (MIME) types supported by a file. This API is called by the server and can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -82,7 +90,7 @@ Called by the server to obtain the Multipurpose Internet Mail Extensions (MIME) ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback>) { + getFileTypes(uri, mimeTypeFilter, callback) { let err = {"code":0}; let ret = new Array("type01", "type02", "type03"); callback(err, ret); @@ -94,7 +102,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { openFile?(uri: string, mode: string, callback: AsyncCallback<number>): void -Called by the server to open a file. This method can be overridden as required. +Opens a file. This API is called by the server and can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -103,14 +111,14 @@ Called by the server to open a file. This method can be overridden as required. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------ | | uri | string | Yes | URI of the file to open. | -| mode | string | Yes | File open mode, including read-only mode and read/write mode.| +| mode | string | Yes | File open mode, which can be read-only or read/write.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the file descriptor. | **Example** ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - openFile(uri: string, mode: string, callback: AsyncCallback) { + openFile(uri, mode, callback) { let err = {"code":0}; let fd = 0; callback(err,fd); @@ -122,7 +130,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void -Called to insert data into the database. This API can be overridden as required. +Inserts data into the database. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -137,13 +145,22 @@ Called to insert data into the database. This API can be overridden as required. **Example** ```ts +import rdb from '@ohos.data.rdb'; + +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; +let rdbStore; + export default class DataShareExtAbility extends DataShareExtensionAbility { - insert(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback) { - if (value == null) { + insert(uri, valueBucket, callback) { + if (valueBucket == null) { console.info('invalid valueBuckets'); return; } - rdbStore.insert(TBL_NAME, value, function (err, ret) { + rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) { console.info('callback ret:' + ret); if (callback != undefined) { callback(err, ret); @@ -157,7 +174,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void -Called by the server to update data in the database. This API can be overridden as required. +Updates data in the database. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -166,19 +183,28 @@ Called by the server to update data in the database. This API can be overridden | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri | string | Yes | URI of the data to update.| -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.| | valueBucket | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| New data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of updated data records.| **Example** ```ts +import rdb from '@ohos.data.rdb'; + +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; +let rdbStore; + export default class DataShareExtAbility extends DataShareExtensionAbility { - update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback) { + update(uri, predicates, valueBucket, callback) { if (predicates == null || predicates == undefined) { return; } - rdbStore.update(TBL_NAME, value, predicates, function (err, ret) { + rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) { if (callback != undefined) { callback(err, ret); } @@ -191,7 +217,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void -Called by the server to delete data from the database. This API can be overridden as required. +Deletes data from the database. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -200,14 +226,23 @@ Called by the server to delete data from the database. This API can be overridde | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ---------------------------------- | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of data records deleted.| **Example** ```ts +import rdb from '@ohos.data.rdb'; + +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; +let rdbStore; + export default class DataShareExtAbility extends DataShareExtensionAbility { - delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback) { + delete(uri, predicates, callback) { if (predicates == null || predicates == undefined) { return; } @@ -224,7 +259,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void -Called by the server to query data from the database. This API can be overridden as required. +Queries data from the database. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -233,15 +268,24 @@ Called by the server to query data from the database. This API can be overridden | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri | string | Yes | URI of the data to query.| -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| | columns | Array<string> | Yes| Columns to query. If this parameter is empty, all columns will be queried.| | callback | AsyncCallback<Object> | Yes| Callback invoked to return the result set.| **Example** ```ts +import rdb from '@ohos.data.rdb'; + +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; +let rdbStore; + export default class DataShareExtAbility extends DataShareExtensionAbility { - query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: AsyncCallback) { + query(uri, predicates, columns, callback) { if (predicates == null || predicates == undefined) { return; } @@ -261,7 +305,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { getType?(uri: string, callback: AsyncCallback<string>): void -Called by the server to obtain the MIME type corresponding to the given URI. This API can be overridden as required. +Obtains the MIME type corresponding to the given URI. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -276,7 +320,7 @@ Called by the server to obtain the MIME type corresponding to the given URI. Thi ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - getType(uri: string, callback: AsyncCallback) { + getType(uri, callback) { let err = {"code":0}; let ret = "image"; callback(err, ret); @@ -284,11 +328,11 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { }; ``` -## BatchInsert +## batchInsert -BatchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: AsyncCallback<number>): void +batchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: AsyncCallback<number>): void -Called by the server to insert batch data into the database. This API can be overridden as required. +Batch inserts data into the database. This API is called by the server and can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -303,8 +347,17 @@ Called by the server to insert batch data into the database. This API can be ove **Example** ```ts +import rdb from '@ohos.data.rdb'; + +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; +let rdbStore; + export default class DataShareExtAbility extends DataShareExtensionAbility { - batchInsert(uri: string, valueBuckets: Array, callback: AsyncCallback) { + batchInsert(uri, valueBuckets, callback) { if (valueBuckets == null || valueBuckets.length == undefined) { console.info('invalid valueBuckets'); return; @@ -325,7 +378,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { normalizeUri?(uri: string, callback: AsyncCallback<string>): void -Called by the server to normalize the specified URI. This API can be overridden as required. +Normalizes a URI. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -340,7 +393,7 @@ Called by the server to normalize the specified URI. This API can be overridden ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - normalizeUri(uri: string, callback: AsyncCallback) { + normalizeUri(uri, callback) { let err = {"code":0}; let ret = "normalize+" + uri; callback(err, ret); @@ -352,7 +405,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { denormalizeUri?(uri: string, callback: AsyncCallback<string>): void -Called by the server to denormalize the specified URI. This method can be overridden as required. +Denormalizes a URI. This API can be overridden as required. **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider @@ -361,13 +414,13 @@ Called by the server to denormalize the specified URI. This method can be overri | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ----------------------- | | uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.| -| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, the URI obtained is returned. If the URI passed in is returned, denormalization is not required. If denormalization is not supported, **null** is returned.| +| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, the denormalized URI is returned. If the URI passed in is returned, denormalization is not required. If denormalization is not supported, **null** is returned.| **Example** ```ts export default class DataShareExtAbility extends DataShareExtensionAbility { - denormalizeUri(uri: string, callback: AsyncCallback) { + denormalizeUri(uri, callback) { let err = {"code":0}; let ret = "denormalize+" + uri; callback(err, ret); diff --git a/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md b/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..f0d75fc57deed25160bbb080ef1565a45a94679d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md @@ -0,0 +1,62 @@ +# EnvironmentCallback + +The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + + +## Modules to Import + +```js +import EnvironmentCallback from "@ohos.application.EnvironmentCallback"; +``` + + +## EnvironmentCallback.onConfigurationUpdated + +onConfigurationUpdated(config: Configuration): void; + +Called when the system environment changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-configuration.md) | Yes| **Configuration** object after the change.| + +**Example** + + + ```js +import AbilityStage from "@ohos.application.AbilityStage"; + +var callbackId; + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + globalThis.applicationContext = this.context.getApplicationContext(); + let EnvironmentCallback = { + onConfigurationUpdated(config){ + console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + }, + } + // 1. Obtain an applicationContext object. + let applicationContext = globalThis.applicationContext; + // 2. Register a listener for the environment changes through the applicationContext object. + callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); + console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + } + onDestroy() { + let applicationContext = globalThis.applicationContext; + applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + }); + } +} + ``` diff --git a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md index c850915c4d2743d7ee8f03ce0b96d6a4f7739525..c97515fa2bd988b91c4fd5c27a8e27ed285f141c 100644 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @@ -1,23 +1,39 @@ # MissionSnapshot +The **MissionSnapshot** module provides the mission snapshot information of an ability. + > **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. -Provides the snapshot of a mission. +## Usage -## Modules to Import +The mission snapshot information can be obtained by using **getMissionSnapShot** in **missionManager**. -``` -import missionManager from '@ohos.application.missionManager' +```js import ElementName from '@ohos.bundle'; import image from '@ohos.multimedia.image'; -``` +import missionManager from '@ohos.application.missionManager' + + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + missionManager.getMissionSnapShot("", id, (error, snapshot) => { + console.log("getMissionSnapShot is called, error.code = " + error.code); + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) +``` ## MissionSnapshot Describes the mission snapshot. +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | ability | ElementName | Yes| Yes| Information that matches an ability.| 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 e221f4506244b56ea43e24ef916085ef1f3fac63..d1d7416500d37ab61523633f3880670ad8b98779 100644 --- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md +++ b/en/application-dev/reference/apis/js-apis-application-StartOptions.md @@ -1,12 +1,12 @@ # StartOptions +The **StartOptions** module implements ability startup options. + > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -**StartOptions** is the basic communication component of the system. - ## Modules to Import ``` @@ -15,10 +15,9 @@ import StartOptions from '@ohos.application.StartOptions'; ## Attributes -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore +**System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name| Readable| Writable| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-window.md#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-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md index 26c0cd030bcdf36cee488cba5066b2beba38a3d3..f51fee8402c98f9c36e81f355df105a3154e0105 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -1,11 +1,11 @@ # Want +The **Want** module provides the basic communication component of the system. + > **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. -**Want** is the basic communication component of the system. - ## Modules to Import ``` @@ -20,11 +20,26 @@ import Want from '@ohos.application.Want'; | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | | deviceId | Read only | string | No | ID of the device running the ability. | | bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| -| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | | flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| | action | Read only | string | No | Action option. | -| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. | +| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.js) module can be used to obtain application and bundle information. | | entities | Read only | Array\ | No | List of entities. | -| moduleName9+ | Read only | string | No | Module to which the ability belongs. Different abilities among HAP files in an application may use the same name. If the abilities cannot be distinguished by the combination of **bundleName** and **abilityName**, you can set **moduleName** for better distinguishing.| | +| moduleName9+ | Read only | string | No | Module to which the ability belongs.| + +**Example** + +``` js + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters uniquely identify an ability. + console.log("error.code = " + error.code) + }) +``` 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-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index bdf719b34ed6e7ba0dcc227ff5866c8ae7b87a87..565210637c6e83f83ec734c0905e11596baaf0db 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -1,12 +1,17 @@ # Ability +The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. + +This module provides the following common ability-related functions: + +- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee). +- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Manages the ability lifecycle and context. - ## Modules to Import ``` @@ -17,14 +22,12 @@ import Ability from '@ohos.application.Ability'; **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| -| launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.| -| lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.| -| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| - - +| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| +| launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.| +| lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.| +| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| ## Ability.onCreate @@ -36,13 +39,13 @@ Called to initialize the service logic when an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.| - | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.| +| param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| + +**Example** -**Example** - ```js class myAbility extends Ability { onCreate(want, param) { @@ -62,12 +65,12 @@ Called when a **WindowStage** is created for this ability. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | window.WindowStage | Yes| **WindowStage** information.| + +**Example** -**Example** - ```js class myAbility extends Ability { onWindowStageCreate(windowStage) { @@ -85,8 +88,8 @@ Called when the **WindowStage** is destroyed for this ability. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onWindowStageDestroy() { @@ -106,12 +109,12 @@ Called when the **WindowStage** is restored during the migration of this ability **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | window.WindowStage | Yes| **WindowStage** information.| + +**Example** -**Example** - ```js class myAbility extends Ability { onWindowStageRestore(windowStage) { @@ -129,8 +132,8 @@ Called when this ability is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onDestroy() { @@ -148,8 +151,8 @@ Called when this ability is switched from the background to the foreground. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onForeground() { @@ -167,8 +170,8 @@ Called when this ability is switched from the foreground to the background. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onBackground() { @@ -188,18 +191,18 @@ Called to save data during the ability migration preparation process. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | wantParam | {[key: string]: any} | Yes| **want** parameter.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wantParam | {[key: string]: any} | Yes| **want** parameter.| **Return value** - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnContinueResult | Continuation result.| +| Type| Description| +| -------- | -------- | +| AbilityConstant.OnContinueResult | Continuation result.| + +**Example** -**Example** - ```js import AbilityConstant from "@ohos.application.AbilityConstant" class myAbility extends Ability { @@ -222,13 +225,13 @@ Called when the ability startup mode is set to singleton. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.| - | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.| +| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| + +**Example** -**Example** - ```js class myAbility extends Ability { onNewWant(want, launchParams) { @@ -251,12 +254,12 @@ Called when the configuration of the environment where the ability is running is **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + +**Example** -**Example** - ```js class myAbility extends Ability { onConfigurationUpdated(config) { @@ -269,18 +272,18 @@ Called when the configuration of the environment where the ability is running is dump(params: Array\): Array\; -Called when the client information is dumped. +Dumps client information. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| + +**Example** -**Example** - ```js class myAbility extends Ability { dump(params) { @@ -307,19 +310,19 @@ Sends sequenceable data to the target ability. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| +| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return a response.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return a response.| + +**Example** -**Example** - ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ // Custom sequenceable data structure @@ -380,19 +383,19 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| +| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| +| Type| Description| +| -------- | -------- | +| Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| + +**Example** -**Example** - ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ @@ -452,8 +455,8 @@ Releases the caller interface of the target ability. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js import Ability from '@ohos.application.Ability'; var caller; @@ -489,12 +492,12 @@ Registers a callback that is invoked when the stub on the target ability is disc **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| + +**Example** -**Example** - ```js import Ability from '@ohos.application.Ability'; var caller; @@ -529,7 +532,7 @@ Implements callbacks for caller notification registration and deregistration. ## Callee.on -on(method: string, callback: CaleeCallBack): void; +on(method: string, callback: CalleeCallBack): void; Registers a caller notification callback, which is invoked when the target ability registers a function. @@ -537,13 +540,12 @@ Registers a caller notification callback, which is invoked when the target abili **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities.| - | callback | CaleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities.| +| callback | CalleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| -**Example** - +**Example** ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ @@ -593,9 +595,9 @@ Deregisters a caller notification callback, which is invoked when the target abi **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Registered notification message string.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Registered notification message string.| **Example** @@ -616,17 +618,17 @@ Deregisters a caller notification callback, which is invoked when the target abi **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| (msg: string) | function | Yes| No| Prototype of the listener function interface registered by the caller.| - +| (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.| + - ## CaleeCallBack + ## CalleeCallBack (indata: rpc.MessageParcel): rpc.Sequenceable; **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the message listener function interface registered by the callee.| +| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.| 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 3b2a958f7f403cade73487d61ff3695e5935d1bb..ca3269353344ca06935afaf6b390ae0c906f1a1a 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md @@ -1,12 +1,14 @@ # AbilityConstant +The **AbilityConstant** module provides ability launch parameters. + +The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Provides parameters related to ability launch. - ## Modules to Import ```js @@ -17,10 +19,10 @@ import AbilityConstant from '@ohos.application.AbilityConstant'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| +| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| +| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| ## AbilityConstant.LaunchReason @@ -60,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-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md index ec8655be70c9037622328066aa63d2cc643421d1..542214482f3e5bc8a74dad3d9990e1817b3f02e8 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md @@ -1,13 +1,21 @@ # AbilityDelegator +The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** instances that are used to monitor the lifecycle state changes of a specified ability. You can use the APIs to add and remove **AbilityMonitor** instances, wait for an ability to reach the **OnCreate** lifecycle state, set the waiting time, obtain the lifecycle state of an ability, obtain the top ability of the current application, and start an ability. + > **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 +## Usage +The ability delegator can be obtained by calling **getAbilityDelegator** in **AbilityDelegatorRegistry**. ```js import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' + +var abilityDelegator; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); + ``` ## AbilityDelegator @@ -174,7 +182,7 @@ abilityDelegator.removeAbilityMonitor(monitor).then(() => { waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void -Waits for the ability that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle and returns the **Ability** instance. This API uses an asynchronous callback to return the result. +Waits for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -211,7 +219,7 @@ abilityDelegator.waitAbilityMonitor(monitor, (err : any, data : any) => { waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void -Waits a period of time for the ability that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle and returns the **Ability** instance. This API uses an asynchronous callback to return the result. +Waits a period of time for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -250,7 +258,7 @@ abilityDelegator.waitAbilityMonitor(monitor, timeout, (err : any, data : any) => waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\ -Waits a period of time for the ability that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle and returns the **Ability** instance. This API uses a promise to return the result. +Waits a period of time for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -355,7 +363,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { getCurrentTopAbility(callback: AsyncCallback\): void -Obtains the top ability of the application. This API uses an asynchronous callback to return the result. +Obtains the top ability of this application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -384,7 +392,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { getCurrentTopAbility(): Promise\ -Obtains the top ability of the application. This API uses a promise to return the result. +Obtains the top ability of this application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -491,7 +499,7 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses an | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------- | | ability | Ability | Yes | Target ability. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** @@ -529,7 +537,7 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p | Type | Description | | ----------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| +| Promise\ | Promise used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** @@ -562,7 +570,7 @@ Schedules the lifecycle state of an ability to **Background**. This API uses an | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------- | | ability | Ability | Yes | Target ability. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** @@ -600,7 +608,7 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p | Type | Description | | ----------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| +| Promise\ | Promise used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** @@ -620,6 +628,32 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { +### printSync9+ + +printSync(msg: string): void + +Prints log information to the unit test console. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| msg | string | Yes | Log string.| + +**Example** + +```js +var abilityDelegator; +var msg = "msg"; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.printSync(msg); +``` + + + ### print print(msg: string, callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md index ad43acc77bd9e7ff82b9d5bb7e01467e6b36c656..dffe0e39e69e38123bf7e89338b3d4efb14ad82a 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md @@ -1,22 +1,30 @@ # AbilityDelegatorArgs +The **AbilityDelegatorArgs** module provides a global register to store the registered **AbilityDelegator** and **AbilityDelegatorArgs** instances during application startup. + > **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 +## Usage + +The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**. ```js import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' + +var args = AbilityDelegatorRegistry.getArguments(); ``` ## AbilityDelegatorArgs -Describes the test parameters. +Describes the ability delegator arguments. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable| Writable| Description | | ------------------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Yes | Bundle name of the application to test.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| testCaseNames | string | Yes | Yes | Test case names.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| testRunnerClassName | string | Yes | Yes | Names of the test executors that execute the test cases.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| bundleName | string | Yes | Yes | Bundle name of the application to test. | +| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently. | +| testCaseNames | string | Yes | Yes | Test case names. | +| testRunnerClassName | string | Yes | Yes | Names of the test case executors. | diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index 02803ad07bcde72288958a9be4981a15b8b4b555..42974b5fd683af842146b53fec22022edca84de6 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,17 +1,17 @@ # AbilityLifecycleCallback +The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onAbilityWindowStageCreate**, and **onAbilityWindowStageDestroy**, to receive lifecycle state changes in the application context. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -A callback class that provides APIs, such as **onAbilityCreate**, **onAbilityWindowStageCreate**, and **onAbilityWindowStageDestroy**, to listen for the lifecycle of the application context. - ## Modules to Import ```js -import AbilityLifecycleCallback from "@ohos.application.abilityLifecycleCallback"; +import AbilityLifecycleCallback from "@ohos.application.AbilityLifecycleCallback"; ``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e1bf96bae511de4e1fb83d92df6ee05bdddbf990 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -0,0 +1,268 @@ +# AbilityManager + +The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are system APIs and cannot be called by third-party applications. + +## Modules to Import + +```js +import AbilityManager from '@ohos.application.abilityManager' +``` + +## AbilityState + +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.| +| FOREGROUND | 9 | The ability is in the foreground state. | +| BACKGROUND | 10 | The ability is in the background state. | +| FOREGROUNDING | 11 | The ability is in the foregrounding state. | +| BACKGROUNDING | 12 | The ability is in the backgrounding state. | + +## updateConfiguration + +updateConfiguration(config: Configuration, callback: AsyncCallback\): void + +Updates the configuration. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | Configuration | Yes | New configuration.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var config = { + language: 'chinese' +} + +abilitymanager.updateConfiguration(config, () => { + console.log('------------ updateConfiguration -----------'); +}) +``` + +## updateConfiguration + +updateConfiguration(config: Configuration): Promise\ + +Updates the configuration. This API uses a promise to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | Configuration | Yes | New configuration.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var config = { + language: 'chinese' +} + +abilitymanager.updateConfiguration(config).then(() => { + console.log('updateConfiguration success'); +}).catch((err) => { + console.log('updateConfiguration fail'); +}) +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(callback: AsyncCallback\>): void + +Obtains the ability running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getAbilityRunningInfos((err,data) => { + console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); +}); +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(): Promise\> + +Obtains the ability running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getAbilityRunningInfos().then((data) => { + console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) +}).catch((err) => { + console.log("getAbilityRunningInfos err: " + err) +}); +``` + +## getExtensionRunningInfos9+ + +getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void + +Obtains the extension running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var upperLimit = 0; + +abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { + console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); +}); +``` + +## getExtensionRunningInfos9+ + +getExtensionRunningInfos(upperLimit: number): Promise\> + +Obtains the extension running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +var upperLimit = 0; + +abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { + console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getAbilityRunningInfos err: " + err); +}) +``` + +## getTopAbility9+ + +getTopAbility(callback: AsyncCallback\): void; + +Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getTopAbility((err,data) => { + console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); +}); +``` + +## getTopAbility9+ + +getTopAbility(): Promise\; + +Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\| Promise used to return the result.| + +**Example** + +```js +import abilitymanager from '@ohos.application.abilityManager'; + +abilitymanager.getTopAbility().then((data) => { + console.log("getTopAbility data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getTopAbility err: " + err); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-application-abilityMonitor.md index e7f017b48ebb0f440b021386e7a427e2d0a59852..33feda3afdd757e91ed7b7f682dca1ef597a7847 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityMonitor.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityMonitor.md @@ -1,26 +1,47 @@ # AbilityMonitor +The **AbilityMonitor** module provides monitors for abilities that meet specified conditions. The latest matched abilities are stored in an **AbilityMonitor** object. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import +## Usage + +The ability monitor is set by calling **addAbilityMonitor** in **abilityDelegator**. ```js import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.addAbilityMonitor(monitor, (err : any) => { + console.info("addAbilityMonitor callback"); +}); ``` ## AbilityMonitor Describes an ability monitor. +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + | Name | Type | Readable| Writable| Description | | ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| onAbilityCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| onAbilityForeground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability starts to run in the foreground.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| onAbilityBackground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability starts to run in the background.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| onAbilityDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| onWindowStageCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| onWindowStageRestore?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is restored.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| onWindowStageDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor. | +| onAbilityCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | +| onAbilityForeground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability starts to run in the foreground.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | +| onAbilityBackground?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability starts to run in the background.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | +| onAbilityDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the ability is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | +| onWindowStageCreate?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | +| onWindowStageRestore?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is restored.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | +| onWindowStageDestroy?:(data: [Ability](js-apis-application-ability.md#Ability)) | function | Yes | Yes | Called when the window stage is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received. | diff --git a/en/application-dev/reference/apis/js-apis-application-abilitystage.md b/en/application-dev/reference/apis/js-apis-application-abilitystage.md index 731d21305f151cd0318b14813e270bc14a27a3d2..c4f5da0e2989b5565d6405198a8c83ad7f20ee65 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilitystage.md +++ b/en/application-dev/reference/apis/js-apis-application-abilitystage.md @@ -1,12 +1,14 @@ # AbilityStage +**AbilityStage** is a runtime class for HAP files. + +The **AbilityStage** module notifies you of when you can perform HAP initialization such as resource pre-loading and thread creation during the HAP loading. + > **NOTE** > -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Runtime class for HAP files. It provides APIs to notify you when a HAP file starts loading. You can then initialize the HAP file, for example, pre-load resources and create threads. - ## Modules to Import ```js 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 517d9fb529fce872c5972a1aada50ce9f9b54ec9..88eccc98c39c5373930f35465ca48da1df19c40d 100644 --- a/en/application-dev/reference/apis/js-apis-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-application-applicationContext.md @@ -1,19 +1,13 @@ # ApplicationContext +The **ApplicationContext** module provides application-level context. You can use the APIs of this module to register and deregister the ability lifecycle listener in an application. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Provides application-level context and APIs for registering and deregistering the ability lifecycle listener in an application. - -## Modules to Import - -``` -import Ability from '@ohos.application.Ability'; -``` - -## How to Use +## Usage Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance. @@ -34,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** @@ -42,6 +36,54 @@ Registers a listener to monitor the ability lifecycle of the application. | ------ | ------------------------------ | | number | ID of the registered listener. The ID is incremented by 1 each time the listener is registered. When the ID exceeds 2^63-1, **-1** is returned.| +**Example** + + ```js +import AbilityStage from "@ohos.application.AbilityStage"; + +var lifecycleId; + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let AbilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + }, + onAbilityWindowStageCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityWindowStageCreate ability:" + JSON.stringify(ability)); + }, + onAbilityWindowStageDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityWindowStageDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + }, + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + }, + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + } + } + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Use applicationContext to register a listener for the ability lifecycle in the application. + lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + } + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + } +} + ``` + ## ApplicationContext.unregisterAbilityLifecycleCallback @@ -56,52 +98,91 @@ 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** + + ```js + let applicationContext = this.context.getApplicationContext(); + let lifecycleId = 1; + console.log("stage applicationContext: " + JSON.stringify(applicationContext)); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + ``` + +## ApplicationContext.registerEnvironmentCallback + +registerEnvironmentCallback(callback: EnvironmentCallback): **number**; + +Registers a listener for system environment changes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------------ | -------- | ---- | ------------------------------ | +| callback | [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------ | +| number | ID of the registered listener. The ID is incremented by 1 each time the listener is registered. When the ID exceeds 2^63-1, **-1** is returned.| + +**Example** + + ```js +import AbilityStage from "@ohos.application.AbilityStage"; + +var callbackId; + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + globalThis.applicationContext = this.context.getApplicationContext(); + let EnvironmentCallback = { + onConfigurationUpdated(config){ + console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + }, + } + // 1. Obtain an applicationContext object. + let applicationContext = globalThis.applicationContext; + // 2. Use applicationContext to register a listener for the ability lifecycle in the application. + callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); + console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + } + onDestroy() { + let applicationContext = globalThis.applicationContext; + applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + }); + } +} + ``` + +## ApplicationContext.unregisterEnvironmentCallback + +unregisterEnvironmentCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; + +Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | -------------------------- | +| callbackId | number | Yes | ID of the listener to deregister. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js - import AbilityStage from "@ohos.application.AbilityStage"; - - var lifecycleid; - - export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); - }, - onAbilityWindowStageCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageCreate ability:" + JSON.stringify(ability)); - }, - onAbilityWindowStageDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); - }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); - }, - onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); - } - } - // 1. Obtain applicationContext through the context attribute. - let applicationContext = this.context.getApplicationContext(); - // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); - } - onDestroy() { - let applicationContext = this.context.getApplicationContext(); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - } - } + let applicationContext = this.context.getApplicationContext(); + let callbackId = 1; + applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + }); ``` diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index 66cd6b7150041bdbf45d4d0e0adf105e0ade044b..cf5291224477451554ea36e823ecedc0629cbfe0 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -1,39 +1,43 @@ # Context +The **Context** module provides the context for running code. You can use the APIs to query and set the application information and resource manager. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Provides the context for running code, including **applicationInfo** and **resourceManager**. - -## Modules to Import -``` -import AbilityContext from '@ohos.application.Ability'; -``` - ## Usage You must extend **AbilityContext** to implement this module. + ```js +import AbilityContext from '@ohos.application.Ability' + class MainAbility extends AbilityContext { + onWindowStageCreate(windowStage) { + let test = "com.example.test"; + let context = this.context.createBundleContext(test); + } + } + ``` + ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| resourceManager | ResourceManager | Yes| No| **ResourceManager** object.| +| resourceManager | resmgr.ResourceManager; | Yes| No| **ResourceManager** object.| | applicationInfo | ApplicationInfo | Yes| No| Information about the application.| | cacheDir | string | Yes| No| Cache directory of the application on the internal storage.| | tempDir | string | Yes| No| Temporary file directory of the application.| | filesDir | string | Yes| No| File directory of the application on the internal storage.| | databaseDir | string | Yes| No| Storage directory of local data.| -| storageDir | string | Yes| No| Storage directory of lightweight data.| | bundleCodeDir | string | Yes| No| Application installation path.| | distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| | eventHub | [EventHub](js-apis-eventhub.md) | Yes| No| Event hub information.| | area | [AreaMode](#areamode) | Yes| Yes| Area in which the file to be access is located.| - +| preferencesDir | string | Yes| Yes| Preferences directory of the application.| ## Context.createBundleContext @@ -41,19 +45,23 @@ createBundleContext(bundleName: string): Context; Creates a context for a given application. +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Application bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | Context | Context created.| +| Type| Description| +| -------- | -------- | +| Context | Context created.| **Example** @@ -79,15 +87,15 @@ Creates a context for a given HAP. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | moduleName | string | Yes| HAP name in the application.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| moduleName | string | Yes| HAP name in the application.| **Return value** - | Type| Description| - | -------- | -------- | - | Context | Context created.| +| Type| Description| +| -------- | -------- | +| Context | Context created.| **Example** @@ -111,18 +119,20 @@ Creates a context for a given HAP in an application. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| - | moduleName | string | Yes| HAP name in the application.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Application bundle name.| +| moduleName | string | Yes| HAP name in the application.| **Return value** - | Type| Description| - | -------- | -------- | - | Context | Context created.| +| Type| Description| +| -------- | -------- | +| Context | Context created.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md index e0cddeee652418cdd714507cee826971fce73e28..9c47b27f1173eba688942f542cf8eef6e9c90666 100644 --- a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md @@ -1,20 +1,34 @@ # ShellCmdResult +The **ShellCmdResult** module provides the shell command execution result. + > **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 +## Usage + +The result is obtained by calling **executeShellCommand** in **abilityDelegator**. ```js import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +var abilityDelegator; +var cmd = "cmd"; +var timeout = 100; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { + console.info("executeShellCommand promise"); +}); ``` ## ShellCmdResult Describes the shell command execution result. +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + | Name | Type | Readable| Writable| Description | | --------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| stdResult | string | Yes | Yes | Standard output content.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| exitCode | number | Yes | Yes | Result code.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| stdResult | string | Yes | Yes | Standard output content. | +| exitCode | number | Yes | Yes | Result code. | diff --git a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index abd004e82d684fc3b038aebf8fb1153602137476..7c5ba607718d5d14317a55645627022b78976461 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -1,5 +1,7 @@ # StaticSubscriberExtensionAbility +The **StaticSubscriberExtensionAbility** module provides Extension abilities for static subscribers. + > **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. @@ -16,13 +18,15 @@ onReceiveEvent(event: CommonEventData): void; Callback of the common event of a static subscriber. -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | event | CommonEventData | Yes| Callback of the common event of a static subscriber.| + | event | CommonEventData | Yes| Common event of a static subscriber.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 236ed9c1af1231ebb1ddc8c63356a20f57cb3010..05ff78e77e6d6d54527148782b18d0dbca007cd6 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -1,21 +1,17 @@ # appManager +The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. + > **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. - -Implements application management. - - ## Modules to Import - ```js import app from '@ohos.application.appManager'; ``` - ## appManager.isRunningInStabilityTest8+ static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void @@ -165,6 +161,8 @@ getProcessRunningInfos(): Promise\>; Obtains information about the running processes. This API uses a promise to return the result. +**Required permissions**: ohos.permission.GET_RUNNING_INFO + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** @@ -189,6 +187,8 @@ getProcessRunningInfos(callback: AsyncCallback\>): vo Obtains information about the running processes. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.GET_RUNNING_INFO + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** @@ -206,13 +206,533 @@ Obtains information about the running processes. This API uses an asynchronous c }) ``` -## ProcessRunningInfo +## appManager.registerApplicationStateObserver8+ + +registerApplicationStateObserver(observer: ApplicationStateObserver): number; + +Registers the application state observer. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | ApplicationStateObserver | No| Numeric code of the observer.| + +**Example** + + ```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); + } + } + const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); + + ``` +## appManager.unregisterApplicationStateObserver8+ + +unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\): void; + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | No| Numeric code of the observer.| +| callback | AsyncCallback\ | No| Callback used to return the result.| + +**Example** + + ```js + var observerId = 100; + + function unregisterApplicationStateObserverCallback(err) { + if (err) { + console.log('------------ unregisterApplicationStateObserverCallback ------------', err); + } + } + app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); + ``` + +## appManager.unregisterApplicationStateObserver8+ + +unregisterApplicationStateObserver(observerId: number): Promise\; + +Deregisters the application state observer. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | No| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```js + var observerId = 100; + + app.unregisterApplicationStateObserver(observerId) + .then((data) => { + console.log('----------- unregisterApplicationStateObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- unregisterApplicationStateObserver fail ----------', err); + }) + ``` + +## appManager.getForegroundApplications8+ + +getForegroundApplications(callback: AsyncCallback\>): void; + +Obtains applications that run in the foreground. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | No| Callback used to return the application state data.| + +**Example** + + ```js + function getForegroundApplicationsCallback(err, data) { + if (err) { + console.log('--------- getForegroundApplicationsCallback fail ---------', err); + } else { + console.log('--------- getForegroundApplicationsCallback success ---------', data) + } + } + app.getForegroundApplications(getForegroundApplicationsCallback); + ``` + +## appManager.getForegroundApplications8+ + +getForegroundApplications(): Promise\>; + +Obtains applications that run in the foreground. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the application state data.| + +**Example** + + ```js + app.getForegroundApplications() + .then((data) => { + console.log('--------- getForegroundApplications success -------', data); + }) + .catch((err) => { + console.log('--------- getForegroundApplications fail -------', err); + }) + ``` + +## appManager.killProcessWithAccount8+ + +killProcessWithAccount(bundleName: string, accountId: number): Promise\ + +Kills the process by bundle name and account ID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of an application.| + | accountId | number | Yes| Account ID.| + +**Example** + +```js +var bundleName = 'bundleName'; +var accountId = 0; +app.killProcessWithAccount(bundleName, accountId) + .then((data) => { + console.log('------------ killProcessWithAccount success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessWithAccount fail ------------', err); + }) +``` + + +## appManager.killProcessWithAccount8+ + +killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void + +Kills the process by bundle name and account ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of an application.| + | accountId | number | Yes| Account ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + +```js +var bundleName = 'bundleName'; +var accountId = 0; +function killProcessWithAccountCallback(err, data) { + if (err) { + console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessWithAccountCallback success, data: --------------', data); + } +} +app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +``` + +## appManager.killProcessesByBundleName8+ + +killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); + +Kills a process by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | No| Bundle name of an application.| +| callback | AsyncCallback\ | No| Callback used to return the result.| + +**Example** + + ```js + var bundleName = 'bundleName'; + function killProcessesByBundleNameCallback(err, data) { + if (err) { + console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); + } + } + app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); + ``` + +## appManager.killProcessesByBundleName8+ + +killProcessesByBundleName(bundleName: string): Promise\; + +Kills a process by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | No| Bundle name of an application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```js +var bundleName = 'bundleName'; +app.killProcessesByBundleName(bundleName) + .then((data) => { + console.log('------------ killProcessesByBundleName success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessesByBundleName fail ------------', err); + }) + + ``` + +## appManager.clearUpApplicationData8+ + +clearUpApplicationData(bundleName: string, callback: AsyncCallback\); + +Clears application data by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | No| Bundle name of an application.| +| callback | AsyncCallback\ | No| Callback used to return the result.| + +**Example** + + ```js + var bundleName = 'bundleName'; + function clearUpApplicationDataCallback(err, data) { + if (err) { + console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); + } else { + console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); + } + } + app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); + + ``` + +## appManager.clearUpApplicationData8+ + +clearUpApplicationData(bundleName: string): Promise\; + +Clears application data by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | No| Bundle name of an application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```js + var bundleName = 'bundleName'; + app.clearUpApplicationData(bundleName) + .then((data) => { + console.log('------------ clearUpApplicationData success ------------', data); + }) + .catch((err) => { + console.log('------------ clearUpApplicationData fail ------------', err); + }) + + ``` + +## ApplicationStateObserver.onForegroundApplicationChanged8+ + +onForegroundApplicationChanged(appStateData: AppStateData): void; + +Called when the application state changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| appStateData | [AppStateData](#appstatedata) | No| Information about the application whose state is changed.| + +**Example** + +```js +import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' +const foregroundApplicationInfo = ApplicationStateObserver.onForegroundApplicationChanged(); +console.log('-------- foregroundApplicationInfo: ---------', foregroundApplicationInfo); +``` + +## ApplicationStateObserver.onAbilityStateChanged8+ + +onAbilityStateChanged(abilityStateData: AbilityStateData): void; + +Called when the ability state changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityStateData | [AbilityStateData](#abilitystatedata) | No| Information about the ability whose state is changed.| + +**Example** + +```js +import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' +const abilityStateChangedInfo = ApplicationStateObserver.onAbilityStateChanged(); +console.log('-------- abilityStateChangedInfo: ---------', abilityStateChangedInfo); +``` + +## ApplicationStateObserver.onProcessCreated8+ + +onProcessCreated(processData: ProcessData): void; + +Called when a process is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| processData | [ProcessData](#processdata) | No| Process information.| + +**Example** + +```js +import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' +const processCreatedInfo = ApplicationStateObserver.onProcessCreated(); +console.log('-------- processCreatedInfo: ---------', processCreatedInfo); +``` + +## ApplicationStateObserver.onProcessDied8+ + +onProcessDied(processData: ProcessData): void; + +Called when a process is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| processData | ProcessData | No| Process information.| + +**Example** + +```js +import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' +const processDiedInfo = ApplicationStateObserver.onProcessDied(); +console.log('-------- processDiedInfo: ---------', processDiedInfo); +``` + +## AppStateData + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Readable/Writable| Type | Mandatory| Description | | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| pid8+ | Read only | number | No | Process ID. | +| bundleName8+ | Read only | string | No | Bundle name of an application. | | uid8+ | Read only | number | No | User ID.| -| processName8+ | Read only | string | No | Process name.| -| bundleNames8+ | Read only | Array\ | No | **bundleName** array in the running processes.| +| state8+ | Read only | number | No | Application state.| + +## AbilityStateData + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| pid8+ | number | Yes | No | Process ID. | +| bundleName8+ | string | Yes | No | Bundle name of an application. | +| abilityName8+ | string | Yes | No | Ability name. | +| uid8+ | number | Yes | No | User ID. | +| state8+ | number | Yes | No | Application information. | +| moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | +| abilityType8+ | string | Yes | No | Ability type. | + +## ProcessData + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| pid8+ | number | Yes | No | Process ID. | +| bundleName8+ | string | Yes | No | Bundle name of an application. | +| uid8+ | number | Yes | No | User ID. | + + + +## ProcessRunningInfo + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| pid9+ | Read only | number | No | Process ID. | +| uid9+ | Read only | number | No | User ID.| +| processName9+ | Read only | string | No | Process name.| +| bundleNames9+ | Read only | Array\ | No | **bundleName** array in the running processes.| diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index 5eacfc8a69610d57abec3afdd0fba6f7addaa30b..32dc8d6c6ebea54129c103a2323dacdc34a442c1 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1011,7 +1011,7 @@ bluetooth.off('sppRead', clientNumber); ``` -## bluetooth.getProfile8+ +## bluetooth.getProfile8+ getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile @@ -1037,9 +1037,9 @@ Obtains a profile object. let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ``` -## bluetooth.getProfile9+ +## bluetooth.getProfileInst9+ -getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile +getProfileInst(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile Obtains a profile instance. API version 9 is added with **HidHostProfile** and **PanProfile**. @@ -1060,7 +1060,7 @@ Obtains a profile instance. API version 9 is added with **HidHostProfile** and * **Example** ```js -let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST); ``` @@ -1451,14 +1451,12 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent); ``` -### getPlayingState9+ +### getPlayingState8+ getPlayingState(device: string): PlayingState Obtains the playing state of a device. -**Required permissions**: ohos.permission.USE_BLUETOOTH - **System capability**: SystemCapability.Communication.Bluetooth.Core **Parameters** @@ -1559,7 +1557,7 @@ Subscribes to the HFP connection state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event.| -| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the HFP connection state change event. | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback used to return the HFP connection state change event. | **Return value** @@ -1612,7 +1610,7 @@ hfpAg.off('connectionStateChange', onReceiveEvent); Before using a method of **HidHostProfile**, you need to create an instance of this class by using the **getProfile()** method. -### connect9+ +### connect9+ connect(device: string): boolean @@ -1644,7 +1642,7 @@ let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); ``` -### disconnect9+ +### disconnect9+ disconnect(device: string): boolean @@ -1742,7 +1740,7 @@ hidHost.off('connectionStateChange', onReceiveEvent); Before using a method of **PanProfile**, you need to create an instance of this class by using the **getProfile()** method. -### disconnect9+ +### disconnect9+ disconnect(device: string): boolean @@ -1837,7 +1835,7 @@ panProfile.off('connectionStateChange', onReceiveEvent); ### setTethering9+ -setTethering(value: boolean): boolean +setTethering(enable: boolean): void Sets tethering. @@ -1871,12 +1869,10 @@ let ret = panProfile.setTethering(true); isTetheringOn(): boolean -Obtains the tethering status. +Obtains the tethering state. This is a system API. -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH - **System capability**: SystemCapability.Communication.Bluetooth.Core **Return value** @@ -2019,7 +2015,7 @@ let descV = new Uint8Array(arrayBuffer); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', - descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; descriptors[0] = descriptor; // Create characteristics. @@ -2129,7 +2125,7 @@ let descV = new Uint8Array(arrayBuffer); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', - descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; descriptors[0] = descriptor; let arrayBufferC = new ArrayBuffer(8); let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', @@ -2502,7 +2498,6 @@ let gattServer = bluetooth.BLE.createGattServer(); gattServer.off("descriptorWrite"); ``` - ### on('connectStateChange') on(type: "connectStateChange", callback: Callback<BLEConnectChangedState>): void @@ -2709,8 +2704,10 @@ Obtains all services of the remote BLE device. This API uses a promise to return ```js // Promise -gattClientDevice.getServices().then(result => { - console.info("Got services successfully:" + JSON.stringify(result)); +let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); +device.connect(); +device.getServices().then(result => { + console.info("getServices successfully:" + JSON.stringify(result)); }); ``` @@ -3051,7 +3048,7 @@ let descV = new Uint8Array(arrayBuffer); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', - descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; descriptors[0] = descriptor; let arrayBufferC = new ArrayBuffer(8); let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', @@ -3311,7 +3308,7 @@ Enumerates the scan modes. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Default Value | Description | | ---------------------------------------- | ---- | --------------- | | SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | @@ -3326,7 +3323,7 @@ Enumerates the pairing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Default Value | Description | | ------------------ | ---- | ------ | | BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_BONDING | 1 | Pairing. | @@ -3352,7 +3349,7 @@ Enumerates the SPP link types. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Default Value | Description | | ---------- | ---- | ------------- | | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| @@ -3536,7 +3533,7 @@ Defines the scan filter parameters. | serviceSolicitationUuidMask9+ | string | Yes | Yes | Service solicitation UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.| | serviceData9+ | ArrayBuffer | Yes | Yes | Service data of the device to filter, for example, **[0x90, 0x00, 0xF1, 0xF2]**.| | serviceDataMask9+ | ArrayBuffer | Yes | Yes | Service data mask of the device to filter, for example, **[0xFF,0xFF,0xFF,0xFF]**.| -| manufacturerId9+ | number | Yes | Yes | Manufacturer ID of the device to filter, for example, **0x0006**. | +| manufactureId9+ | number | Yes | Yes | Manufacturer ID of the device to filter, for example, **0x0006**. | | manufactureData9+ | ArrayBuffer | Yes | Yes | Manufacturer data of the device to filter, for example, **[0x1F,0x2F,0x3F]**.| | manufactureDataMask9+ | ArrayBuffer | Yes | Yes | Manufacturer data mask of the device to filter, for example, **[0xFF, 0xFF, 0xFF]**.| @@ -3617,7 +3614,7 @@ Defines the BLE advertising parameters. | Name | Type | Readable | Writable | Description | | ----------- | ------- | ---- | ---- | ---------------------------------------- | -| interval | number | Yes | Yes | Interval for BLE advertising. The minimum value is **32** slots (20 ms). The maximum value is **16777215** slots. The default value is **1600** slots (1s).| +| interval | number | Yes | Yes | Interval for BLE advertising. The minimum value is **32** slots (20 ms). The maximum value is **16384** slots. The default value is **1600** slots (1s).| | txPower | number | Yes | Yes | Transmit power, in dBm. The value range is -127 to 1. The default value is **-7**. | | connectable | boolean | Yes | Yes | Whether the advertisement is connectable. The default value is **true**. | @@ -3828,7 +3825,7 @@ Enumerates the A2DP playing states. ## ProfileId8+ -Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOST**. +Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOST** and **PROFILE_PAN_NETWORK**. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -3837,3 +3834,4 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS | PROFILE_A2DP_SOURCE | 0x0001 | A2DP profile.| | PROFILE_HANDS_FREE_AUDIO_GATEWAY | 0x0004 | HFP profile. | | PROFILE_HID_HOST9+ | 0x0006 | Human Interface Device (HID) profile. | +| PROFILE_PAN_NETWORK9+ | 0x0007 | PAN profile. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index 185338803c92789aea72fa0fca2ab7791ab89ea1..94182ce2915f60bd6998f512d17288920549d3f8 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,17 +1,15 @@ # ApplicationInfo +The **ApplicationInfo** module provides application information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. + > **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 information. - ## ApplicationInfo **System capability**: SystemCapability.BundleManager.BundleFramework - - | Name | Type | Readable| Writable| Description | | -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Application name. | @@ -26,16 +24,19 @@ Provides the application information. | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | | supportedModes | number | Yes | No | Running modes supported by the application. | | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_PERMISSION**.| | moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | | entryDir | string | Yes | No | Path for storing application files. | | codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application. | -| metadata9+ | Map\> | Yes | No | Metadata of the application. | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| +| metadata9+ | Map\> | Yes | No | Metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| | removable8+ | boolean | Yes | No | Whether the application is removable. | | accessTokenId8+ | number | Yes | No | Access token ID of the application. | | uid8+ | number | Yes | No | UID of the application. | | entityType8+ | string | Yes | No | Entity type of the application. | -| fingerprint9+ | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you request for the application.| +| fingerprint9+ | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you request for the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT**.| +| iconResource9+ | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Icon resource of the application.| +| labelResource9+ | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Label resource of the application.| +| descriptionResource9+ | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Description resource of the application.| | appDistributionType9+ | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**. | | appProvisionType9+ | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**.| 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-configuration.md b/en/application-dev/reference/apis/js-apis-configuration.md index 507b8a42448dd4ae892424feaae061c47d814138..14abee7e2d9cca63278e11b16486643d89e56bd0 100644 --- a/en/application-dev/reference/apis/js-apis-configuration.md +++ b/en/application-dev/reference/apis/js-apis-configuration.md @@ -1,11 +1,11 @@ # Configuration +The **Configuration** module provides environment configuration information. + > **NOTE** > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -Provides the configuration for the environment where the ability is running. - ## Modules to Import ```js @@ -23,3 +23,4 @@ import Configuration from '@ohos.application.Configuration'; | direction9+ | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| | screenDensity9+ | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| | displayId9+ | number | Yes| No| ID of the display where the application is located.| +| hasPointerDevice9+ | boolean | Yes| No| Whether the pointer device is connected.| diff --git a/en/application-dev/reference/apis/js-apis-configurationconstant.md b/en/application-dev/reference/apis/js-apis-configurationconstant.md index ebb78bc00e5ece7a6e04e64db6135f9d2f7ed7fd..70d527483a15d7f676402ad406964740a5686a6b 100644 --- a/en/application-dev/reference/apis/js-apis-configurationconstant.md +++ b/en/application-dev/reference/apis/js-apis-configurationconstant.md @@ -1,13 +1,11 @@ # ConfigurationConstant +The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. + > **NOTE** > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -Defines enumerated values of the configuration for the environment where the ability is running. - - ## Modules to Import @@ -15,7 +13,6 @@ Defines enumerated values of the configuration for the environment where the abi import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; ``` - ## ConfigurationConstant.ColorMode You can obtain the value of this constant by calling the **ConfigurationConstant.ColorMode** API. 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-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index 14465e3daf5fe8e25a53ae3987dbb889a1f4dc23..c3b59a85ab9e2945a8375a61b44c7e45c5d1c385 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,6 +1,6 @@ # Data Sharing -The **DataShare** module allows applications to manage their own data and supports data sharing between applications on the same device. +The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. >**NOTE** > @@ -10,7 +10,6 @@ The **DataShare** module allows applications to manage their own data and suppor ## Modules to Import ```ts -import Ability from '@ohos.application.Ability' import dataShare from '@ohos.data.dataShare' ``` @@ -34,7 +33,7 @@ Creates a **DataShareHelper** instance. This API uses an asynchronous callback t **Example** ```ts -import dataShare from '@ohos.data.dataShare' +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; @@ -72,7 +71,7 @@ Creates a **DataShareHelper** instance. This API uses a promise to return the re **Example** ```ts -import dataShare from '@ohos.data.dataShare' +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; @@ -86,7 +85,9 @@ dataShare.createDataShareHelper(this.context, uri).then((data) => { ## DataShareHelper -Provides a **DataShareHelper** instance to access or manage data on the server. Before invoking any method provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper). +Provides a **DataShareHelper** instance to access or manage data on the server. Before calling an API provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper). + +This API can be used only in the stage model. ### openFile @@ -109,6 +110,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.openFile(uri, "rwt", (err, data) => { if (err != undefined) { @@ -146,6 +148,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.openFile(uri, "rwt").then((data) => { console.info("openFile succeed, data : " + data); @@ -176,6 +179,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' function onCallback() { console.info("**** Observer on callback ****"); } @@ -204,6 +208,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' function offCallback() { console.info("**** Observer off callback ****"); } @@ -232,6 +237,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose", @@ -268,11 +274,12 @@ This API can be used only in the stage model. | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise<number> | Promise used to return the index of the inserted data record.
The data index is not returned if the APIs of the database (for example, KVDB) in use do not support the return of indexes.| +| Promise<number> | Promise used to return the index of the inserted data record.
The data index is not returned if the APIs of the database in use (for example, KVDB) do not support the return of indexes.| **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose1", @@ -301,12 +308,13 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database used. For example, the KVDB supports only **inKeys**.| -| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.
The number of deleted data records is not returned if the APIs of the database (for example, KVDB) in use do not support it.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.
The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts +import Ability from '@ohos.application.Ability' import dataSharePredicates from '@ohos.data.dataSharePredicates' let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -336,17 +344,18 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database used. For example, the KVDB supports only **inKeys**.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| **Return value** | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise<number> | Promise used to return the number of deleted data records.
The number of deleted data records is not returned if the APIs of the database (for example, KVDB) in use do not support it.| +| Promise<number> | Promise used to return the number of deleted data records.
The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts +import Ability from '@ohos.application.Ability' import dataSharePredicates from '@ohos.data.dataSharePredicates' let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -374,13 +383,14 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | | callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the result set obtained. Otherwise, **err** is an error object.| **Example** ```ts +import Ability from '@ohos.application.Ability' import dataSharePredicates from '@ohos.data.dataSharePredicates' let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -411,7 +421,7 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | **Return value** @@ -423,6 +433,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' import dataSharePredicates from '@ohos.data.dataSharePredicates' let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -451,13 +462,14 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database used. For example, only the relational database (RDB) supports predicates.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| | value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | -| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.
The number of updated data records is not returned if the APIs of the database (for example, KVDB) in use do not support it.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.
The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts +import Ability from '@ohos.application.Ability' import dataSharePredicates from '@ohos.data.dataSharePredicates' let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -493,18 +505,19 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database used. For example, only the RDB supports predicates.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| | value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | **Return value** | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise<number> | Promise used to return the number of data records updated.
The number of updated data records is not returned if the APIs of the database (for example, KVDB) in use do not support it.| +| Promise<number> | Promise used to return the number of data records updated.
The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts +import Ability from '@ohos.application.Ability' import dataSharePredicates from '@ohos.data.dataSharePredicates' let uri = ("datashare:///com.samples.datasharetest.DataShare"); @@ -527,7 +540,7 @@ dataShareHelper.update(uri, da, va).then((data) => { batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void -Inserts batch data into the database. This API uses an asynchronous callback to return the result. +Batch inserts data into the database. This API uses an asynchronous callback to return the result. This API can be used only in the stage model. @@ -539,11 +552,12 @@ This API can be used only in the stage model. | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | | values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | -| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.
The number of inserted data records is not returned if the APIs of the database (for example, KVDB) in use do not support it.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.
The number of inserted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, @@ -561,7 +575,7 @@ dataShareHelper.batchInsert(uri, vbs, (err, data) => { batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number> -Inserts batch data into the database. This API uses a promise to return the result. +Batch inserts data into the database. This API uses a promise to return the result. This API can be used only in the stage model. @@ -578,11 +592,12 @@ This API can be used only in the stage model. | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise<number> | Promise used to return the number of data records inserted.
The number of inserted data records is not returned if the APIs of the database (for example, KVDB) in use do not support it.| +| Promise<number> | Promise used to return the number of data records inserted.
The number of inserted data records is not returned if the APIs of the database (for example, KVDB) in use do not the return of the number of data records.| **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, @@ -614,6 +629,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.getType(uri, (err, data)=>{ if (err != undefined) { @@ -650,6 +666,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.getType(uri).then((data) => { console.log("getType succeed, data : " + data); @@ -673,12 +690,13 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME types to match. Example:
**\*/\***: obtain all supported types.
**image/\***: obtain the MIMEs with the main type of **image**.
**\*/jpg**: obtains the MIMEs with subtype of **jpg**.| -| callback | openFile(uri: string, mode: string, callback: AsyncCallback) { let err = {"code":0}; let fd = 0; callback(err,fd);}ts | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the MIME types obtained. Otherwise, **err** is an error object.| +| mimeTypeFilter | string | Yes | MIME types to match. Example:
**\*/\***: Obtain all supported types.
**image/\***: Obtain the MIMEs with the main type of **image**.
**\*/jpg**: Obtain the MIMEs with the subtype of **jpg**.| +| callback | AsyncCallback> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the MIME types obtained. Otherwise, **err** is an error object.| **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); let mimeTypeFilter = "image/*"; dataShareHelper.getFileTypes(uri, mimeTypeFilter, (err,data) => { @@ -705,7 +723,7 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME types to match. Example:
**\*/\***: obtain all supported types.
**image/\***: obtain the MIMEs with the main type of **image**.
**\*/jpg**: obtains the MIMEs with subtype of **jpg**.| +| mimeTypeFilter | string | Yes | MIME types to match. Example:
**\*/\***: Obtain all supported types.
**image/\***: Obtain the MIMEs with the main type of **image**.
**\*/jpg**: Obtain the MIMEs with the subtype of **jpg**.| **Return value** @@ -716,6 +734,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); let mimeTypeFilter = "image/*"; dataShareHelper.getFileTypes(uri, mimeTypeFilter).then((data) => { @@ -729,7 +748,7 @@ dataShareHelper.getFileTypes(uri, mimeTypeFilter).then((data) => { normalizeUri(uri: string, callback: AsyncCallback<string>): void -Normalizes a DataShare URI. The normalized URI can be used across devices, and the DataShare URI can be used only by the local device. This API uses an asynchronous callback to return the result. +Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result. This API can be used only in the stage model. @@ -745,6 +764,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { if (err != undefined) { @@ -759,7 +779,7 @@ dataShareHelper.normalizeUri(uri, (err, data) => { normalizeUri(uri: string): Promise<string> -Normalizes a DataShare URI. The normalized URI can be used across devices, and the DataShare URI can be used only by the local device. This API uses a promise to return the result. +Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result. This API can be used only in the stage model. @@ -780,6 +800,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri).then((data) => { console.log("normalizeUri = " + data); @@ -808,6 +829,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { if (err != undefined) { @@ -843,6 +865,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri).then((data) => { console.log("denormalizeUri = " + data); @@ -871,6 +894,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.log("***** notifyChange *****"); @@ -902,6 +926,7 @@ This API can be used only in the stage model. **Example** ```ts +import Ability from '@ohos.application.Ability' let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` 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 71b5d2bec230d88f378b1fa122319e8ba983c6e7..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.") -}) ``` @@ -1109,7 +1102,7 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** @@ -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. @@ -1144,7 +1137,7 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| **Return value** | Type| Description| @@ -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. @@ -1242,7 +1235,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** @@ -1270,12 +1263,12 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| +| 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,7 +1356,8 @@ Queries data in the RDB store based on specified conditions. This API uses an as **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| +| 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,7 +1387,8 @@ Queries data in the RDB store based on specified conditions. This API uses a pro **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| +| table | string | Yes| Name of the target table.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| **Return value** @@ -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-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index df69b38be754f255ce637249c18a9d2fca5e13fd..52af89ae7faa9fd20a28a62f959f4a3f39340ced 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -5,12 +5,6 @@ > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the FA model. -## Modules to Import - -```js -import featureAbility from "@ohos.ability.featureAbility"; -``` - ## Usage Import the following modules based on the actual situation before using the current module: @@ -573,7 +567,7 @@ Inserts multiple data records into the database. This API uses an asynchronous c | Name | Type | Mandatory| Description | | ------------ | ----------------------- | ---- | -------------------------------- | | uri | string | Yes | URI of the data to insert. | -| valuesBucket | Array\ | Yes | Data records to insert. | +| valuesBucket | Array | Yes | Data records to insert. | | callback | AsyncCallback\ | Yes | Callback used to return the number of inserted data records.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 93ab553ef10e531fea0b2d0871b65183d22bf6fa..8c27495f208ad620ed6e104fb19c958350805c1e 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,11 +1,22 @@ # Device Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +The **DeviceManager** module provides APIs for distributed device management. + +System applications can call the APIs to do the following: + +- Subscribe to or unsubscribe from device state changes. +- Discover peripheral untrusted devices. +- Authenticate or deauthenticate a device. +- Query the trusted device list. +- Query local device information, including the device name, type, and ID. + +> **NOTE** +> > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are system APIs and cannot be called by third-party applications. -## Modules to import: +## Modules to Import ``` import deviceManager from '@ohos.distributedHardware.deviceManager'; @@ -21,10 +32,10 @@ Creates a **DeviceManager** instance. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of the application.| - | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes| Callback invoked to return the **DeviceManager** instance created.| + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------------------------------------ | + | bundleName | string | Yes | Bundle name of an application. | + | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| - Example ``` @@ -34,10 +45,40 @@ Creates a **DeviceManager** instance. return; } console.info("createDeviceManager success"); - this.dmInstance = data; + let dmInstance = data; }); ``` +## DeviceInfo + +Defines device information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| ---------------------- | ------------------------- | ---- | -------- | +| deviceId | string | Yes | Unique identifier of a device.| +| deviceName | string | Yes | Device name. | +| deviceType | [DeviceType](#devicetype) | Yes | Device type. | +| networkId8+ | string | Yes | Network ID of the device. | + + +## DeviceType + +Enumerates the device types. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ------------ | ---- | ---- | +| SPEAKER | 0x0A | Smart speaker.| +| PHONE | 0x0E | Phone. | +| TABLET | 0x11 | Tablet. | +| WEARABLE | 0x6D | Wearable.| +| TV | 0x9C | Smart TV. | +| CAR | 0x83 | Car. | +| UNKNOWN_TYPE | 0 | Unknown device type.| + ## DeviceStateChangeAction @@ -45,42 +86,103 @@ Enumerates the device states. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name| Default Value| Description| -| -------- | -------- | -------- | -| ONLINE | 0 | The device is online.| -| READY | 1 | The device is ready, and the device information has been synchronized.| -| OFFLINE | 2 | The device is offline.| -| CHANGE | 3 | The device information is changed.| +| Name | Default Value | Description | +| ------- | ---- | --------------- | +| ONLINE | 0 | The device is online. | +| READY | 1 | The device is ready, and the device information has been synchronized.| +| OFFLINE | 2 | The device is offline. | +| CHANGE | 3 | The device information is changed. | +## SubscribeInfo -## DeviceType +Defines subscription information. -Enumerates the device types. +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| ------------- | --------------------------------- | ---- | ----------------- | +| subscribeId | number | Yes | Subscription ID, used to identify a device discovery period.| +| mode | [DiscoverMode ](#discovermode) | No | Device discovery mode. | +| medium | [ExchangeMedium](#exchangemedium) | No | Medium used for device discovery. | +| freq | [ExchangeFreq](#exchangefreq) | No | Frequency of device discovery. | +| isSameAccount | boolean | No | Whether the same account is used on the discovered device. | +| isWakeRemote | boolean | No | Whether to wake up the discovered device. | +| capability | [SubscribeCap](#subscribecap) | No | Discovery capability. | + + +## DiscoverMode + +Enumerates the device discovery modes. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name| Default Value| Description| -| -------- | -------- | -------- | -| SPEAKER | 0x0A | Smart speaker.| -| PHONE | 0x0E | Phone.| -| TABLET | 0x11 | Tablet.| -| WEARABLE | 0x6D | Wearable.| -| TV | 0x9C | Smart TV.| -| CAR | 0x83 | Car.| -| UNKNOWN_TYPE | 0 | Unknown device type.| +| Name | Default Value | Description | +| --------------------- | ---- | ----- | +| DISCOVER_MODE_PASSIVE | 0x55 | Passive discovery.| +| DISCOVER_MODE_ACTIVE | 0xAA | Active discovery.| -## DeviceInfo +## ExchangeMedium -Defines device information. +Enumerates the media used for device discovery. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | number | Yes| Unique device identifier.| -| deviceName | string | Yes| Device name.| -| deviceType | number | Yes| Device type.| +| Name | Default Value | Description | +| ---- | ---- | --------- | +| AUTO | 0 | Automatic. | +| BLE | 1 | Bluetooth. | +| COAP | 2 | Wi-Fi.| +| USB | 3 | USB. | + +## ExchangeFreq + +Enumerates the device discovery frequencies. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ---------- | ---- | ----- | +| LOW | 0 | Low frequency. | +| MID | 1 | Medium frequency. | +| HIGH | 2 | High frequency. | +| SUPER_HIGH | 3 | Ultra-high frequency.| + + +## SubscribeCap + +Enumerates the discovery capabilities. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ------------------------- | ---- | -------------- | +| SUBSCRIBE_CAPABILITY_DDMP | 0 | DDMP capability. This will be deprecated later.| +| SUBSCRIBE_CAPABILITY_OSD | 1 | OSD capability. | + + +## AuthParam + +Defines the authentication parameters. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| --------- | -------------------- | ---- | ---------- | +| authType | number | Yes | Authentication type. | +| extraInfo | {[key:string] : any} | No | Extended field.| + +## AuthInfo + +Defines authentication information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| --------- | -------------------- | ---- | ---------- | +| authType | number | Yes | Authentication type. | +| token | number | Yes | Authentication token. | +| extraInfo | {[key:string] : any} | No | Extended field.| ## DeviceManager @@ -92,12 +194,12 @@ Provides APIs to obtain information about trusted devices and local devices. Bef release(): void -Releases the **DeviceManager** instance that is no longer used. +Releases this **DeviceManager** instance when it is no longer used. **System capability**: SystemCapability.DistributedHardware.DeviceManager - Example - ``` + ```js dmInstance.release(); ``` @@ -111,16 +213,258 @@ Obtains all trusted devices synchronously. **System capability**: SystemCapability.DistributedHardware.DeviceManager - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | -------------------------------------- | --------- | | Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| - Example - ``` + ```js var deviceInfoList = dmInstance.getTrustedDeviceListSync(); ``` +### getTrustedDeviceList8+ + +getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): void + +Obtains all trusted devices. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------- | + | callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | Yes | Callback used to return the list of trusted devices.| + +- Example + ```js + dmInstance.getTrustedDeviceList((err, data) => { + console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + console.log('get trusted device info: ' + JSON.stringify(data)); + } + ); + ``` + +### getTrustedDeviceList8+ + +getTrustedDeviceList(): Promise<Array<DeviceInfo>> + +Obtains all trusted devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the list of trusted devices.| + +- Example + ```js + dmInstance.getTrustedDeviceList().then((data) => { + console.log('get trusted device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + }); + ``` + +### getLocalDeviceInfoSync8+ + +getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) + +Obtains local device information synchronously. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Name | Description | + | -------------------------------------- | --------- | + | Array<[DeviceInfo](#deviceinfo)> | List of local devices obtained.| + +- Example + ```js + var deviceInfo = dmInstance.getLocalDeviceInfoSync(); + ``` + + +### getLocalDeviceInfo8+ + +getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void + +Obtains local device information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------- | + | callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | Yes | Callback used to return the local device information.| + +- Example + ```js + dmInstance.getLocalDeviceInfo((err, data) => { + console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + console.log('get local device info: ' + JSON.stringify(data)); + } + ); + ``` + +### getLocalDeviceInfo8+ + +getLocalDeviceInfo(): Promise<DeviceInfo> + +Obtains local device information. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the local device information.| + +- Example + ```js + dmInstance.getLocalDeviceInfo().then((data) => { + console.log('get local device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + }); + ``` + +### startDeviceDiscovery + +startDeviceDiscovery(subscribeInfo: SubscribeInfo): void + +Starts to discover peripheral devices. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ------------- | ------------------------------- | ---- | ----- | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + +- Example + ```js + // Automatically generate a unique subscription ID. + var subscribeId = Math.floor(Math.random() * 10000 + 1000); + var subscribeInfo = { + "subscribeId": subscribeId, + "mode": 0xAA, // Active discovery + "medium": 0, // Automatic. Multiple media can be used for device discovery. + "freq": 2, // High frequency + "isSameAccount": false, + "isWakeRemote": false, + "capability": 1 + }; + dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. + ``` + +### stopDeviceDiscovery + +stopDeviceDiscovery(subscribeId: number): void + +Stops device discovery. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ----------- | ------ | ---- | ----- | + | subscribeId | number | Yes | Subscription ID.| + +- Example + ```js + // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery. + dmInstance.stopDeviceDiscovery(subscribeId); + ``` + +### authenticateDevice + +authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: AsyncCallback<{deviceId: string, pinToken ?: number}>): void + +Authenticates a device. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | + | authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | + | callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| + +- Example + ```js + // Information about the device to authenticate. The information can be obtained from the device discovery result. + var deviceInfo ={ + "deviceId": "XXXXXXXX", + "deviceName": "", + deviceType: 0x0E + }; + let authParam = { + "authType": 1, // Authentication type. The value 1 means no account PIN authentication. + "extraInfo": {} + } + dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { + if (err) { + console.info(TAG + "authenticateDevice err:" + JSON.stringify(err)); + return; + } + console.info(TAG + "authenticateDevice result:" + JSON.stringify(data)); + token = data.pinToken; + }); + ``` + +### unAuthenticateDevice8+ + +unAuthenticateDevice(deviceInfo: DeviceInfo): void + +Deauthenticates a device. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ---------- | ------------------------- | ---- | ----- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| + +- Example + ```js + dmInstance.unAuthenticateDevice(deviceInfo); + ``` + + +### verifyAuthInfo + +verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void + +Verifies authentication information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------- | + | authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | + | authInfo | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + +- Example + ```js + let authInfo = { + "authType": 1, + "token": xxxxxx, + "extraInfo": {} + } + dmInstance.verifyAuthInfo(authInfo, (err, data) => { + if (err) { + console.info(TAG + "verifyAuthInfo err:" + JSON.stringify(err)); + return; + } + console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data)); + }); + ``` + + ### on('deviceStateChange') on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void @@ -130,13 +474,13 @@ Subscribes to changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **deviceStateChange**, which indicates a device state change event.| - | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes| Callback invoked to return the device information and state.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state. | - Example - ``` + ```js dmInstance.on('deviceStateChange', (data) => { console.info("deviceStateChange on:" + JSON.stringify(data)); } @@ -146,20 +490,20 @@ Subscribes to changes in the device state. ### off('deviceStateChange') -off(type: 'deviceStateChange', callback?: Call back<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void +off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void Unsubscribes from changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **deviceStateChange** indicates an event of device state change.| - | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo)  }> | Yes| Callback invoked to return the device information and state.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. | + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state.| - Example - ``` + ```js dmInstance.off('deviceStateChange', (data) => { console.info('deviceStateChange' + JSON.stringify(data)); } @@ -167,6 +511,95 @@ Unsubscribes from changes in the device state. ``` +### on('deviceFound') + +on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: DeviceInfo }>): void + +Subscribes to device discovery events. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | -------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| + | callback | Callback<{ subscribeId: number, device: DeviceInfo }> | Yes | Callback used for device discovery. | + +- Example + ```js + dmInstance.on('deviceFound', (data) => { + console.info("deviceFound:" + JSON.stringify(data)); + } + ); + ``` + +### off('deviceFound') + +off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: DeviceInfo }>): void + +Unsubscribes from device discovery events. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | + | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used for device discovery, which is invoked to return the device information and state.| + +- Example + ```js + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + } + ); + ``` + +### on('discoverFail') + +on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: number }>): void + +Subscribes to device discovery failures. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | + +- Example + ```js + dmInstance.on('discoverFail', (data) => { + this.log("discoverFail on:" + JSON.stringify(data)); + } + ); + ``` + +### off('discoverFail') + +off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: number }>): void + +Unsubscribes from device discovery failures. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ----------------- | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure.| + +- Example + ```js + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + } + ); + ``` + + ### on('serviceDie') on(type: 'serviceDie', callback: () => void): void @@ -176,13 +609,13 @@ Subscribes to dead events of the **DeviceManager** service. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| - | callback | () => void | Yes| Callback invoked when a dead event of the **DeviceManager** service occurs.| + | Name | Type | Mandatory | Description | + | -------- | ----------------------- | ---- | ---------------------------------------- | + | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | Yes | Callback invoked when a dead event of the **DeviceManager** service occurs. | - Example - ``` + ```js dmInstance.on("serviceDie", () => { console.info("serviceDie on"); } @@ -199,13 +632,13 @@ Unsubscribes from dead events of the **DeviceManager** service. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| - | callback | () => void | No| Callback used to return the dead event of the **DeviceManager** service.| + | Name | Type | Mandatory | Description | + | -------- | ----------------------- | ---- | ---------------------------------------- | + | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | No | Callback used to return the dead event of the **DeviceManager** service. | - Example - ``` + ```js dmInstance.off("serviceDie", () => { console.info("serviceDie off"); } 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-effectKit.md b/en/application-dev/reference/apis/js-apis-effectKit.md new file mode 100644 index 0000000000000000000000000000000000000000..089bf96cb239204c4b52c3ce71848f15141d76a4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-effectKit.md @@ -0,0 +1,310 @@ +# Image Effect + +The **EffectKit** module provides basic image processing capabilities, including brightness adjustment, blurring, grayscale adjustment, and color picker. + +This module provides the following classes: + +- [Filter](#filter): a class that provides the effect chain. +- [Color](#color): a class used to store the color picked. +- [ColorPicker](#colorpicker): a smart color picker. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import effectKit from '@ohos.effectKit'; +``` + +## effectKit.createEffect +createEffect(source: image.PixelMap): Filter + +Creates a **Filter** instance based on the pixel map. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------- | ---- | -------- | +| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. | + +**Return value** + +| Type | Description | +| -------------------------------- | -------------- | +| [Filter](#filter) | Head node of the filter linked list without any effect. If the operation fails, **null** is returned.| + +**Example** + +```js +import image from "@ohos.multimedia.image" +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; +image.createPixelMap(color, opts) + .then((pixelMap) => { + let headFilter = effectKit.createEffect(pixelMap) + }) +``` + +## effectKit.createColorPicker + +createColorPicker(source: image.PixelMap): Promise\ + +Creates a **ColorPicker** instance based on the pixel map. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | -------------------------- | +| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module.| + +**Return value** + +| Type | Description | +| ---------------------- | -------------- | +| Promisse\<[ColorPicker](#colorpicker)> | Promise used to return the **ColorPicker** instance created.| + +**Example** + +```js +import image from "@ohos.multimedia.image" +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; +image.createPixelMap(color, opts, (pixelMap) => { + effectKit.createColorPicker(pixelMap).then(colorPicker => { + console.info("color picker=" + colorPicker); + }) + .catch(ex => console.error(".error=" + ex.toString())) +}) +``` + +## effectKit.createColorPicker + +createColorPicker(source: image.PixelMap, callback: AsyncCallback\): void + +Creates a **ColorPicker** instance based on the pixel map. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | -------------------------- | +| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes |**PixelMap** instance created by the image module. | +| callback | AsyncCallback\<[ColorPicker](#colorpicker)> | Yes | Callback used to return the **ColorPicker** instance created.| + +**Example** + +```js +import image from "@ohos.multimedia.image" +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; +image.createPixelMap(color, opts, (pixelMap) => { + effectKit.createColorPicker(pixelMap, (error, colorPicker) => { + if(error) { + console.log('Failed to create color picker.'); + } else { + console.log('Succeeded in creating color picker.'); + } + }) +}) +``` + +## Color + +A class that stores the color picked. + +**System capability**: SystemCapability.Multimedia.Image.Core + +| Name | Type | Readable| Writable| Description | +| ------ | ----- | ---- | ---- | ---------------- | +| red | number | Yes | No | Value of the red component. | +| green | number | Yes | No | Value of the green component. | +| blue | number | Yes | No | Value of the blue component. | +| alpha | number | Yes | No | Value of the alpha component. | + +## ColorPicker + +A class used to obtain the main color of an image from its data. Before calling any method of **ColorPicker**, use [createColorPicker](#effectkitcreatecolorpicker) to create a **ColorPicker** instance. + +### getMainColor + +getMainColor(): Promise\ + +Obtains the main color of the image and writes the result to a **[Color](#color)** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Return value** + +| Type | Description | +| :------------- | :---------------------------------------------- | +| Promise\<[Color](#color)> | Promise used to return the color value of the main color. If the operation fails, an error message is returned.| + +**Example** + +```js +colorPicker.getMainColor().then(color => { + console.log('Succeeded in getting main color.') + console.info("color[ARGB]=" + color.alpha + "," + color.red + "," + color.green + "," + color.blue); +}).catch(error => { + console.log('Failed to get main color.'); +}) +``` + +### getMainColorSync + +getMainColorSync(): Color + +Obtains the main color of the image and writes the result to a **[Color](#color)** instance. This API returns the result in synchronous mode. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Return value** + +| Type | Description | +| :------- | :----------------------------------- | +| [Color](#color) | Color value of the main color. If the operation fails, **null** is returned.| + +**Example** + +```js +let color = colorPicker.getMainColorSync(); +console.log('get main color =' + color); +``` + +## Filter + +A class used to add a specified effect to an image. Before calling any method of **Filter**, use [createEffect](#effectkitcreateeffect) to create a **Filter** instance. + +### blur + +blur(radius: number): Filter + +Adds the blur effect to the filter linked list, and returns the head node of the linked list. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Blur radius, in pixels. The blur effect is proportional to the configured value. A larger value indicates a more obvious effect.| + +**Return value** + +| Type | Description | +| :------------- | :---------------------------------------------- | +| [Filter](#filter) | Head node of the filter linked list.| + +**Example** + +```js +import image from "@ohos.multimedia.image" +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; +image.createPixelMap(color, opts) + .then((pixelMap) => { + let radius = 5; + let headFilter = effectKit.createEffect(pixelMap) + if (headFilter != null) { + headFilter.blur(radius) + } + }) +``` + +### brightness + +brightness(bright: number): Filter + +Adds the brightness effect to the filter linked list, and returns the head node of the linked list. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ------------------------------------------------------------ | +| bright | number | Yes | Brightness value, ranging from 0 to 1. When the value is **0**, the image brightness remains unchanged.| + +**Return value** + +| Type | Description | +| :------------- | :---------------------------------------------- | +| [Filter](#filter) | Head node of the filter linked list.| + +**Example** + +```js +import image from "@ohos.multimedia.image" +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; +image.createPixelMap(color, opts) + .then((pixelMap) => { + let bright = 0.5; + let headFilter = effectKit.createEffect(pixelMap) + if (headFilter != null) { + headFilter.brightness(bright) + } + }) +``` + +### grayscale + +grayscale(): Filter + +Adds the grayscale effect to the filter linked list, and returns the head node of the linked list. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Return value** + +| Type | Description | +| :------------- | :---------------------------------------------- | +| [Filter](#filter) | Head node of the filter linked list.| + +**Example** + +```js +import image from "@ohos.multimedia.image" +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; +image.createPixelMap(color, opts) + .then((pixelMap) => { + let headFilter = effectKit.createEffect(pixelMap) + if (headFilter != null) { + headFilter.grayscale() + } + }) +``` + +### getPixelMap + +getPixelMap(): image.PixelMap + +Obtains **image.PixelMap** of the source image to which the filter linked list is added. + +**System capability**: SystemCapability.Multimedia.Image.Core + +**Return value** + +| Type | Description | +| :------------- | :---------------------------------------------- | +| [image.PixelMap](js-apis-image.md#pixelmap7) | **image.PixelMap** of the source image.| + +**Example** + +```js +import image from "@ohos.multimedia.image" +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; +image.createPixelMap(color, opts) + .then((pixelMap) => { + let pixel = effectKit.createEffect(pixelMap).grayscale().getPixelMap() + }) +``` 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-eventhub.md b/en/application-dev/reference/apis/js-apis-eventhub.md index a5a25efdbab5c977e92b85a5fcc656f5c3ae3ef7..ca1b1500dcb8836b73abd13e837a0255a78a3a5f 100644 --- a/en/application-dev/reference/apis/js-apis-eventhub.md +++ b/en/application-dev/reference/apis/js-apis-eventhub.md @@ -1,18 +1,12 @@ # EventHub +The **EventHub** module provides APIs to subscribe to, unsubscribe from, and trigger events. + > **NOTE** > -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Implements event subscription, unsubscription, and triggering. - -## Modules to Import - -```js -import Ability from '@ohos.application.Ability' -``` - ## Usage ​Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. diff --git a/en/application-dev/reference/apis/js-apis-extension-context.md b/en/application-dev/reference/apis/js-apis-extension-context.md index 24ca2bb2e99bd5b308aea4683a9242c998417e78..7d7b21f2cb04fbb7c0cb9d9a3581e09813cd00ef 100644 --- a/en/application-dev/reference/apis/js-apis-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-extension-context.md @@ -1,22 +1,20 @@ # ExtensionContext +The **ExtensionContext** module, inherited from **Context**, implements the context for Extension abilities. + +This module allows access to Extension abilities. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Implements the extension context. This module is inherited from **Context**. - -## Modules to Import - -```js -import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility'; -``` ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP. | +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP. | | config | Configuration | Yes| No| Module configuration information.| +| extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) | Yes| No| Extension ability information.| diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md index 62f6d9b631aa687e61fc6a1b4fe26fb72f16f105..66b794234a41c9e57977946adbf02a9f35182b60 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md @@ -1,20 +1,15 @@ # ExtensionRunningInfo +The **ExtensionRunningInfo** module provides running information and states for Extension abilities. + > **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. - -Provides extension running information. - -## Modules to Import - -```js -import abilitymanager from '@ohos.application.abilityManager'; -``` +> The APIs of this module are system APIs and cannot be called by third-party applications. ## Usage -The extension running information is obtained through an **abilityManager** instance. +The Extension ability running information is obtained through an **abilityManager** instance. ```js import abilitymanager from '@ohos.application.abilityManager'; @@ -24,37 +19,16 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { }); ``` - -### Attributes +## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extension | ElementName | Yes| No| Information that matches an extension.| +| extension | ElementName | Yes| No| Information that matches an Extension ability.| | pid | number | Yes| No| Process ID.| | uid | number | Yes| No| User ID.| | processName | string | Yes| No| Process name.| -| startTime | number | Yes| No| Extension start time.| +| startTime | number | Yes| No| Start time of the Extension ability.| | clientPackage | Array<String> | Yes| No| Names of all packages in the process.| -| type | [bundle.ExtensionAbilityType](#bundleextensionabilitytype) | Yes| No| Extension type.| - - -## bundle.ExtensionAbilityType - -Enumerates extension types. - -**System capability**: SystemCapability.BundleManager.BundleFramework - - | Name| Value| Description| -| -------- | -------- | -------- | -| FORM | 0 | Extension information of the form type.< | -| WORK_SCHEDULER | 1 | Extension information of the work scheduler type.< | -| INPUT_METHOD | 2 | Extension information of the input method type.< | -| SERVICE | 3 | Extension information of the service type.< | -| ACCESSIBILITY | 4 | Extension information of the accessibility type.< | -| DATA_SHARE | 5 | Extension information of the data share type.< | -| FILE_SHARE | 6 | Extension information of the file share type.< | -| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type.< | -| WALLPAPER | 8 | Extension information of the wallpaper type.< | -| UNSPECIFIED | 9 | Extension information of the unspecified type.< | +| type | [bundle.ExtensionAbilityType](js-apis-Bundle.md#extensionabilitytype9) | Yes| No| Extension ability type.| diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md index 4c15fefc458a174ee0477d23b77aa9796f2bb051..93941ea52e332de2f3306673c20c74ef176cb808 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -1,5 +1,7 @@ # FeatureAbility +The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connecting to a Service ability. + > **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. @@ -19,7 +21,7 @@ import featureAbility from '@ohos.ability.featureAbility' startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts an ability. This API uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -127,7 +129,7 @@ featureAbility.acquireDataAbilityHelper( startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts an ability. This API uses a callback to return the execution result when the ability is destroyed. +Starts an ability. This API uses an asynchronous callback to return the execution result when the ability is destroyed. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -214,7 +216,6 @@ featureAbility.startAbilityForResult( mykey7: true, }, }, - requestCode: 2, }, ).then((data) => { console.info("==========================>startAbilityForResult=======================>"); @@ -225,7 +226,7 @@ featureAbility.startAbilityForResult( terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses a callback to return the result. +Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -326,13 +327,11 @@ featureAbility.terminateSelfWithResult( }); ``` - - ## featureAbility.hasWindowFocus7+ hasWindowFocus(callback: AsyncCallback\): void -Checks whether the main window of this ability has the focus. This API uses a callback to return the result. +Checks whether the main window of this ability has the focus. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -349,8 +348,6 @@ import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus() ``` - - ## featureAbility.hasWindowFocus7+ hasWindowFocus(): Promise\ @@ -368,19 +365,17 @@ Checks whether the main window of this ability has the focus. This API uses a pr **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus().then((data) => { console.info("==========================>hasWindowFocus=======================>"); }); ``` - - ## featureAbility.getWant getWant(callback: AsyncCallback\): void -Obtains the **Want** object sent from this ability. This API uses a callback to return the result. +Obtains the **Want** object sent from this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -397,8 +392,6 @@ import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant() ``` - - ## featureAbility.getWant getWant(): Promise\ @@ -444,13 +437,11 @@ var context = featureAbility.getContext() context.getBundleName() ``` - - ## featureAbility.terminateSelf7+ terminateSelf(callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses a callback to return the result. +Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -467,8 +458,6 @@ import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf() ``` - - ## featureAbility.terminateSelf7+ terminateSelf(): Promise\ @@ -496,7 +485,7 @@ featureAbility.terminateSelf().then((data) => { connectAbility(request: Want, options:ConnectOptions): number -Connects this ability to a specific Service ability. This API uses a callback to return the result. +Connects this ability to a specific Service ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -505,17 +494,9 @@ Connects this ability to a specific Service ability. This API uses a callback to | Name | Type | Mandatory | Description | | ------- | -------------- | ---- | --------------------- | | request | [Want](js-apis-application-Want.md) | Yes | Service ability to connect.| -| options | ConnectOptions | Yes | Callback used to return the result. | +| options | [ConnectOptions](#connectoptions) | Yes | Callback used to return the result. | -Want - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name | Readable/Writable| Type | Mandatory | Description | -| ----------- | ---- | ------ | ---- | ---------------------------------------- | -| deviceId | Read-only | string | No | Device ID of the Service ability to connect. The default value is the local device ID.| -| bundleName | Read-only | string | Yes | Bundle name of the Service ability to connect. | -| abilityName | Read-only | string | Yes | Class name of the Service ability to connect. | +## ConnectOptions ConnectOptions @@ -523,9 +504,9 @@ ConnectOptions | Name | Readable/Writable| Type | Mandatory | Description | | ------------ | ---- | -------- | ---- | ------------------------- | -| onConnect | Read-only | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect | Read-only | function | Yes | Callback invoked when the connection fails. | -| onFailed | Read-only | function | Yes | Callback invoked when **connectAbility** fails to be called.| +| onConnect7+ | Read-only | function | Yes | Callback invoked when the connection is successful. | +| onDisconnect7+ | Read-only | function | Yes | Callback invoked when the connection fails. | +| onFailed7+ | Read-only | function | Yes | Callback invoked when **connectAbility** fails to be called.| **Return value** @@ -565,7 +546,7 @@ var connId = featureAbility.connectAbility( disconnectAbility(connection: number, callback:AsyncCallback\): void -Disconnects this ability from a specific Service ability. This API uses a callback to return the result. +Disconnects this ability from a specific Service ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -654,8 +635,10 @@ var connId = featureAbility.connectAbility( }, ); -featureAbility.disconnectAbility(connId).then((error,data) => { - console.log('featureAbilityTest result errCode : ' + error.code + " data: " + data); +featureAbility.disconnectAbility(connId).then((data) => { + console.log('data : ' + data); +}).catch((error)=>{ + console.log('featureAbilityTest result errCode : ' + error.code); }); ``` @@ -664,7 +647,7 @@ featureAbility.disconnectAbility(connId).then((error,data) => { getWindow(callback: AsyncCallback\): void -Obtains the window corresponding to this ability. This API uses a callback to return the result. +Obtains the window corresponding to this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -914,7 +897,7 @@ Enumerates operation types of the Data ability. ## StartAbilityParameter -**System capability**: SystemCapability.AbilityRuntime.FAModel +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | Name | Readable/Writable| Type | Mandatory | Description | | ------------------- | ---- | -------------------- | ---- | -------------------------------------- | @@ -925,7 +908,7 @@ Enumerates operation types of the Data ability. **System capability**: SystemCapability.Ability.AbilityBase -| Name | Value | Description | +| Name | Name | Description | | ------------------------------------ | ---------- | ---------------------------------------- | | FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | | FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | @@ -933,10 +916,10 @@ Enumerates operation types of the Data ability. | FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | | FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | 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-formInfo.md b/en/application-dev/reference/apis/js-apis-formInfo.md index 502a8212f54e8cdefa381a8b862f1148e2f73b11..15e434ce7b5e6e29d67749b6d12a1069fb258c75 100644 --- a/en/application-dev/reference/apis/js-apis-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-formInfo.md @@ -1,11 +1,11 @@ # FormInfo +The **FormInfo** module provides widget information and state. + > **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. -Provides widget information. - ## Modules to Import ``` @@ -14,15 +14,13 @@ import formInfo from '@ohos.application.formInfo'; ## Required Permissions -None. +None ## FormInfo Describes widget information. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form | Name | Readable/Writable| Type | Description | | ----------- | -------- | -------------------- | ------------------------------------------------------------ | @@ -43,15 +41,13 @@ SystemCapability.Ability.Form | updateDuration | Read only | string | Widget update period.| | defaultDimension | Read only | number | Default dimension of the widget. | | supportDimensions | Read only | Array<number> | Dimensions supported by the widget. | -| customizeData | Read only | {[key: string]: [value: string]} | Custom data of the widget. | +| customizeData | Read only | {[key: string]: [value: string]} | Custom data of the widget. | ## FormType Enumerates the widget types. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form | Name | Value | Description | | ----------- | ---- | ------------ | @@ -61,13 +57,11 @@ SystemCapability.Ability.Form Enumerates the color modes supported by the widget. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form | Name | Value | Description | | ----------- | ---- | ------------ | -| MODE_AUTO | -1 | Automatic mode. | +| MODE_AUTO | -1 | Auto mode. | | MODE_DARK | 0 | Dark mode. | | MODE_LIGHT | 1 | Light mode. | @@ -75,22 +69,18 @@ SystemCapability.Ability.Form Describes the widget state information. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form | Name | Readable/Writable| Type | Description | | ----------- | -------- | -------------------- | ------------------------------------------------------------ | -| formState | Read only | [FormState](#formstate) | Widget state. | +| formState | Read only | [FormState](#formstate) | Widget state. | | want | Read only | Want | Want text. | ## FormState Enumerates the widget states. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form | Name | Value | Description | | ----------- | ---- | ------------ | @@ -102,13 +92,11 @@ SystemCapability.Ability.Form Enumerates the widget parameters. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form | Name | Value | Description | | ----------- | ---- | ------------ | -| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | ID of a widget. | +| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | ID of a widget.
**System API**: This is a system API and cannot be called by third-party applications. | | DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | | NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | | MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | diff --git a/en/application-dev/reference/apis/js-apis-formbindingdata.md b/en/application-dev/reference/apis/js-apis-formbindingdata.md index 622f78b73e55afbe4fdcf8b342597b3ba44edeeb..612b2dc84f23f465a844d73656954bc983c5a233 100644 --- a/en/application-dev/reference/apis/js-apis-formbindingdata.md +++ b/en/application-dev/reference/apis/js-apis-formbindingdata.md @@ -1,5 +1,7 @@ # FormBindingData +The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. + > **NOTE** > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -26,7 +28,7 @@ Creates a **FormBindingData** object. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object or string| No | Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| +| obj | Object or string| No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| **Return value** @@ -63,4 +65,4 @@ Describes a **FormBindingData** object. | Name| Readable| Writable| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -------- | -| data | Yes| No| Object | Yes| Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| +| data | Yes| No| Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| diff --git a/en/application-dev/reference/apis/js-apis-formerror.md b/en/application-dev/reference/apis/js-apis-formerror.md index 62e062c25eab28cfa018f4971da3e5317db7d448..b5868572cb1d74e528b029609da121a4db0b3ca6 100644 --- a/en/application-dev/reference/apis/js-apis-formerror.md +++ b/en/application-dev/reference/apis/js-apis-formerror.md @@ -1,11 +1,11 @@ # FormError +The **FormError** module provides error codes for widgets. + > **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. -Provides widget-related error codes. - ## Modules to Import ``` diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md index cd6b0eaff6f6f35da2f2899efe36312943ee66d8..daea33dbb50edf3aec50c84eee9795339bd9c43a 100644 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ b/en/application-dev/reference/apis/js-apis-formextension.md @@ -1,12 +1,12 @@ # FormExtension +The **FormExtension** module provides APIs related to Form Extension abilities. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Provides **FormExtension** APIs. - ## Modules to Import ``` @@ -35,15 +35,15 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | - | want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| **Return value** - | Type | Description | - | ------------------------------------------------------------ | ----------------------------------------------------------- | - | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| **Example** @@ -72,9 +72,9 @@ Called to notify the widget provider that a temporary widget has been converted **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | formId | string | Yes | ID of the widget that requests to be converted to a normal one.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| **Example** @@ -96,9 +96,9 @@ Called to notify the widget provider that a widget has been updated. After obtai **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget that requests to be updated.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget that requests to be updated.| **Example** @@ -127,9 +127,9 @@ Called to notify the widget provider of the change of visibility. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | ------------------------- | ---- | ---------------------------- | - | newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ---------------------------- | +| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| **Example** @@ -162,10 +162,10 @@ Called to instruct the widget provider to receive and process the widget event. **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------ | ---- | ---------------------- | - | formId | string | Yes | ID of the widget that requests the event.| - | message | string | Yes | Event message. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------- | +| formId | string | Yes | ID of the widget that requests the event.| +| message | string | Yes | Event message. | **Example** @@ -187,9 +187,9 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget to be destroyed.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget to be destroyed.| **Example** @@ -211,9 +211,9 @@ Called when the configuration of the environment where the ability is running is **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| **Example** @@ -225,28 +225,28 @@ Called when the configuration of the environment where the ability is running is } ``` - ## FormExtension.onAcquireFormState +## FormExtension.onAcquireFormState onAcquireFormState?(want: Want): formInfo.FormState; -Called when the widget provider receives the status query result of a specified service widget. By default, the initial state is returned. +Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. **System capability**: SystemCapability.Ability.Form **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| **Example** ```js - import fromInfo from '@ohos.application.fromInfo' + import formInfo from '@ohos.application.formInfo' class MyFormExtension extends FormExtension { onAcquireFormState(want) { console.log('FormExtension onAcquireFormState, want:' + want); - return fromInfo.FormState.UNKNOWN; + return formInfo.FormState.UNKNOWN; } } ``` diff --git a/en/application-dev/reference/apis/js-apis-formextensioncontext.md b/en/application-dev/reference/apis/js-apis-formextensioncontext.md index 4e877102c65aaf630ee5d5e12eff7d3c9e611b42..f2e1fe143fbac2991698d2dd4244d88b23b0ebd5 100644 --- a/en/application-dev/reference/apis/js-apis-formextensioncontext.md +++ b/en/application-dev/reference/apis/js-apis-formextensioncontext.md @@ -1,86 +1,87 @@ # FormExtensionContext -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. +The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for Form Extension abilities. -Implements the context that provides the capabilities and APIs of **FormExtension**. This class is inherited from **ExtensionContext**. +You can use the APIs of this module to start abilities. -## Modules to Import - -```js -import FormExtension from '@ohos.application.FormExtension'; -``` +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. -## FormExtensionContext.updateForm +## FormExtensionContext.startAbility -updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void +startAbility(want: Want, callback: AsyncCallback<void>): void -Updates a widget. This method uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name | Type | Mandatory| Description | - | --------------- | ------------------------------------------------------------ | ---- | -------------------------------------- | - | formId | string | Yes | ID of the widget that requests to be updated. | - | formBindingData | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | New data of the widget. | - | callback | AsyncCallback\ | Yes | Callback used to return the result indicating whether the method is successfully called.| +| Name| Type | Mandatory| Description | +| ------| --------------------------------- | ---- | -------------------------------------- | +| want| [Want](js-apis-application-Want.md) | Yes | Information about the ability to start, such as the ability name and bundle name.| +| callback| AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2, (data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }); - } - } - - - ``` +```js +var want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: {} +} +this.context.startAbility(want, function(err) { + console.info(err.code); +}) +``` -## FormExtensionContext.updateForm +## FormExtensionContext.startAbility -updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ +startAbility(want: Want): Promise<void> -Updates a widget. This method uses a promise to return the result. +Starts an ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name | Type | Mandatory| Description | - | --------------- | ------------------------------------------------------------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget that requests to be updated.| - | formBindingData | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | New data of the widget. | +| Name| Type | Mandatory| Description | +| ------| --------------------------------- | ---- | -------------------------------------- | +| want| [Want](js-apis-application-Want.md) | Yes | Information about the ability to start, such as the ability name and bundle name.| **Return value** - | Type | Description | - | -------------- | --------------------------------- | - | Promise\ | Promise returned with the result indicating whether the method is successfully called.| +| Type | Description | +| ------------ | ---------------------------------- | +| Promise\ | Promise used to return the result.| **Example** - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - - ``` +```js +var want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: {} +} +this.context.startAbility(want).then(() => { + console.info("StartAbility Success"); +}).catch((error) => { + console.info("StartAbility failed"); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md index 91ea521d2bcdece8aa8b3f7b4fc7c278db4c2ba1..769b226018f184016164e0866c4020fa5e601c5a 100644 --- a/en/application-dev/reference/apis/js-apis-formhost.md +++ b/en/application-dev/reference/apis/js-apis-formhost.md @@ -1,11 +1,11 @@ # FormHost +The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets, send notifications to widgets, and obtain widget information and status. + > **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. -Provides APIs related to the widget host. - ## Modules to Import ``` @@ -24,9 +24,11 @@ deleteForm(formId: string, callback: AsyncCallback<void>): void; Deletes a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -52,9 +54,11 @@ deleteForm(formId: string): Promise<void>; Deletes a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -85,9 +89,11 @@ releaseForm(formId: string, callback: AsyncCallback<void>): void; Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -113,9 +119,11 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback< Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -142,9 +150,11 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void>; Releases a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -176,9 +186,11 @@ requestForm(formId: string, callback: AsyncCallback<void>): void; Requests a widget update. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -204,9 +216,11 @@ requestForm(formId: string): Promise<void>; Requests a widget update. This API uses a promise to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -237,9 +251,11 @@ castTempForm(formId: string, callback: AsyncCallback<void>): void; Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -265,9 +281,11 @@ castTempForm(formId: string): Promise<void>; Converts a temporary widget to a normal one. This API uses a promise to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -298,9 +316,11 @@ notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void Instructs the widget framework to make a widget visible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -326,9 +346,11 @@ notifyVisibleForms(formIds: Array<string>): Promise<void>; Instructs the widget framework to make a widget visible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -359,9 +381,11 @@ notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<vo Instructs the widget framework to make a widget invisible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -387,9 +411,11 @@ notifyInvisibleForms(formIds: Array<string>): Promise<void>; Instructs the widget framework to make a widget invisible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -420,9 +446,11 @@ enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void& Instructs the widget framework to make a widget updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -448,9 +476,11 @@ enableFormsUpdate(formIds: Array<string>): Promise<void>; Instructs the widget framework to make a widget updatable. This API uses a promise to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -481,9 +511,11 @@ disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void Instructs the widget framework to make a widget not updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget cannot receive updates from the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -509,9 +541,11 @@ disableFormsUpdate(formIds: Array<string>): Promise<void>; Instructs the widget framework to make a widget not updatable. This API uses a promise to return the result. After this API is called, the widget cannot receive updates from the widget provider. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -542,9 +576,9 @@ isSystemReady(callback: AsyncCallback<void>): void; Checks whether the system is ready. This API uses an asynchronous callback to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -569,9 +603,9 @@ isSystemReady(): Promise<void>; Checks whether the system is ready. This API uses a promise to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Return value** @@ -596,9 +630,11 @@ getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -625,9 +661,11 @@ getAllFormsInfo(): Promise<Array<formInfo.FormInfo>>; Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. -**System capability** +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Return value** @@ -652,9 +690,11 @@ getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.Fo Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -682,9 +722,11 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback< Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -713,9 +755,11 @@ getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formI Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. -**System capability** +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -746,9 +790,11 @@ deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<numb Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -776,9 +822,11 @@ deleteInvalidForms(formIds: Array<string>): Promise<number>; Deletes invalid widgets from the list. This API uses a promise to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -809,9 +857,11 @@ acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo&g Obtains the widget state. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -848,6 +898,12 @@ acquireFormState(want: Want): Promise<formInfo.FormStateInfo>; Obtains the widget state. This API uses a promise to return the result. +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type | Mandatory| Description | @@ -860,10 +916,6 @@ Obtains the widget state. This API uses a promise to return the result. | :------------ | :---------------------------------- | | Promise<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Promise used to return the widget state.| -**System capability** - -SystemCapability.Ability.Form - **Example** ```js @@ -890,9 +942,9 @@ on(type: "formUninstall", callback: Callback<string>): void; Subscribes to widget uninstall events. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -916,9 +968,9 @@ off(type: "formUninstall", callback?: Callback<string>): void; Unsubscribes from widget uninstall events. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -942,9 +994,11 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: A Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -971,9 +1025,11 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise< Instructs the widgets to make themselves visible. This API uses a promise to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1005,9 +1061,11 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, c Instructs the widgets to enable or disable updates. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1034,9 +1092,11 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Instructs the widgets to enable or disable updates. This API uses a promise to return the result. -**System capability** +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-formprovider.md index 0637af7ceb3c1368f242d91d9f4b59566b7f08df..81855948f4994b85d601763ffe5e817a175d3733 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-formprovider.md @@ -1,6 +1,6 @@ # FormProvider -The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and release a widget release. +The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. > **NOTE** > @@ -28,11 +28,11 @@ SystemCapability.Ability.Form **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------- | -| formId | string | Yes | ID of a widget. | -| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------- | + | formId | string | Yes | ID of a widget. | + | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -57,16 +57,16 @@ SystemCapability.Ability.Form **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------- | -| formId | string | Yes | ID of a widget. | -| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------- | + | formId | string | Yes | ID of a widget. | + | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | **Return value** -| Type | Description | -| ------------- | ---------------------------------- | -| Promise\ |Promise used to return the result. | + | Type | Description | + | ------------- | ---------------------------------- | + | Promise\ |Promise used to return the result. | **Example** @@ -91,11 +91,11 @@ SystemCapability.Ability.Form **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| formId | string | Yes | ID of the widget to update.| -| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + | Name| Type | Mandatory| Description | + | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | + | formId | string | Yes | ID of the widget to update.| + | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -122,10 +122,10 @@ SystemCapability.Ability.Form **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| formId | string | Yes | ID of the widget to update.| -| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | + | Name| Type | Mandatory| Description | + | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | + | formId | string | Yes | ID of the widget to update.| + | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | **Return value** diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 01a012065ab52ac2e7a1dc781b608ec865394c31..f15805a326e19b0a579d1da1ae0e44e9937fef6f 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -8,8 +8,7 @@ Location services provide basic functions such as GNSS positioning, network posi ## Modules to Import - -``` +```js import geolocation from '@ohos.geolocation'; ``` @@ -23,17 +22,18 @@ Registers a listener for location changes with a location request initiated. **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| | request | LocationRequest | Yes| Location request.| | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -52,16 +52,17 @@ Unregisters the listener for location changes with the corresponding location re **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| | callback | Callback<[Location](#location)> | No| Callback used to return the location change event.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -81,18 +82,19 @@ Registers a listener for location service status change events. **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.| -- Example +**Example** - ``` + ```js var locationServiceState = (state) => { - console.log('locationServiceState: ' + state); + console.log('locationServiceState: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); ``` @@ -108,18 +110,19 @@ Unregisters the listener for location service status change events. **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| | callback | Callback<boolean> | No| Callback used to return the location service status change event.| -- Example +**Example** - ``` + ```js var locationServiceState = (state) => { - console.log('locationServiceState: state: ' + state); + console.log('locationServiceState: state: ' + JSON.stringify(state)); } geolocation.on('locationServiceState', locationServiceState); geolocation.off('locationServiceState', locationServiceState); @@ -136,19 +139,20 @@ Registers a listener for cached GNSS location reports. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| | request | CachedGnssLocationsRequest | Yes| Request for reporting cached GNSS location.| | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| -- Example +**Example** - ``` + ```js var cachedLocationsCb = (locations) => { - console.log('cachedGnssLocationsReporting: locations: ' + locations); + console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); @@ -165,18 +169,19 @@ Unregisters the listener for cached GNSS location reports. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| | callback | Callback<boolean> | No| Callback used to return cached GNSS locations.| -- Example +**Example** - ``` + ```js var cachedLocationsCb = (locations) => { - console.log('cachedGnssLocationsReporting: locations: ' + locations); + console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb); @@ -194,18 +199,19 @@ Registers a listener for GNSS satellite status change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| | callback | Callback<SatelliteStatusInfo> | Yes| Callback used to return GNSS satellite status changes.| -- Example +**Example** - ``` + ```js var gnssStatusCb = (satelliteStatusInfo) => { - console.log('gnssStatusChange: ' + satelliteStatusInfo); + console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); ``` @@ -221,17 +227,18 @@ Unregisters the listener for GNSS satellite status change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| | callback | Callback<SatelliteStatusInfo> | No| Callback used to return GNSS satellite status changes.| -- Example +**Example** - ``` + ```js var gnssStatusCb = (satelliteStatusInfo) => { - console.log('gnssStatusChange: ' + satelliteStatusInfo); + console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } geolocation.on('gnssStatusChange', gnssStatusCb); geolocation.off('gnssStatusChange', gnssStatusCb); @@ -248,18 +255,19 @@ Registers a listener for GNSS NMEA message change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.| -- Example +**Example** - ``` + ```js var nmeaCb = (str) => { - console.log('nmeaMessageChange: ' + str); + console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb ); ``` @@ -275,18 +283,19 @@ Unregisters the listener for GNSS NMEA message change events. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| | callback | Callback<string> | No| Callback used to return GNSS NMEA message changes.| -- Example +**Example** - ``` + ```js var nmeaCb = (str) => { - console.log('nmeaMessageChange: ' + str); + console.log('nmeaMessageChange: ' + JSON.stringify(str)); } geolocation.on('nmeaMessageChange', nmeaCb); geolocation.off('nmeaMessageChange', nmeaCb); @@ -303,60 +312,38 @@ Registers a listener for status change events of the specified geofence. **System capability**: SystemCapability.Location.Location.Geofence -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| | request | GeofenceRequest | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| -- Example +**Example** - ``` - import WantAgent from '@ohos.wantAgent'; - import { OperationType, WantAgentFlags } from '@ohos.wantagent'; - // WantAgent object - var wantAgent; - // getWantAgent callback - function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } - } - // WantAgentInfo object - var wantAgentInfo = { + ```js + import geolocation from '@ohos.geolocation'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } } ], - operationType: OperationType.START_ABILITIES, + operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] - } - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; - geolocation.on('fenceStatusChange', requestInfo, wantAgent); + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); + }); ``` @@ -370,60 +357,91 @@ Unregisters the listener for status change events of the specified geofence. **System capability**: SystemCapability.Location.Location.Geofence -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| | request | GeofenceRequest | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| -- Example +**Example** - ``` - import WantAgent from '@ohos.wantAgent'; - import { OperationType, WantAgentFlags } from '@ohos.wantagent'; - // WantAgent object - var wantAgent; - // getWantAgent callback - function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } - } - // WantAgentInfo object - var wantAgentInfo = { + ```js + import geolocation from '@ohos.geolocation'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } } ], - operationType: OperationType.START_ABILITIES, + operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + geolocation.on('fenceStatusChange', requestInfo, wantAgentObj); + geolocation.off('fenceStatusChange', requestInfo, wantAgentObj); + }); + ``` + + +## geolocation.on('countryCodeChange')9+ + +on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; + +Subscribe to country code information reporting events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is "countrycodechange", which means subscribing to the submission of country code information. | + | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | + + +**Example** + + ```js + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); } - WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; - geolocation.on('fenceStatusChange', requestInfo, wantAgent); - geolocation.off('fenceStatusChange', requestInfo, wantAgent); + geolocation.on('countryCodeChange', callback); + ``` + + +## geolocation.off('countryCodeChange')9+ + +off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; + +Unsubscribe from the country code to report events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is "countrycodechange", which means unsubscribing to the submission of country code information. | + | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | + + +**Example** + + ```js + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + geolocation.on('countryCodeChange', callback); + geolocation.off('countryCodeChange', callback); ``` @@ -438,18 +456,24 @@ Obtains the current location. This API uses an asynchronous callback to return t **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { - console.log('locationChanger: ' + err + 'data: ' + location); + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } }; geolocation.getCurrentLocation(requestInfo, locationChange); geolocation.getCurrentLocation(locationChange); @@ -467,22 +491,24 @@ Obtains the current location. This API uses a promise to return the result. **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<[Location](#location)> | Promise used to return the current location.| -- Example +**Example** - ``` + ```js var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; - locationEventListener.getCurrentLocation(requestInfo).then((result) => { + geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); }); ``` @@ -498,17 +524,23 @@ Obtains the previous location. This API uses an asynchronous callback to return **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the previous location.| -- Example +**Example** - ``` + ```js geolocation.getLastLocation((err, data) => { - console.log('getLastLocation: ' + err + " data: " + JSON.stringify(data)); + if (err) { + console.log('getLastLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getLastLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -523,15 +555,16 @@ Obtains the previous location. This API uses a promise to return the result. **System capability**: SystemCapability.Location.Location.Core -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<[Location](#location)> | Promise used to return the previous location.| -- Example +**Example** - ``` + ```js geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -549,17 +582,22 @@ Checks whether the location service is enabled. This API uses an asynchronous ca **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.isLocationEnabled((err, data) => { - console.log('isLocationEnabled: ' + err + " data: " + data); + if (err) { + console.log('isLocationEnabled: err=' + JSON.stringify(err)); + } + if (data) { + console.log('isLocationEnabled: data=' + JSON.stringify(data)); + } }); ``` @@ -574,14 +612,15 @@ Checks whether the location service is enabled. This API uses a promise to retur **System capability**: SystemCapability.Location.Location.Core -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| -- Example +**Example** - ``` + ```js geolocation.isLocationEnabled().then((result) => { console.log('promise, isLocationEnabled: ' + result); }); @@ -599,17 +638,22 @@ Requests to enable the location service. This API uses an asynchronous callback **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.requestEnableLocation((err, data) => { - console.log('requestEnableLocation: ' + err + " data: " + data); + if (err) { + console.log('requestEnableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('requestEnableLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -624,17 +668,17 @@ Requests to enable the location service. This API uses a promise to return the r **System capability**: SystemCapability.Location.Location.Core -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.requestEnableLocation().then((result) => { - console.log('promise, requestEnableLocation: ' + result); + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); ``` @@ -645,23 +689,28 @@ enableLocation(callback: AsyncCallback<boolean>) : void; Enables the location service. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.enableLocation((err, data) => { - console.log('enableLocation: ' + err + " data: " + data); + if (err) { + console.log('enableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('enableLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -672,23 +721,23 @@ enableLocation() : Promise<boolean> Enables the location service. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.enableLocation().then((result) => { - console.log('promise, enableLocation: ' + result); + console.log('promise, enableLocation: ' + JSON.stringify(result)); }); ``` @@ -698,23 +747,28 @@ disableLocation(callback: AsyncCallback<boolean>) : void; Disables the location service. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.disableLocation((err, data) => { - console.log('disableLocation: ' + err + " data: " + data); + if (err) { + console.log('disableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('disableLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -725,23 +779,23 @@ disableLocation() : Promise<boolean> Disables the location service. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. -**Permission required**: ohos.permission.LOCATION +**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Location.Location.Core -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the location service status.| - -- Example +**Example** - ``` + ```js geolocation.disableLocation().then((result) => { - console.log('promise, disableLocation: ' + result); + console.log('promise, disableLocation: ' + JSON.stringify(result)); }); ``` @@ -755,17 +809,22 @@ Checks whether the (reverse) geocoding service is available. This API uses an as **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the (reverse) geocoding service status.| - -- Example +**Example** - ``` + ```js geolocation.isGeoServiceAvailable((err, data) => { - console.log('isGeoServiceAvailable: ' + err + " data: " + data); + if (err) { + console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); + } + if (data) { + console.log('isGeoServiceAvailable: data=' + JSON.stringify(data)); + } }); ``` @@ -780,22 +839,21 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro **System capability**: SystemCapability.Location.Location.Geocoder -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the (reverse) geocoding service status.| - -- Example +**Example** - ``` + ```js geolocation.isGeoServiceAvailable().then((result) => { - console.log('promise, isGeoServiceAvailable: ' + result); + console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); ``` - ## geolocation.getAddressesFromLocation getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void @@ -806,18 +864,24 @@ Converts coordinates into geographic description through reverse geocoding. This **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| -- Example +**Example** - ``` + ```js var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { - console.log('getAddressesFromLocation: ' + err + " data: " + JSON.stringify(data)); + if (err) { + console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocation: data=' + JSON.stringify(data)); + } }); ``` @@ -832,19 +896,21 @@ Converts coordinates into geographic description through reverse geocoding. This **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result.| -- Example +**Example** - ``` + ```js var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -862,19 +928,24 @@ Converts geographic description into coordinates through geocoding. This API use **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| - -- Example +**Example** - ``` + ```js var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { - console.log('getAddressesFromLocationName: ' + err + " data: " + JSON.stringify(data)); + if (err) { + console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocationName: data=' + JSON.stringify(data)); + } }); ``` @@ -889,19 +960,21 @@ Converts geographic description into coordinates through geocoding. This API use **System capability**: SystemCapability.Location.Location.Geocoder -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<Array<[GeoAddress](#geoaddress)>> | Callback used to return the geocoding result.| -- Example +**Example** - ``` + ```js var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -909,7 +982,6 @@ Converts geographic description into coordinates through geocoding. This API use ``` - ## geolocation.getCachedGnssLocationsSize8+ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; @@ -920,16 +992,22 @@ Obtains the number of cached GNSS locations. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | -- Example +**Example** - ``` + ```js geolocation.getCachedGnssLocationsSize((err, size) => { - console.log('getCachedGnssLocationsSize: err:' + err + " size: " + size); + if (err) { + console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); + } + if (size) { + console.log('getCachedGnssLocationsSize: size=' + JSON.stringify(size)); + } }); ``` @@ -944,16 +1022,17 @@ Obtains the number of cached GNSS locations. **System capability**: SystemCapability.Location.Location.Gnss -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<number> | Promise used to return the number of cached GNSS locations.| -- Example +**Example** - ``` + ```js geolocation.getCachedGnssLocationsSize().then((result) => { - console.log('promise, getCachedGnssLocationsSize: ' + result); + console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); ``` @@ -968,16 +1047,22 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **System capability**: SystemCapability.Location.Location.Gnss -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.flushCachedGnssLocations((err, result) => { - console.log('flushCachedGnssLocations: err:' + err + " result: " + result); + if (err) { + console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); + } + if (result) { + console.log('flushCachedGnssLocations: result=' + JSON.stringify(result)); + } }); ``` @@ -992,16 +1077,17 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **System capability**: SystemCapability.Location.Location.Gnss -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.flushCachedGnssLocations().then((result) => { - console.log('promise, flushCachedGnssLocations: ' + result); + console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); ``` @@ -1016,18 +1102,24 @@ Sends an extended command to the location subsystem. This API can only be called **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | command | LocationCommand | Yes| Extended command (string) to be sent.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -- Example +**Example** - ``` + ```js var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { - console.log('sendCommand: err:' + err + " result: " + result); + if (err) { + console.log('sendCommand: err=' + JSON.stringify(err)); + } + if (result) { + console.log('sendCommand: result=' + JSON.stringify(result)); + } }); ``` @@ -1042,22 +1134,24 @@ Sends an extended command to the location subsystem. This API can only be called **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | command | LocationCommand | Yes| Extended command (string) to be sent.| -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Callback used to return the operation result.| -- Example +**Example** - ``` + ```js var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { - console.log('promise, sendCommand: ' + result); + console.log('promise, sendCommand: ' + JSON.stringify(result)); }); ``` @@ -1068,23 +1162,29 @@ isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback&l Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Example +**Example** - ``` + ```js geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result); + if (err) { + console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); + } + if (result) { + console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); + } }); ``` @@ -1095,27 +1195,29 @@ isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean> Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Example +**Example** - ``` + ```js geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + result); + console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); }); ``` @@ -1126,24 +1228,30 @@ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - console.log('isLocationPrivacyConfirmed: err:' + err + " result: " + result); + if (err) { + console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); + } + if (result) { + console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); + } }); ``` @@ -1154,32 +1262,540 @@ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolea Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -- Parameters - | Name| Type| Mandatory| Description| +**Parameters** + + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Return value - | Name| Description| +**Return value** + + | Name| Description| | -------- | -------- | | Promise<boolean> | Callback used to return the operation result.| -- Example +**Example** - ``` + ```js geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + result); + console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); + }); + ``` + + +## geolocation.getCountryCode9+ + +getCountryCode(callback: AsyncCallback<CountryCode>) : void; + +Query the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<CountryCode> | Yes | Callback is used to receive the country code. | + +**Example**: + + ```js + geolocation.getCountryCode((err, result) => { + if (err) { + console.log('getCountryCode: err=' + JSON.stringify(err)); + } + if (result) { + console.log('getCountryCode: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geolocation.getCountryCode9+ + +getCountryCode() : Promise<CountryCode>; + +Query the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + +None + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<CountryCode> | return country code. | + +**Example**: + + ```js + geolocation.getCountryCode() + .then((result) => { + console.log('promise, getCountryCode: result=' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCountryCode: error=' + JSON.stringify(error)); + }); + ``` + + +## geolocation.enableLocationMock9+ + +enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; + +Enable the position simulation function of a scene, and only one scene can be enabled at the same time. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates under what scenario the position simulation function is enabled. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.enableLocationMock(request, (err, result) => { + if (err) { + console.log('enableLocationMock: err=' + JSON.stringify(err)); + } + if (result) { + console.log('enableLocationMock: result=' + JSON.stringify(result)); + } + }); + ``` + +## geolocation.enableLocationMock9+ + +enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; + +Enable the position simulation function of a scene, and only one scene can be enabled at the same time. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates which scene's position simulation function is enabled. If this parameter is not carried, it means that the position simulation function of all scenes is enabled. | + + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.enableLocationMock(request) + .then((result) => { + if (result) { + console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geolocation.disableLocationMock9+ + +disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; + +To disable the position simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.disableLocationMock(request, (err, result) => { + if (err) { + console.log('disableLocationMock: err=' + JSON.stringify(err)); + } + if (result) { + console.log('disableLocationMock: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geolocation.disableLocationMock9+ + +disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; + +To disable the position simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr, otherwise it will return an error message | + +**Example**: + + ```js + var request = {"scenario": 0x0301}; + geolocation.disableLocationMock(request) + .then((result) => { + if (result) { + console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geolocation.setMockedLocations9+ + +setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; + +Set the simulated location information, and then report the simulated location at the time interval carried in the interface. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations": locations}; + geolocation.setMockedLocations(config, (err, data) => { + if (err) { + console.log('setMockedLocations: err=' + JSON.stringify(err)); + } + if (data) { + console.log('setMockedLocations: data=' + JSON.stringify(data)); + } + }); + ``` + +## geolocation.setMockedLocations9+ + +setMockedLocations(config: LocationMockConfig) : Promise<void>; + +Set the simulated location information, and then report the simulated location at the time interval carried in the interface. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations":locations}; + geolocation.setMockedLocations(config) + .then((result) => { + if (result) { + console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); + } + }); + ``` + + + +## geolocation.enableReverseGeocodingMock9+ + +enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; + +Enable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + geolocation.enableReverseGeocodingMock((err, data) => { + if (err) { + console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + if (data) { + console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); + } + }); + ``` + + +## geolocation.enableReverseGeocodingMock9+ + +enableReverseGeocodingMock() : Promise<void>; + +Enable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters**: + +None + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + geolocation.enableReverseGeocodingMock() + .then((result) => { + if (result) { + console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); + } + }); + ``` + + +## geolocation.disableReverseGeocodingMock9+ + +disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; + +Disable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters**: + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message | + +**Example**: + + ```js + geolocation.disableReverseGeocodingMock((err, result) => { + if (err) { + console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); + } + if (result) { + console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); + } + }); + ``` + + +## geolocation.disableReverseGeocodingMock9+ + +disableReverseGeocodingMock() : Promise<void>; + +Disable reverse geocoding simulation function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters**: + +None + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + geolocation.disableReverseGeocodingMock() + .then((result) => { + if (result) { + console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); + } }); ``` +## geolocation.setReverseGeocodingMockInfo9+ + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; + +Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | + | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { + if (err) { + console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); + } + if (data) { + console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); + } + }); + ``` + + +## geolocation.setReverseGeocodingMockInfo9+ + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; + +Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | + +**Return value** + + | Name| Description| + | -------- | -------- | + | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | + +**Example**: + + ```js + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + geolocation.setReverseGeocodingMockInfo(mockInfos) + .then((result) => { + if (result) { + console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); + } + }) + .catch((error) => { + if (error) { + console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); + } + }); + ``` + ## LocationRequestPriority @@ -1225,13 +1841,15 @@ Enumerates error codes of the location service. | Name| Default Value| Description| | -------- | -------- | -------- | -| INPUT_PARAMS_ERROR | 101 | Incorrect input parameters.| -| REVERSE_GEOCODE_ERROR | 102 | Failed to call the reverse geocoding API.| -| GEOCODE_ERROR | 103 | Failed to call the geocoding API.| -| LOCATOR_ERROR | 104 | Failed to obtain the location.| -| LOCATION_SWITCH_ERROR | 105 | Failed to change the location service switch.| -| LAST_KNOWN_LOCATION_ERROR | 106 | Failed to obtain the previous location.| -| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | Failed to obtain the location within the specified time.| +| NOT_SUPPORTED9+ | 100 | Indicates that the interface function is not supported. | +| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| +| QUERY_COUNTRY_CODE_ERROR9+ | 108 | Indicates that the country code query failed. | ## ReverseGeoCodeRequest @@ -1279,24 +1897,25 @@ Defines a geographic location. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName | string | No| Landmark of the location.| -| countryCode | string | No| Country code.| -| countryName | string | No| Country name.| -| administrativeArea | string | No| Administrative region name.| -| subAdministrativeArea | string | No| Sub-administrative region name.| -| locality | string | No| Locality information. | -| subLocality | string | No| Sub-locality information. | -| roadName | string | No| Road name.| -| subRoadName | string | No| Auxiliary road information.| -| premises | string | No| House information.| -| postalCode | string | No| Postal code.| -| phoneNumber | string | No| Phone number.| -| addressUrl | string | No| Website URL.| -| descriptions | Array<string> | No| Additional description.| -| descriptionsSize | number | No| Total number of additional descriptions.| +| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | No| Landmark of the location.| +| countryCode7+ | string | No| Country code.| +| countryName7+ | string | No| Country name.| +| administrativeArea7+ | string | No| Administrative region name.| +| subAdministrativeArea7+ | string | No| Sub-administrative region name.| +| locality7+ | string | No| Locality information. | +| subLocality7+ | string | No| Sub-locality information. | +| roadName7+ | string | No| Road name.| +| subRoadName7+ | string | No| Auxiliary road information.| +| premises7+ | string | No| House information.| +| postalCode7+ | string | No| Postal code.| +| phoneNumber7+ | string | No| Phone number.| +| addressUrl7+ | string | No| Website URL.| +| descriptions7+ | Array<string> | No| Additional description.| +| descriptionsSize7+ | number | No| Total number of additional descriptions.| +| isFromMock9+ | Boolean | No | Indicates whether the geographical name information comes from the reverse geocoding simulation function. | ## LocationRequest @@ -1434,13 +2053,68 @@ Defines a location. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| altitude | number | Yes| Location altitude, in meters.| -| accuracy | number | Yes| Location accuracy, in meters.| -| speed | number | Yes| Speed, in m/s.| -| timeStamp | number | Yes| Location timestamp in the UTC format.| -| direction | number | Yes| Direction information.| -| timeSinceBoot | number | Yes| Location timestamp since boot.| -| additions | Array<string> | No| Additional information.| -| additionSize | number | No| Number of additional descriptions.| +| latitude7+ | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude7+ | number | Yes| Location altitude, in meters.| +| accuracy7+ | number | Yes| Location accuracy, in meters.| +| speed7+ | number | Yes| Speed, in m/s.| +| timeStamp7+ | number | Yes| Location timestamp in the UTC format.| +| direction7+ | number | Yes| Direction information.| +| timeSinceBoot7+ | number | Yes| Location timestamp since boot.| +| additions7+ | Array<string> | No| Additional information.| +| additionSize7+ | number | No| Number of additional descriptions.| +| isFromMock9+ | Boolean | No | Indicates whether the location information comes from the location simulation function. | + + +## ReverseGeocodingMockInfo9+ + +The configuration information of the reverse geocoding simulation function includes a location information and a place name information. + +**System capability**:SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| location | ReverseGeoCodeRequest | Yes | Indicates longitude and latitude information. | +| geoAddress | GeoAddress | Yes | Represents a geographic location. | + + +## LocationMockConfig9+ + +The configuration parameters of the location simulation function include the time interval of the simulation position report and the array of simulation locations. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| timeInterval | number | Yes | Indicates the time interval of analog location reporting, in seconds. | +| locations | Array<Location> | Yes | Represents an array of mocked locations. | + + +## CountryCode9+ + +The country code information structure contains the country code string and the source information of the country code. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| country | string | Yes | Represents the country code string. | +| type | CountryCodeType | Yes | Indicates the source of country code information. | + + +## CountryCodeType9+ + +Country code source type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | The country code obtained from the language configuration information of the globalization module. | +| COUNTRY_CODE_FROM_SIM | 2 | The country code obtained from the SIM card. | +| COUNTRY_CODE_FROM_LOCATION | 3 | Based on the user's location information, the country code is queried through reverse geocoding. | +| COUNTRY_CODE_FROM_NETWORK | 4 | The country code obtained from the cellular network registration information. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index f1ef654168a4696ee3f0e54e361a5e81ac7dc6a9..9e0e0bf5160d01596d0c6e0969c3cc783712f45a 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -1,6 +1,8 @@ # Data Request ->![](public_sys-resources/icon-note.gif) **NOTE** +This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. + +>**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. > @@ -18,17 +20,17 @@ import http from '@ohos.net.http'; // Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. let httpRequest = http.createHttp(); -// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements. -// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+ +// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision. +// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); }); httpRequest.request( - // Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData. + // Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL. "EXAMPLE_URL", { method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. - // You can add the header field based on service requirements. + // You can add header fields based on service requirements. header: { 'Content-Type': 'application/json' }, @@ -48,7 +50,7 @@ httpRequest.request( console.info('cookies:' + data.cookies); // 8+ } else { console.info('error:' + JSON.stringify(err)); - // Call the destroy() method to release resources after the call is complete. + // Call the destroy() method to release resources after HttpRequest is complete. httpRequest.destroy(); } } @@ -79,7 +81,7 @@ let httpRequest = http.createHttp(); ## HttpRequest -Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. +HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. ### request @@ -93,9 +95,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ----------------------- | -| url | string | Yes | URL for initiating an HTTP request.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------- | +| url | string | Yes | URL for initiating an HTTP request.| | callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | **Example** @@ -169,15 +171,15 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------ | ---- | -------------------------------------------------- | -| url | string | Yes | URL for initiating an HTTP request. | +| Name | Type | Mandatory| Description | +| ------- | ------------------ | ---- | ----------------------------------------------- | +| url | string | Yes | URL for initiating an HTTP request. | | options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| **Return value** -| Type | Description | -| :-------------------- | :-------------------------------- | +| Type | Description | +| :------------------------------------- | :-------------------------------- | | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| @@ -225,8 +227,7 @@ on\(type: 'headerReceive', callback: AsyncCallback\): void Registers an observer for HTTP Response Header events. >![](public_sys-resources/icon-note.gif) **NOTE** -> -> This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. +>This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. **System capability**: SystemCapability.Communication.NetStack @@ -308,7 +309,6 @@ off\(type: 'headersReceive', callback?: Callback\): void Unregisters the observer for HTTP Response Header events. >![](public_sys-resources/icon-note.gif) **NOTE** -> >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -355,13 +355,13 @@ Specifies the type and value range of the optional parameters in the HTTP reques **System capability**: SystemCapability.Communication.NetStack -| Name | Type | Mandatory| Description | -| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- | -| method | [RequestMethod](#requestmethod) | No | Request method. | +| Name | Type | Mandatory| Description | +| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| method | [RequestMethod](#requestmethod) | No | Request method. | | extraData | string \| Object \| ArrayBuffer8+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.8+
- To pass in a string object, you first need to encode the object on your own.8+ | -| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.| -| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | -| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | +| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | +| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | +| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | ## RequestMethod @@ -388,13 +388,13 @@ Enumerates the response codes for an HTTP request. | Name | Value | Description | | ----------------- | ---- | ------------------------------------------------------------ | -| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | +| OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | -| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | +| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | | NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. | | RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | -| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | +| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | | MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | | MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.| | MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | @@ -418,7 +418,7 @@ Enumerates the response codes for an HTTP request. | REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | | UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | | INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | -| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | +| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | | BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| | UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | | GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. | @@ -433,6 +433,17 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | result | string \| Object \| ArrayBuffer8+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| -| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. The error code can be one of the following:
- 200: common error
- 202: parameter error
- 300: I/O error| +| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | + +## Error Codes + +| Error Code| Description | +| ------ | ------------------------------------------------------------ | +| -1 | Incorrect parameters. | +| 3 | Incorrect URL format. | +| 4 | Built-in request function, protocol, or option not found during build. | +| 5 | Unable to resolve the proxy. | +| 6 | Unable to resolve the host. | +| 7 | Unable to connect to the proxy or host. | diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 5c45f18dc00dba05a5615311c968f342cd6684d3..0abc724302fcf89b86421b90c0bb507f1894b312 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -117,12 +117,12 @@ setSystemLanguage(language: string): boolean Sets the system language. +This is a system API. + **Permission required**: ohos.permission.UPDATE_CONFIGURATION **System capability**: SystemCapability.Global.I18n -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Description | | -------- | ------ | ----- | @@ -211,12 +211,12 @@ setSystemRegion(region: string): boolean Sets the system region. +This is a system API. + **Permission required**: ohos.permission.UPDATE_CONFIGURATION **System capability**: SystemCapability.Global.I18n -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Description | | ------ | ------ | ----- | @@ -258,12 +258,12 @@ setSystemLocale(locale: string): boolean Sets the system locale. +This is a system API. + **Permission required**: ohos.permission.UPDATE_CONFIGURATION **System capability**: SystemCapability.Global.I18n -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Description | | ------ | ------ | --------------- | @@ -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+ @@ -1548,3 +1574,135 @@ Obtains the offset between the time zone represented by a **TimeZone** object an var timezone = i18n.getTimeZone(); timezone.getOffset(1234567890); ``` + +### getAvailableIDs9+ + +static getAvailableIDs(): Array<string> + +Obtains the list of time zone IDs supported by the system. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| ------ | ----------------------- | +| Array<string> | List of time zone IDs supported by the system.| + +**Example** + ``` + var ids = i18n.TimeZone.getAvailableIDs(); + ``` + + +### getAvailableZoneCityIDs9+ + +static getAvailableZoneCityIDs(): Array<string> + +Obtains the list of time zone city IDs supported by the system. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| ------ | ----------------------- | +| Array<string> | List of time zone city IDs supported by the system.| + +**Example** + ``` + var cityIDs = i18n.TimeZone.getAvailableZoneCityIDs(); + ``` + + +### getCityDisplayName9+ + +static getCityDisplayName(cityID: string, locale: string): string + +Obtains the localized display of a time zone city in the specified locale. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| cityID | string | Yes | Time zone city ID.| +| locale | string | Yes | Locale ID.| + +**Return value** +| Type | Description | +| ------ | ----------------------- | +| string | Localized display of the time zone city in the specified locale.| + +**Example** + ``` + var displayName = i18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); + ``` + + +### getTimezoneFromCity9+ + +static getTimezoneFromCity(cityID: string): TimeZone + +Obtains the **TimeZone** object corresponding to the specified time zone city ID. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| cityID | string | Yes | Time zone city ID.| + +**Return value** +| Type | Description | +| ------ | ----------------------- | +| TimeZone | **TimeZone** object corresponding to the specified time zone city ID.| + +**Example** + ``` + var timezone = i18n.TimeZone.getTimezoneFromCity("Shanghai"); + ``` + + +## i18n.setUsingLocalDigit9+ + +setUsingLocalDigit(flag: boolean): boolean + +Sets whether to turn on the local digit switch. +This is a system API. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.| + +**Return value** +| Type | Description | +| -------- | ------------ | +| boolean | Result indicating whether the local digit switch is successfully set. The value **true** indicates that the local digit switch is successfully set, and the value **false** indicates the opposite.| + +**Example** + ``` + var status = i18n.setUsingLocalDigit(true); + ``` + + +## i18n.getUsingLocalDigit9+ + +getUsingLocalDigit(): boolean + +Checks whether the local digit switch is turned on. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| -------- | ------------ | +| boolean | Result indicating whether the local digit switch is turned on. The value **true** indicates that the local digit switch is turned on, and the value **false** indicates the opposite.| + +**Example** + ``` + var status = i18n.getUsingLocalDigit(); + ``` 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-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 3d2f6f3e9703e606847e92822c62aa20c2811e8f..91059df152841c2317196bcd8496be2412f2fd30 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -49,7 +49,9 @@ getMediaLibrary(): MediaLibrary Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents. -> **Note**: This API is no longer maintained since API version 8. You are advised to use [mediaLibrary.getMediaLibrary8+](#medialibrarygetmedialibrary8) instead. +> **NOTE** +> +> This API is no longer maintained since API version 8. You are advised to use [mediaLibrary.getMediaLibrary8+](#medialibrarygetmedialibrary8) instead. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -99,7 +101,9 @@ media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success'); fetchFileResult.getAllObject((err, fileAssetList) => { if (fileAssetList != undefined) { - fileAssetList.forEach(getAllObjectInfo); + fileAssetList.forEach(function(getAllObjectInfo){ + console.info("getAllObjectInfo.displayName :" + getAllObjectInfo.displayName); + }); } }); } @@ -137,7 +141,7 @@ let imagesfetchOp = { selectionArgs: [imageType.toString()], }; media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(dir)); + console.info("getFileAssets successfully: image number is "+ fetchFileResult.getCount()); }).catch(function(err){ console.info("getFileAssets failed with error:"+ err); }); @@ -161,7 +165,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback **Example** ``` -mediaLibrary.on('imageChange', () => { +media.on('imageChange', () => { // image file had changed, do something }) ``` @@ -449,7 +453,9 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>) Stores a media asset. This API uses an asynchronous callback to return the URI that stores the media asset. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -485,7 +491,9 @@ storeMediaAsset(option: MediaAssetOption): Promise<string> Stores a media asset. This API uses a promise to return the URI that stores the media asset. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -524,7 +532,9 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **dataability://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -566,7 +576,9 @@ startImagePreview(images: Array<string>, callback: AsyncCallback<void&g Starts image preview. This API can be used to preview local images whose URIs start with **dataability://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **** component can be used to render and display local images and network images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -606,7 +618,9 @@ startImagePreview(images: Array<string>, index?: number): Promise<void& Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with dataability:// or online images whose URIs start with https://. It uses a promise to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **** component can be used to render and display local images and network images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -651,7 +665,9 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array< Starts media selection. This API uses an asynchronous callback to return the list of URIs that store the selected media assets. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -666,7 +682,7 @@ Starts media selection. This API uses an asynchronous callback to return the lis ``` let option = { - type : "image", + type : "media", count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { @@ -686,7 +702,9 @@ startMediaSelect(option: MediaSelectOption): Promise<Array<string>> Starts media selection. This API uses a promise to return the list of URIs that store the selected media assets. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -706,7 +724,7 @@ Starts media selection. This API uses a promise to return the list of URIs that ``` let option = { - type : "image", + type : "media", count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { @@ -745,7 +763,7 @@ Provides APIs for encapsulating file asset attributes. | width | number | Yes | No | Image width, in pixels. | | height | number | Yes | No | Image height, in pixels. | | orientation | number | Yes | Yes | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees).| -| duration8+ | number | Yes | No | Duration, in seconds. | +| duration8+ | number | Yes | No | Duration, in ms. | | albumId | number | Yes | No | ID of the album to which the file belongs. | | albumUri8+ | string | Yes | No | URI of the album to which the file belongs. | | albumName | string | Yes | No | Name of the album to which the file belongs. | @@ -771,6 +789,7 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -806,6 +825,7 @@ Checks whether this file asset is a directory. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -843,6 +863,7 @@ Commits the modification in this file asset to the database. This API uses an as ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -879,6 +900,7 @@ Commits the modification in this file asset to the database. This API uses a pro ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -899,9 +921,11 @@ open(mode: string, callback: AsyncCallback<number>): void Opens this file asset. This API uses an asynchronous callback to return the result. -Note: Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. +> **NOTE** +> +> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -919,7 +943,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - asset = await media.createAsset(mediaType, "image00003.jpg", path); + const asset = await media.createAsset(mediaType, "image00003.jpg", path); asset.open('rw', (openError, fd) => { if(fd > 0){ asset.close(fd); @@ -936,9 +960,11 @@ open(mode: string): Promise<number> Opens this file asset. This API uses a promise to return the result. -Note: Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. +> **NOTE** +> +> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -946,7 +972,7 @@ Note: Currently, the write operations are mutually exclusive. After the write op | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------------------------------- | -| mode | string | Yes | Mode of opening the file, for example, **r** (read-only), **w** (write-only), and **rw** (read-write).| +| mode | string | Yes | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).| **Return value** @@ -961,7 +987,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - asset = await media.createAsset(mediaType, "image00003.jpg", path); + const asset = await media.createAsset(mediaType, "image00003.jpg", path); asset.open('rw') .then((fd) => { console.info('File fd!' + fd); @@ -978,7 +1004,7 @@ close(fd: number, callback: AsyncCallback<void>): void Closes this file asset. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -993,6 +1019,7 @@ Closes this file asset. This API uses an asynchronous callback to return the res ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1002,13 +1029,19 @@ async function example() { }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.close(fd, (closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd, (closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); }); } ``` @@ -1019,7 +1052,7 @@ close(fd: number): Promise<void> Closes this file asset. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **'r'**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **'w'**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1039,6 +1072,7 @@ Closes this file asset. This API uses a promise to return the result. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1048,14 +1082,20 @@ async function example() { }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.close(fd).then((closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd).then((closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); }); } ``` @@ -1080,6 +1120,7 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1116,6 +1157,7 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1123,6 +1165,7 @@ async function example() { order: fileKeyObj.DATE_ADDED + " DESC", extendArgs: "", }; + let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size, (err, pixelmap) => { @@ -1157,6 +1200,7 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1164,6 +1208,7 @@ async function example() { order: fileKeyObj.DATE_ADDED + " DESC", extendArgs: "", }; + let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size) @@ -1197,6 +1242,7 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1238,6 +1284,7 @@ Favorites or unfavorites this file asset. This API uses a promise to return the ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1275,6 +1322,7 @@ Checks whether this file asset is favorited. This API uses an asynchronous callb ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1314,6 +1362,7 @@ Checks whether this file asset is favorited. This API uses a promise to return t ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1354,6 +1403,7 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1398,6 +1448,7 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1435,6 +1486,7 @@ Checks whether this file asset is in the trash. This API uses an asynchronous ca ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1448,7 +1500,7 @@ async function example() { function isTrashCallBack(err, isTrash) { if (isTrash == true) { console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK isTrash = ' + isTrash); - asset.trash(true, trashCallBack); + asset.trash(true, istrashCallBack); } else { console.info('mediaLibraryTest : ASSET_CALLBACK isTrash Unsuccessfull = ' + err); @@ -1479,6 +1531,7 @@ Checks whether this file asset is in the trash. This API uses a promise to retur ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1518,6 +1571,8 @@ Obtains the total number of files in the result set. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.FILE; let getFileCountOneOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], @@ -1547,6 +1602,7 @@ Checks whether the cursor is in the last row of the result set. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1584,6 +1640,7 @@ Releases and invalidates this **FetchFileResult** instance. Other APIs in this i ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1614,6 +1671,7 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1622,12 +1680,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getFirstObject((err, value) => { + fetchFileResult.getFirstObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1650,6 +1708,7 @@ Obtains the first file asset in the result set. This API uses a promise to retur ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1672,8 +1731,6 @@ async function example() { Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1686,6 +1743,7 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1694,12 +1752,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getNextObject((err, value) => { + fetchFileResult.getNextObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1710,8 +1768,6 @@ async function example() { Obtains the next file asset in the result set. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Return value** @@ -1724,6 +1780,7 @@ Obtains the next file asset in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1734,7 +1791,7 @@ async function example() { let fetchFileResult = await media.getFileAssets(getImageOp); const fetchCount = fetchFileResult.getCount(); console.info('mediaLibraryTest : count:' + fetchCount); - fileAsset = await fetchFileResult.getNextObject(); + let fileAsset = await fetchFileResult.getNextObject(); } ``` @@ -1756,6 +1813,7 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1764,12 +1822,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getLastObject((err, value) => { + fetchFileResult.getLastObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1792,6 +1850,7 @@ Obtains the last file asset in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1823,6 +1882,7 @@ Obtains a file asset with the specified index in the result set. This API uses a ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1831,12 +1891,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(0, (err, value) => { + fetchFileResult.getPositionObject(0, (err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1847,8 +1907,6 @@ getPositionObject(index: number): Promise<FileAsset> Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1867,6 +1925,7 @@ Obtains a file asset with the specified index in the result set. This API uses a ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1875,12 +1934,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1, (err, value) => { + fetchFileResult.getPositionObject(1, (err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1891,8 +1950,6 @@ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1905,6 +1962,7 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1913,12 +1971,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getAllObject((err, value) => { + fetchFileResult.getAllObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1941,6 +1999,7 @@ Obtains all the file assets in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -2068,6 +2127,10 @@ async function example() { selections: '', selectionArgs: [], }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack); @@ -2107,6 +2170,10 @@ async function example() { selections: '', selectionArgs: [], }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ @@ -2120,8 +2187,9 @@ async function example() { ## PeerInfo8+ Describes information about a registered device. +This is a system API. -**System capability**: SystemCapability.Multimedia.MediaLibrary.Core +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore | Name | Type | Readable| Writable| Description | | ---------- | -------------------------- | ---- | ---- | ---------------- | @@ -2138,12 +2206,12 @@ Enumerates media types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value| Description| -| ----- | ------ | ---- | -| FILE | 1 | File.| -| IMAGE | 3 | Image.| -| VIDEO | 4 | Video.| -| AUDIO | 5 | Audio.| +| Name | Description| +| ----- | ---- | +| FILE | File.| +| IMAGE | Image.| +| VIDEO | Video.| +| AUDIO | Audio.| ## FileKey8+ @@ -2166,7 +2234,7 @@ Enumerates key file information. | TITLE | title | Title in the file. | | ARTIST | artist | Artist of the file. | | AUDIOALBUM | audio_album | Audio album. | -| DURATION | duration | Duration, in seconds. | +| DURATION | duration | Duration, in ms. | | WIDTH | width | Image width, in pixels. | | HEIGHT | height | Image height, in pixels. | | ORIENTATION | orientation | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| @@ -2179,30 +2247,31 @@ Enumerates directory types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value| Description | -| ------------- | ------ | ------------------ | -| DIR_CAMERA | 0 | Directory of camera files.| -| DIR_VIDEO | 1 | Directory of video files. | -| DIR_IMAGE | 2 | Directory of image files. | -| DIR_AUDIO | 3 | Directory of audio files. | -| DIR_DOCUMENTS | 4 | Directory of documents. | -| DIR_DOWNLOAD | 5 | Download directory. | +| Name | Description | +| ------------- | ------------------ | +| DIR_CAMERA | Directory of camera files.| +| DIR_VIDEO | Directory of video files. | +| DIR_IMAGE | Directory of image files. | +| DIR_AUDIO | Directory of audio files. | +| DIR_DOCUMENTS | Directory of documents. | +| DIR_DOWNLOAD | Download directory. | ## DeviceType8+ Enumerates device types. +This is a system API. -**System capability**: SystemCapability.Multimedia.MediaLibrary.Core +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore -| Name | Default Value| Description | -| ------------ | ------ | ---------- | -| TYPE_UNKNOWN | 0 | Unknown.| -| TYPE_LAPTOP | 1 | Laptop.| -| TYPE_PHONE | 2 | Phone. | -| TYPE_TABLET | 3 | Tablet. | -| TYPE_WATCH | 4 | Smart watch. | -| TYPE_CAR | 5 | Vehicle-mounted device. | -| TYPE_TV | 6 | TV. | +| Name | Description | +| ------------ | ---------- | +| TYPE_UNKNOWN | Unknown.| +| TYPE_LAPTOP | Laptop.| +| TYPE_PHONE | Phone. | +| TYPE_TABLET | Tablet. | +| TYPE_WATCH | Smart watch. | +| TYPE_CAR | Vehicle-mounted device. | +| TYPE_TV | TV. | ## MediaFetchOptions7+ @@ -2222,6 +2291,7 @@ Describes options for fetching media files. ## Size8+ Describes the image size. +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Type | Readable | Writable | Description | | ------ | ------ | ---- | ---- | -------- | @@ -2232,7 +2302,9 @@ Describes the image size. Implements the media asset option. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2247,7 +2319,9 @@ Implements the media asset option. Describes media selection option. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 94fb115434d6860cb2096586d48f0c981ea9a30a..b981d28061d45feb313dbaf7ea0709d6f198e0e8 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -1,12 +1,11 @@ # missionManager +The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. > **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. -missionManager provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. - ## Modules to Import ``` @@ -23,8 +22,12 @@ registerMissionListener(listener: MissionListener): number; Registers a listener to observe the mission status. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -59,8 +62,12 @@ unregisterMissionListener(listenerId: number, callback: AsyncCallback<void> Deregisters a mission status listener. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -93,8 +100,12 @@ unregisterMissionListener(listenerId: number): Promise<void>; Deregisters a mission status listener. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -132,8 +143,12 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<M Obtains the information about a given mission. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -166,8 +181,12 @@ getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; Obtains the information about a given mission. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -198,8 +217,12 @@ getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Arr Obtains information about all missions. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -227,8 +250,12 @@ getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionIn Obtains information about all missions. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -259,8 +286,12 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback& Obtains the snapshot of a given mission. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -294,8 +325,12 @@ getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnaps Obtains the snapshot of a given mission. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -334,8 +369,12 @@ lockMission(missionId: number, callback: AsyncCallback<void>): void; Locks a given mission. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -367,8 +406,12 @@ lockMission(missionId: number): Promise<void>; Locks a given mission. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -405,8 +448,12 @@ unlockMission(missionId: number, callback: AsyncCallback<void>): void; Unlocks a given mission. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -438,8 +485,12 @@ unlockMission(missionId: number): Promise<void>; Unlocks a given mission. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -480,8 +531,12 @@ clearMission(missionId: number, callback: AsyncCallback<void>): void; Clears a given mission, regardless of whether it is locked. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -513,8 +568,12 @@ clearMission(missionId: number): Promise<void>; Clears a given mission, regardless of whether it is locked. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -552,8 +611,12 @@ clearAllMissions(callback: AsyncCallback<void>): void; Clears all unlocked missions. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Example** ```js @@ -571,8 +634,12 @@ clearAllMissions(): Promise<void>; Clears all unlocked missions. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type| Description| @@ -595,8 +662,12 @@ moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void Switches a given mission to the foreground. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -628,8 +699,12 @@ moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCall Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -662,8 +737,12 @@ moveMissionToFront(missionId: number, options?: StartOptions): Promise<void&g Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses a promise to return the result. +**Required permission**: ohos.permission.MANAGE_MISSIONS + **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -699,7 +778,9 @@ Switches a given mission to the foreground, with the startup parameters for the Describes the mission information. -**System capability**: SystemCapability.Ability.AbilityBase +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -710,4 +791,4 @@ Describes the mission information. | want | [Want](js-apis-application-Want.md) | Yes| Yes| **Want** information of the mission.| | label | string | Yes| Yes| Label of the mission.| | iconPath | string | Yes| Yes| Path of the mission icon.| -| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device. | +| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 6e1eab82dbbd426d7e1facd48a0516d981658f28..ec63d11121dcd5138d11d7a2e1898833deaaf9c7 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -1,5 +1,6 @@ # Network Connection Management +The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. > **NOTE** > @@ -79,7 +80,7 @@ Checks whether the default data network is activated. This API uses an asynchron ```js connection.hasDefaultNet(function (error, has) { console.log(JSON.stringify(error)) - console.log(has) + console.log('has: ' + has) }) ``` @@ -101,7 +102,7 @@ Checks whether the default data network is activated. This API uses a promise to ```js connection.hasDefaultNet().then(function (has) { - console.log(has) + console.log('has: ' + has) }) ``` @@ -167,7 +168,7 @@ Obtains connection properties of the network corresponding to given network hand | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------------------ | ---- | ---------------- | -| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| +| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. | **Example** @@ -195,7 +196,7 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi | Name | Type | Mandatory| Description | | --------- | ----------------------- | ---- | ---------------- | -| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| +| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| **Return Value** @@ -227,7 +228,7 @@ Obtains capability information of the network corresponding to **netHandle**. Th | Name | Type | Mandatory| Description | | --------- | --------------------------------------------------- | ---- | ---------------- | -| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| +| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. | **Example** @@ -255,7 +256,7 @@ Obtains capability information of the network corresponding to **netHandle**. Th | Name | Type | Mandatory| Description | | --------- | ----------------------- | ---- | ---------------- | -| netHandle | [NetHandle](#nethandle) | Yes | Network handle.| +| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| **Return Value** @@ -446,6 +447,105 @@ connection.getAddressesByName(host).then(function (addresses) { }) ``` + +## connection.enableAirplaneMode + +enableAirplaneMode(callback: AsyncCallback\): void + +Enables the airplane mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +connection.enableAirplaneMode(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.enableAirplaneMode + +enableAirplaneMode(): Promise\ + +Enables the airplane mode. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +connection.enableAirplaneMode().then(function (error) { + console.log(JSON.stringify(error)) +}) +``` + + +## connection.disableAirplaneMode + +disableAirplaneMode(callback: AsyncCallback\): void + +Disables the airplane mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +connection.disableAirplaneMode(function (error) { + console.log(JSON.stringify(error)) +}) +``` + +## connection.disableAirplaneMode + +disableAirplaneMode(): Promise\ + +Disables the airplane mode. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +connection.disableAirplaneMode().then(function (error) { + console.log(JSON.stringify(error)) +}) +``` + + ## connection.createNetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection @@ -476,7 +576,7 @@ let netConnection = connection.createNetConnection() // Cellular network let netConnectionCellular = connection.createNetConnection({ netCapabilities: { - bearerTypes: [NetBearType.BEARER_CELLULAR] + bearerTypes: [connection.NetBearType.BEARER_CELLULAR] } }) ``` @@ -497,7 +597,7 @@ Registers a listener for **netAvailable** events. | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed to **netAvailable**.
**netAvailable**: event indicating that the data network is available.| +| type | string | Yes | Event type. The value is fixed at **netAvailable**.
**netAvailable**: event indicating that the data network is available.| | callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | **Example** @@ -520,7 +620,7 @@ Registers a listener for **netCapabilitiesChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.
**netCapabilitiesChange**: event indicating that he network capabilities have changed.| +| type | string | Yes | Event type. The value is fixed at **netCapabilitiesChange**.
**netCapabilitiesChange**: event indicating that network capabilities have changed.| | callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes | Callback used to return the result. | **Example** @@ -543,7 +643,7 @@ Registers a listener for **netConnectionPropertiesChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| +| type | string | Yes | Event type. The value is fixed at **netConnectionPropertiesChange**.
**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| | callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes | Callback used to return the result. | **Example** @@ -566,7 +666,7 @@ Registers a listener for **netBlockStatusChange** events. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.
**netBlockStatusChange**: event indicating a change in the network blocking status.| +| type | string | Yes | Event type. The value is fixed at **netBlockStatusChange**.
**netBlockStatusChange**: event indicating a change in the network blocking status.| | callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the result. | **Example** @@ -589,7 +689,7 @@ Registers a listener for **netLost** events. | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed to **netLost**.
netLost: event indicating that the network is interrupted or normally disconnected.| +| type | string | Yes | Event type. The value is fixed at **netLost**.
netLost: event indicating that the network is interrupted or normally disconnected.| | callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. | **Example** @@ -613,7 +713,7 @@ Registers a listener for **netUnavailable** events. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed to **netUnavailable**.
**netUnavailable**: event indicating that the network is unavailable.| +| type | string | Yes | Event type. The value is fixed at **netUnavailable**.
**netUnavailable**: event indicating that the network is unavailable.| | callback | Callback\ | Yes | Callback used to return the result. | **Example** @@ -908,4 +1008,4 @@ Defines the network address. | ------- | ------ | ------------------------------ | | address | string | Network address. | | family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| -| port | number | Port number. The value ranges from **0** to **65535**. | \ No newline at end of file +| port | number | Port number. The value ranges from **0** to **65535**. | diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index b68d1dc35be314220feb88ba2d67a3429ce75c58..a6fcacc4333ab0aa48dae7cd8b629e1e77bb399f 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -1,5 +1,7 @@ # Observer +The observer module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. + >**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. @@ -15,7 +17,7 @@ import observer from '@ohos.telephony.observer' on\(type: \'networkStateChange\', callback: Callback\): void; -Registers an observer for network status change events. This API uses an asynchronous callback to return the execution result. +Registers an observer for network status change events. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -41,7 +43,7 @@ observer.on('networkStateChange', data =>{ on\(type: \'networkStateChange\', options: { slotId: number }, callback: Callback\): void; -Registers an observer for network status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the execution result. +Registers an observer for network status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -68,9 +70,7 @@ observer.on('networkStateChange', {slotId: 0}, data =>{ off\(type: \'networkStateChange\', callback?: Callback\): void; -Unregisters the observer for network status change events. This API uses an asynchronous callback to return the execution result. - -**Required permission**: ohos.permission.GET_NETWORK_INFO +Unregisters the observer for network status change events. This API uses an asynchronous callback to return the result. >**NOTE** > @@ -101,7 +101,7 @@ observer.off('networkStateChange'); on\(type: \'signalInfoChange\', callback: Callback\>): void; -Registers an observer for signal status change events. This API uses an asynchronous callback to return the execution result. +Registers an observer for signal status change events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -125,7 +125,7 @@ observer.on('signalInfoChange', data =>{ on\(type: \'signalInfoChange\', options: { slotId: number }, callback: Callback\>): void; -Registers an observer for signal status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the execution result. +Registers an observer for signal status change events of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -150,7 +150,7 @@ observer.on('signalInfoChange', {slotId: 0}, data =>{ off\(type: \'signalInfoChange\', callback?: Callback\>): void; -Unregisters the observer for signal status change events. This API uses an asynchronous callback to return the execution result. +Unregisters the observer for signal status change events. This API uses an asynchronous callback to return the result. >**NOTE** > @@ -182,9 +182,7 @@ observer.off('signalInfoChange'); on(type: 'callStateChange', callback: Callback\<{ state: CallState, number: string }\>): void; -Registers an observer for call status change events. This API uses an asynchronous callback to return the execution result. - -**Required permission**: ohos.permission.READ_CALL_LOG +Registers an observer for call status change events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -208,9 +206,7 @@ observer.on('callStateChange', value =>{ on(type: 'callStateChange', options: { slotId: number }, callback: Callback<{ state:CallState, number: string }>): void; -Registers an observer for call status change events. This API uses an asynchronous callback to return the execution result. - -**Required permission**: ohos.permission.READ_CALL_LOG +Registers an observer for call status change events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -235,9 +231,7 @@ observer.on('callStateChange', {slotId: 0}, value =>{ off(type: 'callStateChange', callback?: Callback<{ state: CallState, number: string }>): void; -Unregisters the observer for call status change events. This API uses an asynchronous callback to return the execution result. - -**Required permission**: ohos.permission.READ_CALL_LOG +Unregisters the observer for call status change events. This API uses an asynchronous callback to return the result. >**NOTE** > @@ -269,7 +263,7 @@ observer.off('callStateChange'); on\(type: 'cellularDataConnectionStateChange', callback: Callback\<{ state: DataConnectState, network: RatType}\>\): void; -Registers an observer for connection status change events of the cellular data link. This API uses an asynchronous callback to return the result. +Registers an observer for connection status change events of the cellular data connection.This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -277,7 +271,7 @@ Registers an observer for connection status change events of the cellular data l | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Connection status change event of the cellular data link. | +| type | string | Yes | Connection status change event of the cellular data connection. | | callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** @@ -293,7 +287,7 @@ observer.on('cellularDataConnectionStateChange', value =>{ on\(type: 'cellularDataConnectionStateChange', options: { slotId: number }, callback: Callback\<{ state: DataConnectState, network: RatType }\>\): void; -Registers an observer for connection status change events of the cellular data link over the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Registers an observer for connection status change events of the cellular data connection over the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.StateRegistry @@ -301,7 +295,7 @@ Registers an observer for connection status change events of the cellular data l | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Connection status change event of the cellular data link. | +| type | string | Yes | Connection status change event of the cellular data connection. | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| @@ -318,7 +312,7 @@ observer.on('cellularDataConnectionStateChange', {slotId: 0}, value =>{ off\(type: 'cellularDataConnectionStateChange', callback?: Callback\<{ state: DataConnectState, network: RatType}\>\): void; -Unregisters the observer for connection status change events of the cellular data link. This API uses an asynchronous callback to return the result. +Unregisters the observer for connection status change events of the cellular data connection.This API uses an asynchronous callback to return the result. >**NOTE** > @@ -330,7 +324,7 @@ Unregisters the observer for connection status change events of the cellular dat | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Connection status change event of the cellular data link. | +| type | string | Yes | Connection status change event of the cellular data connection. | | callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | No | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** diff --git a/en/application-dev/reference/apis/js-apis-particleAbility.md b/en/application-dev/reference/apis/js-apis-particleAbility.md index 12f2fd80bdd78b13c59b1684f080ac2798a9c436..ac0152abec3ed642d7e0cc61af6aa2ab5d7c5e3f 100644 --- a/en/application-dev/reference/apis/js-apis-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-particleAbility.md @@ -1,4 +1,6 @@ -# ParticleAbility +# particleAbility + +The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index f0d3ed2f0ce6e5e84883f38b7d9441b74dae5ae4..d133b1b37776187ac1120f42ead17e98273f0db4 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -1,19 +1,13 @@ # PermissionRequestResult +The **PermissionRequestResult** module provides the result of a permission request. + > **NOTE** > -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Provides the permission request result. - -## Modules to Import - -```js -import Ability from '@ohos.application.Ability' -``` - -## How to Use +## Usage The permission request result is obtained through an **AbilityStage** instance. diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index e6f796d1a08c0bce209a84e2999dcbf4f3b6a78c..98d55f53e7f3c51f33fc9505fccf33df846c9ef6 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -1,6 +1,7 @@ # Obtaining Process Information -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -409,7 +410,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | timeout | number | No| Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.| -| killSignal | number  \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| +| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| | maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-processrunninginfo.md index 24fb9f15a5427a450ea907bb296c43f3d3f55a91..e26e01dc8f8d7fbb6472d11217f1156ceb1b41b8 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-processrunninginfo.md @@ -1,16 +1,10 @@ # ProcessRunningInfo +The **ProcessRunningInfo** module provides process running information. + > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -Provides process running information. - -## Modules to Import - -```js -import appManager from '@ohos.application.appManager' -``` +> 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. ## Usage @@ -23,7 +17,6 @@ appManager.getProcessRunningInfos((error,data) => { }); ``` - ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index b8cbdcc23c001aa24aebe7dfaae2ca06a0fae706..5b371ea07267732eb69de7676cab7f6057954275 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1,5 +1,7 @@ # Radio +The radio module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. + >**NOTE** > >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. @@ -15,7 +17,7 @@ import radio from '@ohos.telephony.radio' getRadioTech\(slotId: number, callback: AsyncCallback<\{psRadioTech: RadioTechnology, csRadioTech: RadioTechnology\}\>\): void -Obtains the radio access technology (RAT) used by the CS and PS domains for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Obtains the RAT used in the CS and PS domains for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -42,7 +44,7 @@ radio.getRadioTech(slotId, (err, data) =>{ getRadioTech\(slotId: number\): Promise<\{psRadioTech: RadioTechnology, csRadioTech: RadioTechnology\}\> -Obtains the RAT used by the CS and PS domains for the SIM card in the specified slot. This API uses a promise to return the result. +Obtains the RAT used in the CS and PS domains for the SIM card in the specified slot. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -573,7 +575,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -607,7 +609,7 @@ This is a system API. | Type | Description | | --------------- | ------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise used to return the result.| **Example** 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-router.md b/en/application-dev/reference/apis/js-apis-router.md index 40076077bd258dab549dbcb46e16a7137961c107..ac9435450c7e47d70deb11ed0a5b7249eea8f368 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -1,9 +1,12 @@ # Page Routing +The **Router** module provides APIs to access pages through URLs. You can use the APIs to navigate to a specified page in an application, replace the current page with another one in an application, and return to the previous page or a specified page. + > **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. -> - Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. +> +> - Page routing APIs can be invoked only after page rendering is complete. Do not call these APIs in **onInit** and **onReady** when the page is still in the rendering phase. ## Modules to Import @@ -11,10 +14,6 @@ import router from '@ohos.router' ``` -## Required Permissions - -None. - ## router.push push(options: RouterOptions): void @@ -24,44 +23,50 @@ Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| options | [RouterOptions](#routeroptions) | Yes| Page routing parameters.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| **Example** - ```js - // Current page - export default { - pushPage() { - router.push({ - url: 'pages/routerpage2/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - }, - }, - }); - } - } - ``` - ```js - // routerpage2 page - export default { - data: { - data1: 'default', - data2: { - data3: [1, 2, 3] - } +```js +router.push({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] }, - onInit() { - console.info('showData1:' + this.data1); - console.info('showData3:' + this.data2.data3); - } - } - ``` + }, +}); +``` +## router.push9+ + +push(options: RouterOptions, mode: RouterMode): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------- | ---- | -------------------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | +| mode9+ | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Example** +```js +router.push({ + url: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, +},router.RouterMode.Standard); +``` ## router.replace @@ -72,37 +77,45 @@ Replaces the current page with another one in the application and destroys the c **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| options | [RouterOptions](#routeroptions) | Yes| Description of the new page.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| **Example** - ```js - // Current page - export default { - replacePage() { - router.replace({ - url: 'pages/detail/detail', - params: { - data1: 'message', - }, - }); - } - } - ``` +```js +router.replace({ + url: 'pages/detail', + params: { + data1: 'message', + }, +}); +``` - ```js - // detail page - export default { - data: { - data1: 'default' - }, - onInit() { - console.info('showData1:' + this.data1) - } - } - ``` + ## router.replace9+ + +replace(options: RouterOptions, mode: RouterMode): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory| Description | +| ----------------- | ------------------------------- | ---- | -------------------- | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | +| mode9+ | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Example** + +```js +router.replace({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, +}, router.RouterMode.Standard); +``` ## router.back @@ -113,59 +126,15 @@ Returns to the previous page or a specified page. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| options | [RouterOptions](#routeroptions) | Yes| Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| options | [RouterOptions](#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.| **Example** - ```js - // index page - export default { - indexPushPage() { - router.push({ - url: 'pages/detail/detail', - }); - } - } - ``` - - ```js - // detail page - export default { - detailPushPage() { - router.push({ - url: 'pages/mall/mall', - }); - } - } - ``` - - ```js - // Navigate from the mall page to the detail page through router.back(). - export default { - mallBackPage() { - router.back(); - } - } - ``` - ```js - // Navigate from the detail page to the index page through router.back(). - export default { - defaultBack() { - router.back(); - } - } - ``` - - ```js - // Return to the detail page through router.back(). - export default { - backToDetail() { - router.back({uri:'pages/detail/detail'}); - } - } - ``` +```js +router.back({url:'pages/detail'}); +``` ## router.clear @@ -176,13 +145,10 @@ Clears all historical pages in the stack and retains only the current page at th **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** - ```js - export default { - clearPage() { - router.clear(); - } - }js - ``` + +```js +router.clear(); +``` ## router.getLength @@ -193,19 +159,15 @@ Obtains the number of pages in the current stack. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ---------------------------------- | | string | Number of pages in the stack. The maximum value is **32**.| **Example** - ```js - export default { - getLength() { - var size = router.getLength(); - console.log('pages stack size = ' + size); - } - } - ``` +```js +var size = router.getLength(); +console.log('pages stack size = ' + size); +``` ## router.getState @@ -220,28 +182,26 @@ Obtains state information about the current page. | Type | Description | | --------------------------- | -------------- | | [RouterState](#routerstate) | Page routing state.| +**Example** + +```js +var page = router.getState(); +console.log('current index = ' + page.index); +console.log('current name = ' + page.name); +console.log('current path = ' + page.path); +``` + ## RouterState + Describes the page routing state. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Description| -| -------- | -------- | -------- | -| index | number | Index of the current page in the stack.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The index starts from 1 from the bottom to the top of the stack.| -| name | string | Name of the current page, that is, the file name.| -| path | string | Path of the current page.| - -**Example** - ```js - export default { - getState() { - var page = router.getState(); - console.log('current index = ' + page.index); - console.log('current name = ' + page.name); - console.log('current path = ' + page.path); - } - } - ``` +| Name | Type | Description | +| ----- | ------ | ------------------------------------------------------------ | +| index | number | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.| +| name | string | Name of the current page, that is, the file name. | +| path | string | Path of the current page. | ## router.enableAlertBeforeBackPage @@ -252,26 +212,16 @@ Enables the display of a confirm dialog box before returning to the previous pag **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| options | [EnableAlertOptions](#enablealertoptions) | Yes| Description of the dialog box.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------- | ---- | ------------------ | +| options | [EnableAlertOptions](#enablealertoptions) | Yes | Description of the dialog box.| **Example** - ```js - export default { - enableAlertBeforeBackPage() { - router.enableAlertBeforeBackPage({ - message: 'Message Info', - success: function() { - console.log('success'); - }, - fail: function() { - console.log('fail'); - }, - }); - } - } + ```js + router.enableAlertBeforeBackPage({ + message: 'Message Info' + }); ``` ## EnableAlertOptions @@ -279,9 +229,9 @@ Describes the confirm dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| message | string | Yes| Content displayed in the confirm dialog box.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------- | +| message | string | Yes | Content displayed in the confirm dialog box.| ## router.disableAlertBeforeBackPage @@ -292,13 +242,9 @@ Disables the display of a confirm dialog box before returning to the previous pa **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** - ```js - export default { - disableAlertBeforeBackPage() { - router.disableAlertBeforeBackPage(); - } - } - ``` +```js +router.disableAlertBeforeBackPage(); +``` ## router.getParams @@ -316,122 +262,141 @@ Obtains the parameters passed from the page that initiates redirection to the cu **Example** -- Web-like example - ```js - // Current page - export default { - pushPage() { - router.push({ - url: 'pages/detail/detail', - params: { - data1: 'message', - }, - }); - } +``` +router.getParams(); +``` + +## RouterOptions + +Describes the page routing options. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| url | string | Yes | URI of the destination page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URI is a slash (/), the home page is displayed. | +| params | Object | No | Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| + + + > **NOTE** + > + > The page routing stack supports a maximum of 32 pages. + +## RouterMode9+ + +Enumerates the routing modes. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Description | +| -------- | ------------------------------------------------------------ | +| Standard | Standard mode. | +| Single | Singleton mode.
If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.
If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.| + +## Examples + +### JavaScript-based Web-like Development Paradigm + +```js +// Current page +export default { + pushPage() { + router.push({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); } - ``` - ```js - // detail page - export default { - onInit() { - console.info('showData1:' + router.getParams().data1); - } +} +``` +```js +// detail page +export default { + onInit() { + console.info('showData1:' + router.getParams()[data1]); } - ``` +} +``` -- Declarative example +### TypeScript-based Declarative Development Paradigm - ```ts - // Navigate to the target page through router.push with the params parameter carried. - import router from '@ohos.router' - - @Entry - @Component - struct Index { - async routePage() { - let options = { - url: 'pages/second', - params: { - text: 'This is the value on the first page.', - data: { - array: [12, 45, 78] - }, - } - } - try { - await router.push(options) - } catch (err) { - console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`) +```ts +// Navigate to the target page through router.push with the params parameter carried. +import router from '@ohos.router' + +@Entry +@Component +struct Index { + async routePage() { + let options = { + url: 'pages/second', + params: { + text: 'This is the value on the first page.', + data: { + array: [12, 45, 78] + }, } } - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('This is the first page.') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button() { - Text('next page') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ top: 20 }) - .backgroundColor('#ccc') - .onClick(() => { - this.routePage() - }) - } - .width('100%') - .height('100%') + try { + await router.push(options) + } catch (err) { + console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`) } } - ``` - ```ts - // Receive the transferred parameters on the second page. - import router from '@ohos.router' - - @Entry - @Component - struct Second { - private content: string = "This is the second page." - @State text: string = router.getParams()['text'] - @State data: any = router.getParams()['data'] - @State secondData : string = '' - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text(`${this.content}`) + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('This is the first page.') .fontSize(50) .fontWeight(FontWeight.Bold) - Text(this.text) - .fontSize(30) - .onClick(()=>{ - this.secondData = (this.data.array[1]).toString() - }) - .margin({top:20}) - Text('Value from the first page '+'' + this.secondData) - .fontSize(20) - .margin({top:20}) - .backgroundColor('red') - } - .width('100%') - .height('100%') + Button() { + Text('next page') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ top: 20 }) + .backgroundColor('#ccc') + .onClick(() => { + this.routePage() + }) } + .width('100%') + .height('100%') } - ``` - -## RouterOptions - -Describes the page routing options. - -**System capability**: SystemCapability.ArkUI.ArkUI.Lite - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| url | string | Yes| URI of the destination page, in either of the following formats:
-  Absolute path of the page. The value is available in the pages list in the config.json file, for example:
  - pages/index/index
  - pages/detail/detail
-  Particular path. If the URI is a slash (/), the home page is displayed.| -| params | Object | No| Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| +} +``` +```ts +// Receive the transferred parameters on the second page. +import router from '@ohos.router' - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** - > The page routing stack supports a maximum of 32 pages. +@Entry +@Component +struct Second { + private content: string = "This is the second page." + @State text: string = router.getParams()['text'] + @State data: any = router.getParams()['data'] + @State secondData : string = '' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(`${this.content}`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Text(this.text) + .fontSize(30) + .onClick(()=>{ + this.secondData = (this.data.array[1]).toString() + }) + .margin({top:20}) + Text('Value from the first page '+'' + this.secondData) + .fontSize(20) + .margin({top:20}) + .backgroundColor('red') + } + .width('100%') + .height('100%') + } +} +``` 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 new file mode 100644 index 0000000000000000000000000000000000000000..94f5f3cb5e532f3e28f221addb164358589b1754 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -0,0 +1,718 @@ +# Screen +The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. +## Modules to Import + +```js +import screen from '@ohos.screen'; +``` + +## screen.getAllScreens + +getAllScreens(callback: AsyncCallback<Array<Screen>>): void + +Obtains all screens. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback<Array<[Screen](#screen)>> | Yes | Callback used to return all the **Screen** objects obtained.| + +**Example** + +```js +var screenClass = null; +screen.getAllScreens((err, data) => { + if (err.code) { + console.error('Failed to get all screens . Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting all screens . Data:' + JSON.stringify(data)); + screenClass = data[0]; +}); +``` +## screen.getAllScreens + +getAllScreens(): Promise<Array<Screen>> + +Obtains all screens. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** +| Type | Description | +| --------------------------------------------- | ----------------------------------------- | +| Promise<Array<[Screen](#screen)>> | Promise used to return all the **Screen** objects obtained.| + +**Example** +```js +var screenClass = null; +let promise = screen.getAllScreens(); +promise.then((data) => { + screenClass = data[0]; + console.log('Succeeded in getting all screens . Data:'+ JSON.stringify(data)); +}).catch((err) => { + console.log('Failed to get all screens . Cause: ' + JSON.stringify(err)); +}); +``` +## screen.on('connect' | 'disconnect' | 'change') +on(eventType: 'connect' | 'disconnect' | 'change', callback: Callback<number>): void + +Subscribes to events related to the screen state. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| --------- | ---------------------- | ---- | ------------------------------------------------------------ | +| eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| +| callback | Callback<number> | Yes | Callback used to return the screen ID. | + +**Example** +```js +var callback = (data) => { + console.info('Register the callback for screen changes. Data: ' + JSON.stringify(data)) +}; +screen.on("connect", callback); +``` +## screen.off('connect' | 'disconnect' | 'change') +off(eventType: 'connect' | 'disconnect' | 'change', callback?: Callback<number>): void + +Unsubscribes from events related to the screen state. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| --------- | ---------------------- | ---- | ------------------------------------------------------------ | +| eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| +| callback | Callback<number> | No | Callback used to return the screen ID. | + +**Example** +```js +var callback = (data) => { + console.info('Unegister the callback for screen changes. Data: ' + JSON.stringify(data)) +}; +screen.off("connect", callback); +``` + +## screen.makeExpand +makeExpand(options:Array<ExpandOption>, callback: AsyncCallback<number>): void + +Sets the screen to the expanded mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | -------------------------------- | +| options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen. | +| callback | Callback<number> | Yes | Callback used to return the group ID of the expanded screens.| + +**Example** + +```js +var groupId = null; +screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}], (err, data) => { + if (err.code) { + console.error('Failed to make screens as expand-screen. Cause:' + JSON.stringify(err)); + return; + } + groupId = data; + console.info('Succeeded in making screens as expand-screen.Data:' + JSON.stringify(data)); +}); +``` + +## screen.makeExpand +makeExpand(options:Array<ExpandOption>): Promise<number> + +Sets the screen to the expanded mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | ------------------------ | +| options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen.| + +**Return value** +| Type | Description | +| --------------------- | ----------------------------------- | +| Promise<number> | Promise used to return the group ID of the expanded screens.| + +**Example** +```js +screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}]).then((data) => { + console.info('Succeeded in making screens as expand-screen.Data:' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to make screens as expand-screen. Cause:' + JSON.stringify(err)); +}); +``` + +## screen.makeMirror +makeMirror(mainScreen:number, mirrorScreen:Array<number>, callback: AsyncCallback<number>): void + +Sets screen mirroring. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------- | ---- |-----------------| +| mainScreen | number | Yes | ID of the primary screen. | +| mirrorScreen | Array<number> | Yes | IDs of secondary screens. | +| callback | AsyncCallback<number> | Yes | Callback used to return the group ID of the secondary screens.| + +**Example** +```js +var mainScreenId = 0; +var mirrorScreenIds = [1, 2, 3]; +screen.makeMirror(mainScreenId, mirrorScreenIds, (err, data) => { + if (err.code) { + console.error('Failed to make screens as mirror-screen.Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in making screens as mirror-screen.Data:' + JSON.stringify(data)); +}); +``` + +## screen.makeMirror +makeMirror(mainScreen:number, mirrorScreen:Array<number>): Promise<number> + +Sets screen mirroring. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------- | ---- |-----------| +| mainScreen | number | Yes | ID of the primary screen. | +| mirrorScreen | Array<number> | Yes | IDs of secondary screens.| + +**Return value** +| Type | Description | +| --------------------- | ----------------------------------- | +| Promise<number> | Promise used to return the group ID of the secondary screens.| + +**Example** +```js +var mainScreenId = 0; +var mirrorScreenIds = [1, 2, 3]; +screen.makeMirror(mainScreenId, mirrorScreenIds).then((data) => { + console.info('Succeeded in making screens as mirror-screen.Data:' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to make screens as mirror-screen.Cause:' + JSON.stringify(err)); +}); +``` + +## screen.createVirtualScreen +createVirtualScreen(options:VirtualScreenOption, callback: AsyncCallback<Screen>): void + +Creates a virtual screen. This API uses an asynchronous callback 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 | +| -------- | ------------------------------------------- | ---- | ---------------------------------- | +| options | [VirtualScreenOption](#virtualscreenoption) | Yes | Virtual screen parameters. | +| callback | AsyncCallback<[Screen](#screen)> | Yes | Callback used to return the created virtual screen.| + +**Example** +```js +var screenClass = null; +screen.createVirtualScreen({ + name: 'screen01', + width: 1080, + height: 2340, + density: 2, + surfaceId: '' +}, (err, data) => { + if (err.code) { + console.error('Failed to create virtual screen.Cause:' + JSON.stringify(err)); + return; + } + screenClass = data; + console.info('Succeeded in creating virtual screen.Data:' + JSON.stringify(data)); +}); +``` + +## screen.createVirtualScreen +createVirtualScreen(options:VirtualScreenOption): Promise<Screen> + +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 | +| ------- | ------------------------------------------- | ---- | ------------------------ | +| options | [VirtualScreenOption](#virtualscreenoption) | Yes | Virtual screen parameters.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------- | +| Promise<[Screen](#screen)> | Promise used to return the created virtual screen.| + +**Example** +```js +var screenClass = null; +screen.createVirtualScreen({ + name: 'screen01', + width: 1080, + height: 2340, + density: 2, + surfaceId: '' +}).then((data) => { + screenClass = data; + console.info('Succeeded in creating virtual screen.Data:' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to create virtual screen.Cause:' + JSON.stringify(err)); +}); +``` + +## screen.destroyVirtualScreen +destroyVirtualScreen(screenId:number, callback: AsyncCallback<void>): void + +Destroys a virtual screen. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| screenId | number | Yes | Screen ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** +```js +var screenId = 1; +screen.destroyVirtualScreen(screenId, (err,data) => { + if (err.code) { + console.error('Failed to destroy virtual screen.Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying virtual screen.'); +}); +``` + +## screen.destroyVirtualScreen +destroyVirtualScreen(screenId:number): Promise<void> + +Destroys a virtual screen. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| screenId | number | Yes | Screen ID.| + +**Return value** +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** +```js +var screenId = 1; +screen.destroyVirtualScreen(screenId).then((data) => { + console.info('Succeeded in destroying virtual screen.'); +}).catch((err) => { + console.error('Failed to destroy virtual screen.Cause:' + JSON.stringify(err)); +}); +``` + +## screen.setVirtualScreenSurface +setVirtualScreenSurface(screenId:number, surfaceId: string, callback: AsyncCallback<void>): void + +Sets the surface for a virtual screen. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ------------------------------------------------------------ | +| screenId | number | Yes | Screen ID. | +| surfaceId | string | Yes | Surface ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen surface is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** + +```js +var screenId = 1; +var surfaceId = '2048'; +screen.setVirtualScreenSurface(screenId, surfaceId, (err,data) => { + if (err.code) { + console.error('Failed to set surface for the virtual screen. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting surface for the virtual screen.'); +}); +``` + +## screen.setVirtualScreenSurface +setVirtualScreenSurface(screenId:number, surfaceId: string): Promise<void> + +Sets the surface for a virtual screen. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) + +**Parameters** +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------- | +| screenId | number | Yes | Screen ID. | +| surfaceId | string | Yes | Surface ID.| + +**Return value** +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** +```js +var screenId = 1; +var surfaceId = '2048'; +screen.setVirtualScreenSurface(screenId, surfaceId).then((data) => { + console.info('Succeeded in setting surface for the virtual screen.'); +}).catch((err) => { + console.error('Failed to set surface for the virtual screen. Cause:' + JSON.stringify(err)); +}); +``` + +## screen.isScreenRotationLocked +isScreenRotationLocked(): Promise<boolean> + +Checks whether auto rotate is locked. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** +| Type | Description | +| ---------------------- | ------------------------------------- | +| Promise<boolean> | Promise used to return the result. If **true** is returned, auto rotate is locked. If **false** is returned, auto rotate is unlocked.| + +**Example** +```js +screen.isScreenRotationLocked().then((isLocked) => { + console.info('Succeeded in getting screen rotation lock status. isLocked:'+ JSON.stringify(isLocked)); +}).catch((err) => { + console.error('Failed to get screen rotation lock status. Cause:' + JSON.stringify(err)); +}); +``` + +## screen.isScreenRotationLocked +isScreenRotationLocked(callback: AsyncCallback<boolean>): void + +Checks whether auto rotate is locked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If **true** is returned, auto rotate is locked. If **false** is returned, auto rotate is unlocked.| + +**Example** + +```js +screen.isScreenRotationLocked((err, isLocked) => { + if (err.code) { + console.error('Failed to get screen rotation lock status. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting screen rotation lock status. isLocked:' + JSON.stringify(isLocked)); +}); +``` + +## screen.setScreenRotationLocked +setScreenRotationLocked(isLocked: boolean): Promise<void> + +Sets whether to lock auto rotate. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------- | +| isLocked | boolean | Yes | Whether to lock auto rotate. The value **true** means to lock auto rotate, and **false** means the opposite.| + +**Return value** +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** +```js +var isLocked = false; +screen.setScreenRotationLocked(isLocked).then((data) => { + console.info('Succeeded in setting whether to lock screen rotation'); +}).catch((err) => { + console.error('Failed to set whether to lock screen rotation. Cause:' + JSON.stringify(err)); +}); +``` + +## screen.setScreenRotationLocked +setScreenRotationLocked(isLocked: boolean, callback: AsyncCallback<void>): void + +Sets whether to lock auto rotate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ------------------------------------------------------------ | +| isLocked | boolean | Yes | Whether to lock auto rotate. The value **true** means to lock auto rotate, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** + +```js +var isLocked = false; +screen.setScreenRotationLocked(isLocked, (err, data) => { + if (err.code) { + console.error('Failed to set whether to lock screen rotation. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting whether to lock screen rotation.'); +}); +``` + +## ExpandOption +Defines the parameters for expanding a screen. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type| Readable| Writable| Description | +| -------- | -------- | ---- | ---- | ------------------- | +| screenId | number | Yes | Yes | Screen ID. | +| startX | number | Yes | Yes | Start X coordinate of the screen.| +| startY | number | Yes | Yes | Start Y coordinate of the screen.| + +## VirtualScreenOption +Defines virtual screen parameters. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ------------------------- | +| name | string | Yes | Yes | Name of a virtual screen. | +| width | number | Yes | Yes | Width of the virtual screen. | +| height | number | Yes | Yes | Height of the virtual screen. | +| density | number | Yes | Yes | Density of the virtual screen. | +| surfaceId | string | Yes | Yes | Surface ID of the virtual screen.| + +## Screen +Implements a **Screen** instance. + +Before calling any API in **Screen**, you must use **[getAllScreens()](#screengetallscreens)** or **[createVirtualScreen()](#screencreatevirtualscreen)** to obtain a **Screen** instance. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Readable| Writable| Description | +| ----------------- | ---------------------------------------------- | ---- | ---- | ---------------------- | +| id | number | Yes | No | Screen ID. | +| parent | number | Yes | No | ID of the group to which a screen belongs. | +| supportedModeInfo | Array<[ScreenModeInfo](#screenmodeinfo)> | Yes | No | Mode set supported by the screen. | +| activeModeIndex | number | Yes | No | Index of the active screen mode.| +| orientation | [Orientation](#orientation) | Yes | No | Screen orientation. | + +### setOrientation +setOrientation(orientation: Orientation, callback: AsyncCallback<void>): void + +Sets the screen orientation. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | +| orientation | [Orientation](#orientation) | Yes | Screen orientation. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the screen orientation is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** +```js +screenClass.setOrientation(screen.Orientation.VERTICAL, (err, data) => { + if (err.code) { + console.error('Failed to setOrientation VERTICAL. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting Orientation VERTICAL. data: ' + JSON.stringify(data)); +}) +``` +### setOrientation +setOrientation(orientation: Orientation): Promise<void> + +Sets the screen orientation. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ---------- | +| orientation | [Orientation](#orientation) | Yes | Screen orientation.| + +**Return value** +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** +```js +let promise = screenClass.setOrientation(screen.Orientation.VERTICAL); +promise.then((data) => { + console.info('Succeeded in setting Orientation VERTICAL. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to set Orientation VERTICAL. Cause: ' + JSON.stringify(err)); +}) +``` +### setScreenActiveMode +setScreenActiveMode(modeIndex: number, callback: AsyncCallback<void>): void + +Sets the active mode of the screen. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ------------------------------------------------------------ | +| modeIndex | number | Yes | Index of the mode to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the active mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** + +```js +var modeIndex = 0; +screenClass.setScreenActiveMode(modeIndex, (err, data) => { + if (err.code) { + console.error('Failed to set ScreenActiveMode 0. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting ScreenActiveMode 0. data: ' + JSON.stringify(data)); +}) +``` +### setScreenActiveMode +setScreenActiveMode(modeIndex: number): Promise<void> + +Sets the active mode of the screen. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------- | +| modeIndex | number | Yes | Index of the mode to set.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** +```js +var modeIndex = 0; +let promise = screenClass.setScreenActiveMode(modeIndex); +promise.then((data) => { + console.info('Succeeded in setting ScreenActiveMode 0. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to set ScreenActiveMode 0. Cause: ' + JSON.stringify(err)); +}) +``` + +### setDensityDpi +setDensityDpi(densityDpi: number, callback: AsyncCallback<void>): void; + +Sets the pixel density of the screen. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------------------------------------------------------ | +| densityDpi | number | Yes | Pixel density. The value ranges from 80 to 640. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the pixel density is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** +```js +var densityDpi = 320; +screenClass.setDensityDpi(densityDpi, (err, data) => { + if (err.code) { + console.error('Failed to set DensityDpi 320. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeed in setting DensityDpi 320. data: ' + JSON.stringify(data)); +}) +``` + +### setDensityDpi +setDensityDpi(densityDpi: number): Promise<void> + +Sets the pixel density of the screen. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ---------------------------------- | +| densityDpi | number | Yes | Pixel density. The value ranges from 80 to 640.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** +```js +var densityDpi = 320; +var promise = screenClass.setDensityDpi(densityDpi); +promise.then((data) => { + console.info('Succeeded in setting DensityDpi 320. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to set DensityDpi 320. Cause: ' + JSON.stringify(err)); +}) +``` + +## Orientation +Enumerates the screen orientations. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Value | Description | +| ------------------ | ---- | -------------------------------- | +| UNSPECIFIED | 0 | Unspecified. The screen orientation is determined by the system.| +| VERTICAL | 1 | Vertical. | +| HORIZONTAL | 2 | Horizontal. | +| REVERSE_VERTICAL | 3 | Reverse vertical. | +| REVERSE_HORIZONTAL | 4 | Reverse horizontal. | + +## ScreenModeInfo +Defines the screen mode information. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type| Readable| Writable| Description | +| ----------- | -------- | ---- | ---- | -------------------------------------------------- | +| id | number | Yes | Yes | Mode ID. The supported mode is determined by the device resolution and refresh rate.| +| width | number | Yes | Yes | Screen width. | +| height | number | Yes | Yes | Screen height. | +| refreshRate | number | Yes | Yes | Screen refresh rate. | 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-service-extension-ability.md b/en/application-dev/reference/apis/js-apis-service-extension-ability.md index b66c29fe1834b589ee9ffd32eb598e5c53dc2e0a..388657b05dce3f05601cc88123ff2d64adbf127b 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-ability.md @@ -1,12 +1,12 @@ # ServiceExtensionAbility +The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Provides APIs related to **ServiceExtension**. - ## Modules to Import ``` @@ -21,24 +21,28 @@ None. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate onCreate(want: Want): void; -Called when an extension is created to initialize the service logic. +Called when a Service Extension ability is created to initialize the service logic. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this extension, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -55,10 +59,12 @@ Called when an extension is created to initialize the service logic. onDestroy(): void; -Called when this extension is destroyed to clear resources. +Called when this Service Extension ability is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Example** ```js @@ -74,16 +80,18 @@ Called when this extension is destroyed to clear resources. onRequest(want: Want, startId: number): void; -Called after **onCreate** is invoked when an ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. +Called after **onCreate** is invoked when a Service Extension ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this extension, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| +| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** @@ -100,21 +108,23 @@ Called after **onCreate** is invoked when an ability is started by calling **sta onConnect(want: Want): rpc.RemoteObject; -Called after **onCreate** is invoked when an ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. +Called after **onCreate** is invoked when a Service Extension ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md)| Yes| Information related to this extension, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| +| Type| Description| +| -------- | -------- | +| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| **Example** @@ -140,15 +150,17 @@ Called after **onCreate** is invoked when an ability is started by calling **con onDisconnect(want: Want): void; -Called when the ability is disconnected. +Called when this Service Extension ability is disconnected. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-Want.md)| Yes| Information related to this extension, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -159,3 +171,82 @@ Called when the ability is disconnected. } } ``` + +## ServiceExtensionAbility.onReconnect + +onReconnect(want: Want): void; + +Called when this Service Extension ability is reconnected. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + +**Example** + + ```js + class ServiceExt extends ServiceExtension { + onDisconnect(want) { + console.log('onDisconnect, want:' + want.abilityName); + } + } + ``` + +## ServiceExtensionAbility.onConfigurationUpdated + +onConfigurationUpdated(config: Configuration): void; + +Called when the configuration of this Service Extension ability is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + +**Example** + + ```js + class ServiceExt extends ServiceExtension { + onConfigurationUpdated(config) { + console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + } + } + ``` + +## ServiceExtensionAbility.dump + +dump(params: Array\): Array\; + +Dumps the client information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| + +**Example** + + ```js + class ServiceExt extends ServiceExtension { + dump(params) { + console.log('dump, params:' + JSON.stringify(params)); + return ["params"] + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index 518167d562ba8801223e206ad5b35ea07ea94936..241a8bf17f94a3362fe6d12d4662b139c4c4cd8b 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -1,16 +1,25 @@ # ServiceExtensionContext +The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for Service Extension abilities. + +You can use the APIs of this module to start, terminate, connection, and disconnect abilities. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -Implements the context that provides the capabilities and APIs of **ServiceExtension**. This class is inherited from **ExtensionContext**. +## Usage -## Modules to Import +Before using the **ServiceExtensionContext** module, you must define a child class that inherits from **ServiceExtensionAbility**. -``` -import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; +```js + import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'; + class MainAbility extends ServiceExtensionAbility { + onCreate() { + let context = this.context; + } + } ``` ## startAbility @@ -21,6 +30,8 @@ Starts an ability. This API uses a callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -31,34 +42,30 @@ Starts an ability. This API uses a callback to return the result. **Example** ```js - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; - class MainAbility extends ExtensionContext { - onWindowStageCreate(windowStage) { - let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility"}; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringify(err)); - }); - } - } - + let want = { + "bundleName": "com.example.myapp", + "abilityName": "MyAbility"}; + this.context.startAbility(want, (err) => { + console.log('startAbility result:' + JSON.stringify(err)); + }); ``` +## startAbility -## ServiceExtensionContext.startAbility - -startAbility(want: Want): Promise<void>; +startAbility(want: Want, options?: StartOptions): Promise\; Starts an ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| + | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| **Return value** @@ -69,24 +76,428 @@ Starts an ability. This API uses a promise to return the result. **Example** ```js - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; - class MainAbility extends ExtensionContext { - onWindowStageCreate(windowStage) { - let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility" - }; - this.context.startAbility(want).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - } - } - - + let want = { + "bundleName": "com.example.myapp", + "abilityName": "MyAbility" + }; + this.context.startAbility(want).then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + + ``` + +## startAbility + +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void + +Starts an ability. This API uses a callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var options = { + windowMode: 0, + }; + this.context.startAbility(want, options, (error) => { + console.log("error.code = " + error.code) + }) + ``` + +## ServiceExtensionContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startAbilityWithAccount(want, accountId, (err) => { + console.log('---------- startAbilityWithAccount fail, err: -----------', err); + }); + ``` + + +## ServiceExtensionContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; + +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0, + }; + this.context.startAbilityWithAccount(want, accountId, options, (err) => { + console.log('---------- startAbilityWithAccount fail, err: -----------', err); + }); + ``` + + +## ServiceExtensionContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; + +Starts an ability with the account ID specified. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0, + }; + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + console.log('---------- startAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startAbilityWithAccount fail, err: -----------', err); + }) ``` +## ServiceExtensionContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.startServiceExtensionAbility(want, (err) => { + console.log('---------- startServiceExtensionAbility fail, err: -----------', err); + }); + ``` + +## ServiceExtensionContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want): Promise\; + +Starts a new Service Extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.startServiceExtensionAbility(want) + .then((data) => { + console.log('---------- startServiceExtensionAbility success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startServiceExtensionAbility fail, err: -----------', err); + }) + ``` + +## ServiceExtensionContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startServiceExtensionAbilityWithAccount(want,accountId, (err) => { + console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); + }); + ``` + +## ServiceExtensionContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startServiceExtensionAbilityWithAccount(want,accountId) + .then((data) => { + console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); + }) + ``` + +## ServiceExtensionContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Stops Service Extension abilities in the same application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.stopServiceExtensionAbility(want, (err) => { + console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); + }); + ``` + +## ServiceExtensionContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want): Promise\; + +Stops Service Extension abilities in the same application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.stopServiceExtensionAbility(want) + .then((data) => { + console.log('---------- stopServiceExtensionAbility success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); + }) + ``` + +## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Stops Service Extension abilities in the same application with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.stopServiceExtensionAbilityWithAccount(want,accountId, (err) => { + console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); + }); + ``` + +## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Stops Service Extension abilities in the same application with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.stopServiceExtensionAbilityWithAccount(want,accountId) + .then((data) => { + console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); + }) + ``` ## ServiceExtensionContext.terminateSelf @@ -96,6 +507,8 @@ Terminates this ability. This API uses a callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -105,19 +518,11 @@ Terminates this ability. This API uses a callback to return the result. **Example** ```js - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; - class MainAbility extends ExtensionContext { - onWindowStageCreate(windowStage) { - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); - }); - } - } - - + this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringify(err)); + }); ``` - ## ServiceExtensionContext.terminateSelf terminateSelf(): Promise<void>; @@ -126,6 +531,8 @@ Terminates this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type| Description| @@ -135,20 +542,13 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```js - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; - class MainAbility extends ExtensionContext { - onWindowStageCreate(windowStage) { - this.context.terminateSelf().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - } -} - + this.context.terminateSelf().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); ``` - ## ServiceExtensionContext.connectAbility connectAbility(want: Want, options: ConnectOptions): number; @@ -157,12 +557,14 @@ Connects this ability to a Service ability. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to connect to, such as the ability name and bundle name.| - | options | [ConnectOptions](#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| + | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| **Return value** @@ -174,17 +576,58 @@ Connects this ability to a Service ability. ```js let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility" + "bundleName": "com.example.myapp", + "abilityName": "MyAbility" }; let options = { - onConnect: function(elementName, proxy) {}, - onDisConnect: function(elementName) {}, - onFailed: function(code) {} + onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, + onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, + onFailed(code) { console.log('----------- onFailed -----------') } } let connection = this.context.connectAbility(want,options); ``` +## ServiceExtensionContext.connectAbilityWithAccount + +connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; + +Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| ID of the account.| +| options | ConnectOptions | No| Remote object instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Result code of the ability connection.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + var options = { + onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, + onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, + onFailed(code) { console.log('----------- onFailed -----------') } + } + const result = this.context.connectAbilityWithAccount(want, accountId, options); + console.log('----------- connectAbilityResult: ------------', result); + ``` ## ServiceExtensionContext.disconnectAbility @@ -194,6 +637,8 @@ Disconnects this ability from the Service ability. This API uses a callback to r **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -204,21 +649,13 @@ Disconnects this ability from the Service ability. This API uses a callback to r **Example** ```js - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; - class MainAbility extends ExtensionContext { - onWindowStageCreate(windowStage) { - let connection=1 - this.context.disconnectAbility(connection, (err) => { + let connection=1 + this.context.disconnectAbility(connection, (err) => { // connection is the return value of connectAbility. console.log('terminateSelf result:' + JSON.stringify(err)); - }); - } - } - - + }); ``` - ## ServiceExtensionContext.disconnectAbility disconnectAbility(connection: number): Promise<void>; @@ -227,6 +664,8 @@ Disconnects this ability from the Service ability. This API uses a promise to re **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -242,29 +681,11 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Example** ```js - import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; - class MainAbility extends ExtensionContext { - onWindowStageCreate(windowStage) { - let connection=1 - this.context.disconnectAbility(connection).then((data) => { // connection is the return value of connectAbility. + let connection=1 + this.context.disconnectAbility(connection).then((data) => { + // connection is the return value of connectAbility. console.log('success:' + JSON.stringify(data)); - }).catch((error) => { + }).catch((error) => { console.log('failed:' + JSON.stringify(error)); - }); - } - } - + }); ``` - - -## ConnectOptions - -Defines the **ConnectOptions** data structure. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Description| -| -------- | -------- | -| onConnect(elementName:ElementName, remote:IRemoteObject) | Called when this ability is connected to a Service ability.| -| onDisconnect(elementName:ElementName) | Called when the peer service is abnormal or killed.| -| onFailed(code: number) | Called when the connection fails.| diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index acad2c7f0223074ef134389ddeac17b8f8d47455..41a4cfc71c77ff92c77b4b16ed19de9af6395bd3 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -1,5 +1,7 @@ # SIM Management +The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. + >**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. @@ -520,7 +522,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[IccAccountInfo](#IccAccountInfo7)\> | Yes | Callback used to return the result. For details, see [IccAccountInfo](#IccAccountInfo7).| +| callback | AsyncCallback\<[IccAccountInfo](#IccAccountInfo7)\> | Yes | Callback used to return the result. | **Example** @@ -672,7 +674,7 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise used to return the result. | **Example** @@ -737,7 +739,7 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise used to return the result. | **Example** @@ -867,7 +869,7 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise used to return the result. | **Example** @@ -994,7 +996,7 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise used to return the result. | **Example** @@ -1057,7 +1059,7 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 11fdf806794469274ea30ee3b4797b42f9041965..25069b318add375d68d97084e45b08c1f69f3804 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -1,5 +1,7 @@ # SMS +The SMS module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. + >**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. @@ -206,7 +208,7 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise used to return the result. | **Example** 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-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index 309e32bdae7af66c7ca14802f734ccca0ccdbb99..4a711c1f7cbf0defdbcd9ea0c28a08e981c594a9 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -1,5 +1,7 @@ # Cellular Data +The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. + >**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. @@ -78,7 +80,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -110,7 +112,7 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise<\void\> | Promise that returns no value. | +| Promise<\void\> | Promise used to return the result. | **Example** @@ -174,7 +176,7 @@ promise.then((data) => { getCellularDataState(callback: AsyncCallback\): void -Obtains the connection status of the packet switched (PS) domain. This API uses an asynchronous callback to return the result. +Obtains the connection status of the PS domain. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CellularData @@ -342,14 +344,14 @@ Defines the cellular data flow type. ## DataConnectState -Describes the connection status of a cellular data link. +Describes the connection status of a cellular data connection. **System capability**: SystemCapability.Telephony.CellularData | Name | Value | Description | | ----------------------- | ---- | -------------------------- | -| DATA_STATE_UNKNOWN | -1 | The status of the cellular data link is unknown. | -| DATA_STATE_DISCONNECTED | 0 | The cellular data link is disconnected. | -| DATA_STATE_CONNECTING | 1 | The cellular data link is being connected.| -| DATA_STATE_CONNECTED | 2 | The cellular data link is connected. | -| DATA_STATE_SUSPENDED | 3 | The cellular data link is suspended. | +| DATA_STATE_UNKNOWN | -1 | The status of the cellular data connection is unknown. | +| DATA_STATE_DISCONNECTED | 0 | The cellular data connection is disconnected. | +| DATA_STATE_CONNECTING | 1 | The cellular data connection is being established.| +| DATA_STATE_CONNECTED | 2 | The cellular data connection is established. | +| DATA_STATE_SUSPENDED | 3 | The cellular data connection is suspended. | diff --git a/en/application-dev/reference/apis/js-apis-testRunner.md b/en/application-dev/reference/apis/js-apis-testRunner.md index 717c8448a00518b777b882fa7a49d7aca4509e11..bc65de36ea0283d025deb74006dd428d7adefbd7 100644 --- a/en/application-dev/reference/apis/js-apis-testRunner.md +++ b/en/application-dev/reference/apis/js-apis-testRunner.md @@ -1,5 +1,9 @@ # TestRunner +The **TestRunner** module provides a test framework. You can use the APIs of this module to prepare the unit test environment and run test cases. + +To implement your own unit test framework, extend this class and override its APIs. + > **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. @@ -10,8 +14,6 @@ import TestRunner from '@ohos.application.testRunner' ``` - - ## TestRunner.onPrepare onPrepare(): void @@ -23,10 +25,11 @@ Prepares the unit test environment to run test cases. **Example** ```js -export default class UserTestRunner extends TestRunner { +export default class UserTestRunner implements TestRunner { onPrepare() { console.log("Trigger onPrepare") } +onRun(){} }; ``` @@ -43,9 +46,10 @@ Runs test cases. **Example** ```js -export default class UserTestRunner extends TestRunner { - onRun() { - console.log("Trigger onRun") +export default class UserTestRunner implements TestRunner { + onPrepare() { + console.log("Trigger onRun") } +onRun(){} }; ``` diff --git a/en/application-dev/reference/apis/js-apis-uiappearance.md b/en/application-dev/reference/apis/js-apis-uiappearance.md new file mode 100644 index 0000000000000000000000000000000000000000..3bac964627675b3475e273551d06b146636b410d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-uiappearance.md @@ -0,0 +1,106 @@ +# UI Appearance + +The **uiAppearance** module provides basic capabilities for managing the system appearance. It allows for color mode configuration currently, and will introduce more features over time. + +> **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. + + +## Modules to Import + +```ts +import uiAppearance from '@ohos.uiAppearance' +``` + + +## DarkMode + +Enumerates the color modes. + + +**System capability**: SystemCapability.ArkUI.UiAppearance + +| Name| Value| Description| +| -- | -- | -- | +| ALWAYS_DARK | 0 | The system is always in dark mode. | +| ALWAYS_LIGHT | 1 | The system is always in light mode.| + + +## uiAppearance.setDarkMode + +setDarkMode(mode: DarkMode, callback: AsyncCallback\): void + +Sets the system color mode. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.ArkUI.UiAppearance + +**Parameters** +| Name| Type| Mandatory| Description| +| -- | -- | -- | -- | +| mode | [DarkMode](#darkmode) | Yes| Color mode to set.| +| callback | AsyncCallback\| Yes| Callback used to return the result.| + +**Example** + ```ts +uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK, (err) => { + console.info(`${err}`); +}) + ``` + + +## uiAppearance.setDarkMode + +setDarkMode(mode: DarkMode): Promise\; + +Sets the system color mode. This API uses a promise to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**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(() => { + console.log('Set dark-mode successfully.'); +}).catch((err) => { + console.log(`Set dark-mode failed, ${err}`); +}); + ``` + + +## uiAppearance.getDarkMode + +getDarkMode(): DarkMode; + +Obtains the system color mode. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.ArkUI.UiAppearance + +**Return value** +| Type| Description| +| -- | -- | +|[DarkMode](#darkmode) | Color mode obtained.| + +**Example** + ```ts +let darkMode = uiAppearance.getDarkMode(); +console.log(`Get dark-mode ${darkMode}`); + ``` diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 251c1d59b610f4d01372186d0e40d0521cf62ca8..64d76026eeb3981fd589401d71f599fc2112f9dd 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -1,8 +1,5 @@ # Update -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - The Update module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. There are two types of updates: SD card update and over the air (OTA) update. @@ -10,135 +7,180 @@ There are two types of updates: SD card update and over the air (OTA) update. - The SD card update depends on the update packages and SD cards. - The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + ## Modules to Import ```js import update from '@ohos.update' ``` -## Required Permissions - -None - -## update.getUpdater +## update.getOnlineUpdater -getUpdater(upgradeFile: string, updateType?: UpdateTypes): Updater +getOnlineUpdater(upgradeInfo: UpgradeInfo): Updater -Obtains the **Updater** object for local update. +Obtains an **OnlineUpdater** object. **System capability**: SystemCapability.Update.UpdateService **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | --------------------------- | --------- | ------------ | -| upgradeFile | string | Yes | Update file. | -| updateType | [UpdateTypes](#updatetypes) | Yes | Update type. | +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | ---- | ---- | +| upgradeInfo | [UpgradeInfo](#upgradeinfo) | Yes | **UpgradeInfo** object.| **Return value** -| Type | Description | -| ------------------- | ------------------- | -| [Updater](#updater) | **Updater** object. | +| Type | Description | +| ------------------- | ---- | +| [Updater](#updater) | **OnlineUpdater** object.| **Example** ``` try { - let updater = update.getUpdater('/data/updater/updater.zip', 'OTA'); + var upgradeInfo = { + upgradeApp: "com.ohos.ota.updateclient", + businessType: { + vendor: update.BusinessVendor.PUBLIC, + subType: update.BusinessSubType.FIRMWARE + } + } + let updater = update.getOnlineUpdater(upgradeInfo); } catch(error) { - console.error(" Fail to get updater error: " + error); + console.error(`Fail to get updater error: ${error}`); } ``` -## update.getUpdaterForOther +## update.getRestorer -getUpdaterForOther(upgradeFile: string, device: string, updateType?: UpdateTypes): Updater +getRestorer(): Restorer -Obtains the **Updater** object for the device to be updated. +Obtains a **Restorer** object for restoring factory settings. **System capability**: SystemCapability.Update.UpdateService -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | --------------------------- | --------- | --------------------- | -| upgradeFile | string | Yes | Update file. | -| device | string | Yes | Device to be updated. | -| updateType | [UpdateTypes](#updatetypes) | Yes | Update type. | **Return value** -| Type | Description | -| ------------------- | ------------------- | -| [Updater](#updater) | **Updater** object. | +| Type | Description | +| ------------------- | ---- | +| [Restorer](#restorer) | **Restorer** object for restoring factory settings.| **Example** ``` try { - let updater = update.getUpdaterForOther('/data/updater/updater.zip', '1234567890', 'OTA'); + let restorer = update.getRestorer(); } catch(error) { - console.error(" Fail to get updater error: " + error); + console.error(`Fail to get restorer: ${error}`); } ``` -## update.getUpdaterFromOther +## update.getLocalUpdater -getUpdaterFromOther(upgradeFile: string, device: string, updateType?: UpdateTypes): Updater +getLocalUpdater(): LocalUpdater -Obtains the **Updater** object from another device for the device to be updated. +Obtains a **LocalUpdater** object. **System capability**: SystemCapability.Update.UpdateService -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | --------------------------- | --------- | --------------------- | -| upgradeFile | string | Yes | Update file. | -| device | string | Yes | Device to be updated. | -| updateType | [UpdateTypes](#updatetypes) | Yes | Update type. | - **Return value** -| Type | Description | -| ------------------- | ------------------- | -| [Updater](#updater) | **Updater** object. | +| Type | Description | +| ------------------- | ---- | +| [LocalUpdater](#localupdater) | **LocalUpdater** object.| **Example** ``` try { - let updater = update.getUpdaterFromOther('/data/updater/updater.zip', '1234567890', 'OTA'); + let localUpdater = update.getLocalUpdater(); } catch(error) { - console.error(" Fail to get updater error: " + error); + console.error(`Fail to get localUpdater error: ${error}`); } ``` ## Updater +### checkNewVersion + +checkNewVersion(callback: AsyncCallback\): void + +Checks whether a new version is available. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[CheckResult](#checkresult)> | Yes | Callback used to return the result.| + +**Example** + +``` +updater.checkNewVersion((err, result) => { + console.log(`checkNewVersion isExistNewVersion ${result?.isExistNewVersion}`); +}); +``` + +### checkNewVersion + +checkNewVersion(): Promise\ + +Checks whether a new version is available. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[CheckResult](#checkresult)> | Promise used to return the result.| + +**Example** + +``` +updater.checkNewVersion().then(result => { + console.log(`checkNewVersion isExistNewVersion: ${result.isExistNewVersion}`); + // Version digest information + console.log(`checkNewVersion versionDigestInfo: ${result.newVersionInfo.versionDigestInfo.versionDigest}`); +}).catch(err => { + console.log(`checkNewVersion promise error ${JSON.stringify(err)}`); +}); +``` + ### getNewVersionInfo getNewVersionInfo(callback: AsyncCallback\): void -Obtains the new version information. This function uses an asynchronous callback to return the result. +Obtains information about the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[NewVersionInfo](#newversioninfo)> | No | Callback used to return the new version information. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[NewVersionInfo](#newversioninfo)> | Yes | Callback used to return the result.| **Example** ``` -updater.getNewVersionInfo(info => { - console.log("getNewVersionInfo success " + info.status); - console.log(`info versionName = ` + info.checkResult[0].versionName); - console.log(`info versionCode = ` + info.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); +updater.getNewVersionInfo((err, info) => { + console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`); + console.log(`info innerVersion = ${info?.versionComponents[0].innerVersion}`); }); ``` @@ -146,451 +188,1562 @@ updater.getNewVersionInfo(info => { getNewVersionInfo(): Promise\ -Obtains the new version information. This function uses a promise to return the result. +Obtains information about the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the new version information. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the result.| **Example** ``` -updater.getNewVersionInfo().then(value => { - console.log(`info versionName = ` + value.checkResult[0].versionName); - console.log(`info versionCode = ` + value.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); +updater.getNewVersionInfo().then(info => { + console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`); + console.log(`info innerVersion = ${info.versionComponents[0].innerVersion}`); }).catch(err => { - console.log("getNewVersionInfo promise error: " + err.code); + console.log(`getNewVersionInfo promise error ${JSON.stringify(err)}`); }); ``` -### checkNewVersion +### getNewVersionDescription -checkNewVersion(callback: AsyncCallback\): void +getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOptions: DescriptionOptions, callback: AsyncCallback\>): void -Checks whether the current version is the latest. This function uses an asynchronous callback to return the result. +Obtains the description file of the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\<[NewVersionInfo](#newversioninfo)> | No | Callback used to return the new version information. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| +| callback | AsyncCallback\>) | Yes | Callback used to return the result.| **Example** ``` -updater.checkNewVersion(info => { - console.log("checkNewVersion success " + info.status); - console.log(`info versionName = ` + info.checkResult[0].versionName); - console.log(`info versionCode = ` + info.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => { + console.log(`getNewVersionDescription info ${JSON.stringify(info)}`); + console.log(`getNewVersionDescription err ${JSON.stringify(err)}`); }); ``` -### checkNewVersion +### getNewVersionDescription + +getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOptions: DescriptionOptions): Promise\>; + +Obtains the description file of the new version. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\> | Promise used to return the result.| + +**Example** -checkNewVersion(): Promise\ +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => { + console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`); +}).catch(err => { + console.log(`getNewVersionDescription promise error ${JSON.stringify(err)}`); +}); +``` + +### getCurrentVersionInfo + +getCurrentVersionInfo(callback: AsyncCallback\): void + +Obtains information about the current version. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** -Checks whether the current version is the latest. This function uses a promise to return the result. +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[CurrentVersionInfo](#currentversioninfo)> | Yes | Callback used to return the result.| + +**Example** + +``` +updater.getCurrentVersionInfo((err, info) => { + console.log(`info osVersion = ${info?.osVersion}`); + console.log(`info deviceName = ${info?.deviceName}`); + console.log(`info displayVersion = ${info?.versionComponents[0].displayVersion}`); +}); +``` + +### getCurrentVersionInfo + +getCurrentVersionInfo(): Promise\ + +Obtains information about the current version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the new version information. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[CurrentVersionInfo](#currentversioninfo)> | Promise used to return the result.| **Example** ``` -updater.checkNewVersion().then(value => { - console.log(`info versionName = ` + value.checkResult[0].versionName); - console.log(`info versionCode = ` + value.checkResult[0].versionCode); - console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); +updater.getCurrentVersionInfo().then(info => { + console.log(`info osVersion = ${info.osVersion}`); + console.log(`info deviceName = ${info.deviceName}`); + console.log(`info displayVersion = ${info.versionComponents[0].displayVersion}`); }).catch(err => { - console.log("checkNewVersion promise error: " + err.code); + console.log(`getCurrentVersionInfo promise error ${JSON.stringify(err)}`); }); ``` -### verifyUpdatePackage +### getCurrentVersionDescription -verifyUpdatePackage(upgradeFile: string, certsFile: string): void +getCurrentVersionDescription(descriptionOptions: DescriptionOptions, callback: AsyncCallback\>): void -Verifies whether the update package is valid. +Obtains the description file of the current version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | --------- | ---------------------------------------- | -| upgradeFile | string | Yes | Path of the update package to be verified. | -| certsFile | string | Yes | Certificate path. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| +| callback | AsyncCallback\>) | Yes | Callback used to return the result.| **Example** ``` -updater.on("verifyProgress", callback => { - console.info('on verifyProgress ' + callback.percent); +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getCurrentVersionDescription(descriptionOptions, (err, info) => { + console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`); + console.log(`getCurrentVersionDescription err ${JSON.stringify(err)}`); }); -update.verifyUpdatePackage("XXX", "XXX"); ``` -### rebootAndCleanUserData8+ +### getCurrentVersionDescription -rebootAndCleanUserData(): Promise\ +getCurrentVersionDescription(descriptionOptions: DescriptionOptions): Promise\> -Reboots the device and clears the user partition data. This function uses a promise to return the result. +Obtains the description file of the current version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file.| + **Return value** -| Type | Description | -| ---------------- | ---------------------------------------- | -| Promise\ | Promise used to return the execution result. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\> | Promise used to return the result.| **Example** ``` -updater.rebootAndCleanUserData().then(result => { - console.log("rebootAndCleanUserData " + result); +// Options of the description file +var descriptionOptions = { + format: DescriptionFormat.STANDARD, // Standard format + language: "zh-cn" // Chinese +} + +updater.getCurrentVersionDescription(descriptionOptions).then(info => { + console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`); }).catch(err => { - console.info("rebootAndCleanUserData promise error: " + err.code); + console.log(`getCurrentVersionDescription promise error ${JSON.stringify(err)}`); }); ``` -### rebootAndCleanUserData8+ +### getTaskInfo -rebootAndCleanUserData(callback: AsyncCallback\): void +getTaskInfo(callback: AsyncCallback\): void -Reboots the device and clears the user partition data. This function uses a promise to return the result. +Obtains information about the update task. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\<[TaskInfo](#taskinfo)> | Yes | Callback used to return the result.| **Example** ``` -updater.rebootAndCleanUserData(result => { - console.log("rebootAndCleanUserData ", result) +updater.getTaskInfo((err, info) => { + console.log(`getTaskInfo isexistTask= ${info?.existTask}`); }); ``` -### applyNewVersion +### getTaskInfo -applyNewVersion(): Promise\ +getTaskInfo(): Promise\ -Installs the update package. This function uses a promise to return the result. +Obtains information about the update task. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Return value** -| Type | Description | -| ---------------- | ---------------------------------------- | -| Promise\ | Promise used to return the execution result. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\<[TaskInfo](#taskinfo)> | Promise used to return the result.| **Example** ``` -updater.applyNewVersion().then(result => { - console.log("appVewVersion ", result) +updater.getTaskInfo().then(info => { + console.log(`getTaskInfo isexistTask= ${info.existTask}`); }).catch(err => { - console.info("applyNewVersion promise error: " + err.code); + console.log(`getTaskInfo promise error ${JSON.stringify(err)}`); }); ``` -### applyNewVersion +### download -applyNewVersion(callback: AsyncCallback\): void +download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions, callback: AsyncCallback\): void -Installs the update package. This function uses a promise to return the result. +Downloads the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| downloadOptions | [DownloadOptions](#downloadoptions) | Yes | Download options.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| **Example** ``` -updater.applyNewVersion(result => { - console.log("applyNewVersion ", result) +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Download options +var downloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network + order: update.Order.DOWNLOAD // Download +} +updater.download(versionDigestInfo, downloadOptions, (err) => { + console.log(`download error ${JSON.stringify(err)}`); }); ``` ### download -download(): void +download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions): Promise\ -Downloads the new version and displays the download process. +Downloads the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| downloadOptions | [DownloadOptions](#downloadoptions) | Yes | Download options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + **Example** ``` -updater.on("downloadProgress", progress => { - console.log("downloadProgress on" + progress); - console.log(`downloadProgress status: ` + progress.status); - console.log(`downloadProgress percent: ` + progress.percent); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Download options +var downloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network + order: update.Order.DOWNLOAD // Download +} +updater.download(versionDigestInfo, downloadOptions).then(() => { + console.log(`download start`); +}).catch(err => { + console.log(`download error ${JSON.stringify(err)}`); }); -updater.download(); ``` -### upgrade +### resumeDownload + +resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: ResumeDownloadOptions, callback: AsyncCallback\): void + +Resumes download of the new version. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | Yes | Options for resuming download.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for resuming download +var resumeDownloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network +} +updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => { + console.log(`resumeDownload error ${JSON.stringify(err)}`); +}); +``` -upgrade():void +### resumeDownload -Starts an update. +resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: ResumeDownloadOptions): Promise\ + +Resumes download of the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | Yes | Options for resuming download.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + **Example** ``` -updater.on("upgradeProgress", progress => { - console.log("upgradeProgress on" + progress); - console.log(`upgradeProgress status: ` + progress.status); - console.log(`upgradeProgress percent: ` + progress.percent); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for resuming download +var resumeDownloadOptions = { + allowNetwork: update.NetType.CELLULAR, // Whether to allow download over data network +} +updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => { + console.log(`resumeDownload start`); +}).catch(err => { + console.log(`resumeDownload error ${JSON.stringify(err)}`); }); -updater.upgrade(); ``` -### setUpdatePolicy +### pauseDownload -setUpdatePolicy(policy: UpdatePolicy, callback: AsyncCallback\): void +pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseDownloadOptions, callback: AsyncCallback\): void -Sets the update policy. This function uses an asynchronous callback to return the result. +Pauses download of the new version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| policy | [UpdatePolicy](#updatepolicy) | Yes | Update policy to set. | -| callback | Callback used to return the execution result. | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | Yes | Options for pausing download.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| **Example** ``` -// Set the update policy. -let policy = { - autoDownload: false, - autoDownloadNet: true, - mode: 2, - autoUpgradeInterval: [ 2, 3 ], - autoUpgradeCondition: 2 +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for pausing download +var pauseDownloadOptions = { + isAllowAutoResume: true // Whether to allow automatic resuming of download } -updater.setUpdatePolicy(policy, result => { - console.log("setUpdatePolicy ", result) +updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => { + console.log(`pauseDownload error ${JSON.stringify(err)}`); }); ``` -### setUpdatePolicy +### pauseDownload -setUpdatePolicy(policy: UpdatePolicy): Promise\ +pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseDownloadOptions): Promise\ -Sets the update policy. This function uses a promise to return the result. +Resumes download of the new version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ----------------------------- | --------- | --------------------- | -| policy | [UpdatePolicy](#updatepolicy) | Yes | Update policy to set. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | Yes | Options for pausing download.| **Return value** -| Type | Description | -| ---------------- | ---------------------------------------- | -| Promise\ | Promise used to return the execution result. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| **Example** ``` -let policy = { - autoDownload: false, - autoDownloadNet: true, - mode: 2, - autoUpgradeInterval: [ 2, 3 ], - autoUpgradeCondition: 2 +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for pausing download +var pauseDownloadOptions = { + isAllowAutoResume: true // Whether to allow automatic resuming of download } -updater.setUpdatePolicy(policy).then(result => - console.log("setUpdatePolicy ", result) -).catch(err => { - console.log("setUpdatePolicy promise error: " + err.code); +updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => { + console.log(`pauseDownload`); +}).catch(err => { + console.log(`pauseDownload error ${JSON.stringify(err)}`); }); ``` -### getUpdatePolicy +### upgrade -getUpdatePolicy(callback: AsyncCallback\): void +upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions, callback: AsyncCallback\): void -Obtains the update policy. This function uses an asynchronous callback to return the result. +Updates the version. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\<[UpdatePolicy](#updatepolicy)> | No | Callback used to return the update policy. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| upgradeOptions | [UpgradeOptions](#upgradeoptions) | Yes | Update options.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| **Example** ``` -updater.getUpdatePolicy(policy => { - console.log("getUpdatePolicy success"); - console.log(`policy autoDownload = ` + policy.autoDownload); - console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet); - console.log(`policy mode = ` + policy.mode); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Installation options +var upgradeOptions = { + order: update.Order.INSTALL // Installation command +} +updater.upgrade(versionDigestInfo, upgradeOptions, (err) => { + console.log(`upgrade error ${JSON.stringify(err)}`); }); ``` -### getUpdatePolicy +### upgrade -getUpdatePolicy(): Promise\ +upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions): Promise\ -Obtains the update policy. This function uses a promise to return the result. +Updates the version. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| upgradeOptions | [UpgradeOptions](#upgradeoptions) | Yes | Update options.| + **Return value** -| Type | Description | -| --------------------------------------- | ---------------------------------------- | -| Promise\<[UpdatePolicy](#updatepolicy)> | Promise used to return the update policy. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| **Example** ``` -updater.getUpdatePolicy().then(value => { - console.log(`info autoDownload = ` + value.autoDownload); - console.log(`info autoDownloadNet = ` + value.autoDownloadNet); - console.log(`info mode = ` + value.mode); +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Installation options +var upgradeOptions = { + order: update.Order.INSTALL // Installation command +} +updater.upgrade(versionDigestInfo, upgradeOptions).then(() => { + console.log(`upgrade start`); }).catch(err => { - console.log("getUpdatePolicy promise error: " + err.code); + console.log(`upgrade error ${JSON.stringify(err)}`); }); ``` -## UpdateTypes +### clearError + +clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions, callback: AsyncCallback\): void -Enumerates update types. +Clears errors. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Description | -| ----- | ------------- | -| OTA | OTA update. | -| patch | Patch update. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| clearOptions | [ClearOptions](#clearoptions) | Yes | Clear options.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for clearing errors +var clearOptions = { + status: update.UpgradeStatus.UPGRADE_FAIL, +} +updater.clearError(versionDigestInfo, clearOptions, (err) => { + console.log(`clearError error ${JSON.stringify(err)}`); +}); +``` -## PackageTypes +### clearError -Enumerates update package types. +clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions): Promise\ + +Clears errors. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | -| -------------------- | ------------- | --------------------------------------- | -| PACKAGE_TYPE_NORMAL | 1 | Common update package. | -| PACKAGE_TYPE_BASE | 2 | Basic update package. | -| PACKAGE_TYPE_CUST | 3 | Custom update package. | -| PACKAGE_TYPE_PRELOAD | 4 | Preinstalled update package. | -| PACKAGE_TYPE_COTA | 5 | Parameter configuration update package. | -| PACKAGE_TYPE_VERSION | 6 | Version update package. | -| PACKAGE_TYPE_PATCH | 7 | Patch package. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information.| +| clearOptions | [ClearOptions](#clearoptions) | Yes | Update options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +// Version digest information +var versionDigestInfo = { + versionDigest: "versionDigest" // Version digest information in the check result +} + +// Options for clearing errors +var clearOptions = { + status: update.UpgradeStatus.UPGRADE_FAIL, +} +updater.clearError(versionDigestInfo, clearOptions).then(() => { + console.log(`clearError success`); +}).catch(err => { + console.log(`clearError error ${JSON.stringify(err)}`); +}); +``` + +### getUpgradePolicy -## InstallMode +getUpgradePolicy(callback: AsyncCallback\): void -Enumerates update modes. +Obtains the update policy. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | -| ------------------- | ------------- | ----------------- | -| INSTALL_MODE_NORMAL | 0 | Normal update. | -| INSTALL_MODE_NIGHT | 1 | Update at night. | -| INSTALL_MODE_AUTO | 2 | Automatic update. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\<[UpgradePolicy](#upgradepolicy)> | Yes | Callback used to return the result.| + +**Example** + +``` +updater.getUpgradePolicy((err, policy) => { + console.log(`policy downloadStrategy = ${policy?.downloadStrategy}`); + console.log(`policy autoUpgradeStrategy = ${policy?.autoUpgradeStrategy}`); +}); +``` + +### getUpgradePolicy -## NewVersionStatus +getUpgradePolicy(): Promise\ -Enumerates new version check results. +Obtains the update policy. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | -| ------------------- | ------------- | ---------------------------------------- | -| VERSION_STATUS_ERR | -1 | System error while checking for the new version. | -| VERSION_STATUS_NEW | 0 | New version detected. | -| VERSION_STATUS_NONE | 1 | No new version detected. | -| VERSION_STATUS_BUSY | 2 | System busy while checking for the new version. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise\<[UpgradePolicy](#upgradepolicy)> | Promise used to return the result.| + +**Example** + +``` +updater.getUpgradePolicy().then(policy => { + console.log(`policy downloadStrategy = ${policy.downloadStrategy}`); + console.log(`policy autoUpgradeStrategy = ${policy.autoUpgradeStrategy}`); +}).catch(err => { + console.log(`getUpgradePolicy promise error ${JSON.stringify(err)}`); +}); +``` -## UpdatePolicy +### setUpgradePolicy -Defines the update policy. +setUpgradePolicy(policy: UpgradePolicy, callback: AsyncCallback\): void + +Sets the update policy. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| ------------------- | --------------------------- | --------- | ------------------------------------ | -| autoDownload | bool | Yes | Automatic update switch. | -| installMode | [InstallMode](#installmode) | Yes | Update mode. | -| autoUpgradeInterval | Array\ | Yes | Period of time for automatic update. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) -## NewVersionInfo +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------- | +| policy | [UpgradePolicy](#upgradepolicy) | Yes | Update policy.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -Defines the new version information. +**Example** + +``` +let policy = { + downloadStrategy: false, + autoUpgradeStrategy: false, + autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes +} +updater.setUpgradePolicy(policy, (err) => { + console.log(`setUpgradePolicy result: ${err}`); +}); +``` + +### setUpgradePolicy + +setUpgradePolicy(policy: UpgradePolicy): Promise\ + +Sets the update policy. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| --------------- | ---------------------------------------- | --------- | -------------------------------- | -| status | [NewVersionStatus](#newversionstatus) | Yes | Update status. | -| errMsg | string | Yes | Error message. | -| checkResults | Array<[CheckResult](#checkresult)> | Yes | Version check result. | -| descriptionInfo | Array\<[DescriptionInfo](#descriptioninfo)> | Yes | Version description information. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) -## CheckResult +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------------- | ---- | ------ | +| policy | [UpgradePolicy](#upgradepolicy) | Yes | Update policy.| + +**Return value** + +| Type | Description | +| ---------------- | --------------- | +| Promise\ | Promise used to return the result.| -Defines the version check result. +**Example** + +``` +let policy = { + downloadStrategy: false, + autoUpgradeStrategy: false, + autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes +} +updater.setUpgradePolicy(policy).then(() => { + console.log(`setUpgradePolicy success`); +}).catch(err => { + console.log(`setUpgradePolicy promise error ${JSON.stringify(err)}`); +}); +``` + +### terminateUpgrade + +terminateUpgrade(callback: AsyncCallback\): void + +Terminates the update. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| ------------- | ----------------------------- | --------- | --------------------------------- | -| versionName | string | Yes | Version name. | -| versionCode | number | Yes | Version code. | -| size | number | Yes | Version size. | -| verifyInfo | string | Yes | Version verification information. | -| packageType | [PackageTypes](#packagetypes) | Yes | Version type. | -| descriptionId | string | Yes | Version description information. | +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) -## DescriptionInfo +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +updater.terminateUpgrade((err) => { + console.log(`terminateUpgrade error ${JSON.stringify(err)}`); +}); +``` + +### terminateUpgrade + +terminateUpgrade(): Promise\ + +Terminates the update. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +updater.terminateUpgrade().then(() => { + console.log(`terminateUpgrade success`); +}).catch(err => { + console.log(`terminateUpgrade error ${JSON.stringify(err)}`); +}); +``` + + +### on +on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): void + +Enables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +updater.on(eventClassifyInfo, (eventInfo) => { + console.log("updater on " + JSON.stringify(eventInfo)); +}); +``` + +### off +off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): void + +Disables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | No | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +updater.off(eventClassifyInfo, (eventInfo) => { + console.log("updater off " + JSON.stringify(eventInfo)); +}); +``` + +## Restorer + +### factoryReset + +factoryReset(callback: AsyncCallback\): void + +Restores factory settings. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.FACTORY_RESET (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +restorer.factoryReset((err) => { + console.log(`factoryReset error ${JSON.stringify(err)}`); +}); +``` + +### factoryReset + +factoryReset(): Promise\ + +Restores factory settings. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.FACTORY_RESET (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +restorer.factoryReset().then(() => { + console.log(`factoryReset success`); +}).catch(err => { + console.log(`factoryReset error ${JSON.stringify(err)}`); +}); +``` + +## LocalUpdater + +### verifyUpgradePackage + +verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string, callback: AsyncCallback\): void + +Verifies the update package. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| upgradeFile | [UpgradeFile](#upgradefile) | Yes | Update file.| +| certsFile | string | Yes | Path of the certificate file.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +``` +var upgradeFile = { + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +} + +localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => { + console.log(`factoryReset error ${JSON.stringify(err)}`); +}); +``` + +### verifyUpgradePackage + +verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string): Promise\ + +Verifies the update package. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| upgradeFile | [UpgradeFile](#upgradefile) | Yes | Update file.| +| certsFile | string | Yes | Path of the certificate file.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +``` +var upgradeFile = { + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +} +localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => { + console.log(`verifyUpgradePackage success`); +}).catch(err => { + console.log(`verifyUpgradePackage error ${JSON.stringify(err)}`); +}); +``` + +### applyNewVersion +applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>, callback: AsyncCallback\): void + +Installs the update package. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| upgradeFile | Array<[UpgradeFile](#upgradefile)> | Yes | Update file.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Example** + +``` +var upgradeFiles = [{ + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +}] + +localUpdater.applyNewVersion(upgradeFiles, (err) => { + console.log(`applyNewVersion error ${JSON.stringify(err)}`); +}); +``` + +### applyNewVersion + +applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>): Promise\ + +Installs the update package. This API uses a promise to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Required permission**: ohos.permission.UPDATE_SYSTEM (a system permission) + +**Return value** + +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +``` +var upgradeFiles = [{ + fileType: update.ComponentType.OTA, // OTA package + filePath: "path" // Path of the local update package +}] +localUpdater.applyNewVersion(upgradeFiles).then(() => { + console.log(`applyNewVersion success`); +}).catch(err => { + console.log(`applyNewVersion error ${JSON.stringify(err)}`); +}); +``` + +### on +on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): void + +Enables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +function onTaskUpdate(eventInfo) { + console.log(`on eventInfo id `, eventInfo.eventId); +} + +localUpdater.on(eventClassifyInfo, onTaskUpdate); +``` + +### off +off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): void + +Disables listening for update events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Update.UpdateService + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| + +**Example** + +``` +var eventClassifyInfo = { + eventClassify: update.EventClassify.TASK, // Listening for update events + extraInfo: "" +} + +function onTaskUpdate(eventInfo) { + console.log(`on eventInfo id `, eventInfo.eventId); +} + +localUpdater.off(eventClassifyInfo, onTaskUpdate); +``` + +## UpgradeInfo + +Represents update information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| upgradeApp | string | Yes | Application package name. | +| businessType | [BusinessType](#businesstype) | Yes | Update service type. | + +## BusinessType + +Enumerates update service types. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| vendor | [BusinessVendor](#businessvendor) | Yes | Application vendor. | +| subType | [BusinessSubType](#businesssubtype) | Yes | Update service sub-type. | + +## CheckResult + +Represents the package check result. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| isExistNewVersion | bool | Yes | Whether a new version is available. | +| newVersionInfo | [NewVersionInfo](#newversioninfo) | No | Information about the new version. | + +## NewVersionInfo + +Represents information about the new version. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | +| versionComponents | Array\<[VersionComponent](#versioncomponent)> | Yes | Version components. | + +## VersionDigestInfo + +Represents version digest information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| versionDigest | string | Yes | Version digest information. | + +## VersionComponent + +Represents a version component. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| componentId | number | Yes | Component ID. | +| componentType | [ComponentType](#componentyype) | Yes | Component type. | +| upgradeAction | [UpgradeAction](#upgradeaction) | Yes | Update mode. | +| displayVersion | string | Yes | Display version number. | +| innerVersion | string | Yes | Internal version number. | +| size | number | Yes | Update package size. | +| effectiveMode | [EffectiveMode](#effectivemode) | Yes | Effective mode. | +| descriptionInfo | [DescriptionInfo](#descriptioninfo) | Yes | Information about the version description file. | + +## DescriptionOptions + +Represents options of the description file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| format | [DescriptionFormat](#descriptionformat) | Yes | Format of the description file. | +| language | string | Yes | Language of the description file. | + +## ComponentDescription + +Represents a component description file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| componentId | string | Yes | Component ID. | +| descriptionInfo | [DescriptionInfo](#descriptioninfo) | Yes | Information about the description file. | + +## DescriptionInfo + +Represents information about the version description file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| descriptionType | [DescriptionType](#descriptiontype) | Yes | Type of the description file. | +| content | string | Yes | Content of the description file. | + +## CurrentVersionInfo + +Represents information about the current version. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| osVersion | string | Yes | System version number. | +| deviceName | string | Yes | Device name. | +| versionComponents | Array\<[VersionComponent](#vesioncomponent)> | No | Version components. | + +## DownloadOptions + +Represents download options. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| allowNetwork | [NetType](#nettype) | Yes | Network type. | +| order | [Order](#order) | Yes | Update command. | + +## ResumeDownloadOptions + +Represents options for resuming download. + +**System capability**: SystemCapability.Update.UpdateService + +| Parameter | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| allowNetwork | [NetType](#nettype) | Yes | Network type. | + +## PauseDownloadOptions + +Represents options for pausing download. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| isAllowAutoResume | bool | Yes | Whether to allow automatic resuming of download. | + +## UpgradeOptions + +Represents update options. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| order | [Order](#order) | Yes | Update command. | + +## ClearOptions + +Represents options for clearing errors. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| status | [UpgradeStatus](#upgradestatus) | Yes | Error status. | + +## UpgradePolicy + +Represents an update policy. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| downloadStrategy | bool | Yes | Automatic download policy. | +| autoUpgradeStrategy | bool | Yes | Automatic update policy. | +| autoUpgradePeriods | Array\<[UpgradePeriod](#upgradeperiod)> | Yes | Automatic update period.| + +## UpgradePeriod + +Represents a period for automatic update. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| start | number | Yes | Start time. | +| end | number | Yes | End time. | + +## TaskInfo + +Represents task information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| existTask | bool | Yes | Whether a task exists. | +| taskBody | [TaskBody](#taskinfo) | Yes | Task data. | + +## EventInfo + +Represents event information. + +**System capability**: SystemCapability.Update.UpdateService + +| Parameter | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| eventId | [EventId](#eventid) | Yes | Event ID. | +| taskBody | [TaskBody](#taskinfo) | Yes | Task data. | + +## TaskBody + +Represents task data. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | +| status | [UpgradeStatus](#upgradestatus) | Yes | Update status. | +| subStatus | number | No | Sub-status. | +| progress | number | Yes | Progress. | +| installMode | number | Yes | Installation mode. | +| errorMessages | Array\<[ErrorMessage](#errormessage)> | No | Error message. | +| versionComponents | Array\<[VersionComponent](#versioncomponent)> | Yes | Version components. | + +## ErrorMessage + +Represents an error message. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| errorCode | number | Yes | Error code. | +| errorMessage | string | Yes | Error description. | + +## EventClassifyInfo + +Represents event type information. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| eventClassify | [EventClassify](#eventclassify) | Yes | Event type. | +| extraInfo | string | Yes | Additional information. | + +## UpgradeFile + +Represents an update file. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Type | Mandatory | Description | +| ------------------- | --------------------------- | ---- | ------- | +| fileType | [ComponentType](#componenttype) | Yes | File type. | +| filePath | string | Yes | File path. | + +## UpgradeTaskCallback + +### (eventInfo: [EventInfo](#eventinfo)): void + +Event callback. + +**System capability**: SystemCapability.Update.UpdateService + +| Parameter | Type | Mandatory | Description | +| --------------- | ---------------------------------------- | ---- | ---- | +| eventInfo | [EventInfo](#eventinfo) | Yes | Event information.| + +## BusinessVendor + +Device vendor. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| PUBLIC | "public" | Open source. | + +## BusinessSubType + +Represents an update type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| FIRMWARE | 1 | Firmware. | + +## ComponentType + +Represents a component type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| OTA | 1 | Firmware. | + +## UpgradeAction + +Represents an update mode. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| UPGRADE | "upgrade" | Differential package. | +| RECOVERY | "recovery" | Recovery package. | + +## EffectiveMode + +Represents an effective mode. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| COLD | 1 | Cold update. | +| LIVE | 2 | Live update. | +| LIVE_AND_COLD | 3 | Hybrid live and cold update. | + +## DescriptionType + +Represents a description file type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| CONTENT | 0 | Content. | +| URI | 1 | Link. | + +## DescriptionFormat + +Represents a description file format. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| STANDARD | 0 | Standard format. | +| SIMPLIFIED | 1 | Simple format. | + +## NetType + +Enumerates network types. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| CELLULAR | 1 | Data network. | +| METERED_WIFI | 2 | Wi-Fi hotspot. | +| NOT_METERED_WIFI | 4 | Non Wi-Fi hotspot. | +| WIFI | 6 | WIFI | +| CELLULAR_AND_WIFI | 7 | Data network and Wi-Fi. | + +## Order + +Represents an update command. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| DOWNLOAD | 1 | Download. | +| INSTALL | 2 | Install. | +| DOWNLOAD_AND_INSTALL | 3 | Download and install. | +| APPLY | 4 | Apply. | +| INSTALL_AND_APPLY | 6 | Install and apply. | + +## UpgradeStatus + +Enumerates update states. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| WAITING_DOWNLOAD | 20 | Waiting for download. | +| DOWNLOADING | 21 | Downloading. | +| DOWNLOAD_PAUSED | 22 | Download paused. | +| DOWNLOAD_FAIL | 23 | Download failed. | +| WAITING_INSTALL | 30 | Waiting for installation. | +| UPDATING | 31 | Updating. | +| WAITING_APPLY | 40 | Waiting for applying the update. | +| APPLYING | 21 | Applying the update. | +| UPGRADE_SUCCESS | 50 | Update succeeded. | +| UPGRADE_FAIL | 51 | Update failed. | + +## EventClassify + +Represents an event type. + +**System capability**: SystemCapability.Update.UpdateService + +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| TASK | 0x01000000 | Task event. | + +## EventId -Defines the version description information. +Enumerates event IDs. **System capability**: SystemCapability.Update.UpdateService -| Name | Type | Mandatory | Description | -| ------------- | ------ | --------- | ------------------------------ | -| descriptionId | string | Yes | Version ID information. | -| content | string | Yes | Version changelog information. | +| Name | Default Value | Description | +| ------------------- | ---- | -------- | +| EVENT_TASK_BASE | 0x01000000 | Indicates a task event. | +| EVENT_TASK_RECEIVE | 0x01000001 | Indicates that a task is received. | +| EVENT_TASK_CANCEL | 0x01000010 | Indicates that a task is cancelled. | +| EVENT_DOWNLOAD_WAIT | 0x01000011 | Indicates the state of waiting for the download. | +| EVENT_DOWNLOAD_START | 0x01000100 | Indicates that the download starts. | +| EVENT_DOWNLOAD_UPDATE | 0x01000101 | Indicates the download progress update. | +| EVENT_DOWNLOAD_PAUSE | 0x01000110 | Indicates that the download is paused. | +| EVENT_DOWNLOAD_RESUME | 0x01000111 | Indicates that the download is resumed. | +| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | Indicates that the download succeeded. | +| EVENT_DOWNLOAD_FAIL | 0x01001001 | Indicates that the download failed. | +| EVENT_UPGRADE_WAIT | 0x01001010 | Indicates the state of waiting for the update. | +| EVENT_UPGRADE_START | 0x01001011 | Indicates that the update starts. | +| EVENT_UPGRADE_UPDATE | 0x01001100 | Indicates that the update is in progress. | +| EVENT_APPLY_WAIT | 0x01001101 | Indicates the state of waiting for applying the update. | +| EVENT_APPLY_START | 0x01001110 | Indicates the state of applying the update. | +| EVENT_UPGRADE_SUCCESS | 0x01001111 | Indicates that the update succeeded. | +| EVENT_UPGRADE_FAIL | 0x01010000 | Indicates that the update failed. | diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 2871e53f5e753bf52109e2d9c2e95b2c1d4c8808..55694ec1cb024a25affa93feca40b2a73ef38234 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -1,6 +1,7 @@ # URL String Parsing -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -25,7 +26,7 @@ Creates a **URLSearchParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object | +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| **Example** @@ -48,10 +49,10 @@ Appends a key-value pair into the query string. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key of the key-value pair to append. | - | value | string | Yes | Value of the key-value pair to append. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key of the key-value pair to append.| +| value | string | Yes| Value of the key-value pair to append.| **Example** @@ -72,9 +73,9 @@ Deletes key-value pairs of the specified key. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key of the key-value pairs to delete. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key of the key-value pairs to delete.| **Example** @@ -95,15 +96,15 @@ Obtains all the key-value pairs based on the specified key. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key specified to obtain all key-value pairs. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key specified to obtain all key-value pairs.| **Return value** - | Type | Description | - | -------- | -------- | - | string[] | All key-value pairs matching the specified key. | +| Type| Description| +| -------- | -------- | +| string[] | All key-value pairs matching the specified key.| **Example** @@ -125,9 +126,9 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<[string, string]> | ES6 iterator. | +| Type| Description| +| -------- | -------- | +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -149,18 +150,18 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callbackfn | function | Yes | Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance. | - | thisArg | Object | No | Value to use when the callback is invoked. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| +| thisArg | Object | No| Value to use when the callback is invoked.| **Table 1** callbackfn parameter description - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | value | string | Yes | Value that is currently traversed. | - | key | string | Yes | Key that is currently traversed. | - | searchParams | Object | Yes | Instance that invokes the **forEach** method. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string | Yes| Value that is currently traversed.| +| key | string | Yes| Key that is currently traversed.| +| searchParams | Object | Yes| Instance that invokes the **forEach** method.| **Example** @@ -182,16 +183,16 @@ Obtains the value of the first key-value pair based on the specified key. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key specified to obtain the value. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key specified to obtain the value.| **Return value** - | Type | Description | - | -------- | -------- | - | string | Returns the value of the first key-value pair if obtained. | - | null | Returns null if no value is obtained. | +| Type| Description| +| -------- | -------- | +| string | Returns the value of the first key-value pair if obtained.| +| null | Returns null if no value is obtained.| **Example** @@ -212,15 +213,15 @@ Checks whether a key has a value. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key specified to search for its value. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key specified to search for its value.| **Return value** - | Type | Description | - | -------- | -------- | - | boolean | Returns **true** if the value exists; returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the value exists; returns **false** otherwise.| **Example** @@ -241,10 +242,10 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | name | string | Yes | Key of the value to set. | - | value | string | Yes | Value to set. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Key of the value to set.| +| value | string | Yes| Value to set.| **Example** @@ -282,9 +283,9 @@ Obtains an ES6 iterator that contains the keys of all the key-value pairs. **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<string> | ES6 iterator that contains the keys of all the key-value pairs. | +| Type| Description| +| -------- | -------- | +| IterableIterator<string> | ES6 iterator that contains the keys of all the key-value pairs.| **Example** @@ -306,9 +307,9 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs. **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<string> | ES6 iterator that contains the values of all the key-value pairs. | +| Type| Description| +| -------- | -------- | +| IterableIterator<string> | ES6 iterator that contains the values of all the key-value pairs.| **Example** @@ -330,9 +331,9 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th **Return value** - | Type | Description | - | -------- | -------- | - | IterableIterator<[string, string]> | ES6 iterator. | +| Type| Description| +| -------- | -------- | +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -354,9 +355,9 @@ Obtains search parameters that are serialized as a string and, if necessary, per **Return value** - | Type | Description | - | -------- | -------- | - | string | String of serialized search parameters, which is percent-encoded if necessary. | +| Type| Description| +| -------- | -------- | +| string | String of serialized search parameters, which is percent-encoded if necessary.| **Example** @@ -400,10 +401,10 @@ Creates a URL. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | url | string | Yes | Input object. | - | base | string \ | URL | No | Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Input object.| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| **Example** @@ -433,9 +434,9 @@ Converts the parsed URL into a string. **Return value** - | Type | Description | - | -------- | -------- | - | string | Website address in a serialized string. | +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| **Example** @@ -455,12 +456,12 @@ Converts the parsed URL into a JSON string. **Return value** - | Type | Description | - | -------- | -------- | - | string | Website address in a serialized string. | +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| **Example** ```js const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toJSON() -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 83ed07f3f720da23ff5c006938d15bd2ea660751..71b0490ea8c610dc0169222042ec7770c19d0a83 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,6 +1,9 @@ # USB -> **NOTE**
+This module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. + +> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-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-util.md b/en/application-dev/reference/apis/js-apis-util.md index abf2b4a31a27cefcf9cf1e653a8e2e4249b5a6fb..afa1c20bcd4eace98512772fb3cd7160d23a5b92 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -61,7 +61,7 @@ Obtains detailed information about a system error code. **Example** ```js - var errnum = 10; // 10 is the system error code. + var errnum = 10; // 10 is a system error code. var result = util.getErrorString(errnum); console.log("result = " + result); ``` @@ -104,14 +104,16 @@ Calls back an asynchronous function. In the callback, the first parameter indica promiseWrapper(original: (err: Object, value: Object) => void): Object -> **Introduce**
-> Starting from API version 9, it is recommended to use [util.promisewrapper9 +] (\utilpromisewrapper9) instead. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use **[util.promisify9+](#utilpromisify9)** instead. Processes an asynchronous function and returns a promise version. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | original | Function | Yes| Asynchronous function.| @@ -132,11 +134,11 @@ Processes an asynchronous function and returns a promise version. }) ``` -## util.promiseWrapper9+ +## util.promisify9+ -promiseWrapper(original: (err: Object, value: Object) => void): Function +promisify(original: (err: Object, value: Object) => void): Function -Processes an asynchronous function and returns a promise function. +Processes an asynchronous function and returns a promise. **System capability**: SystemCapability.Utils.Lang @@ -148,7 +150,7 @@ Processes an asynchronous function and returns a promise function. **Return value** | Type| Description| | -------- | -------- | -| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise version.| +| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| **Example** ```js @@ -159,13 +161,12 @@ Processes an asynchronous function and returns a promise function. return str1 } } - let newPromiseObj = util.promiseWrapper(aysnFun); + let newPromiseObj = util.promisify(aysnFun); newPromiseObj({ err: "type error" }, {value:'HelloWorld'}).then(res => { console.log(res); }) ``` - ## TextDecoder ### Attributes @@ -217,7 +218,7 @@ Decodes the input content. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| input | Unit8Array | Yes| Uint8Array to decode.| +| input | Uint8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| **Table 2** options @@ -982,7 +983,6 @@ Performs subsequent operations after a value is removed. **Example** ```js var arr = []; - var arr = []; class ChildLruBuffer extends util.LruBuffer { constructor() @@ -1913,8 +1913,7 @@ Checks whether the input value is of the **native external** type. **Example** ```js var that = new util.types(); - const data = util.createExternalType(); - var result = that.isExternal(data); + var result = that.isExternal(true); ``` 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/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index c6a89b78715f1a819cd04a11f67a0609a98aa4f9..5421d20c5fc129c726f31deaae6610d2bdc28d2e 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,5 +1,7 @@ # WantAgent +The **WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. + > **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. @@ -418,6 +420,8 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -490,6 +494,8 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -704,7 +710,7 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur | Name | Readable| Writable| Type | Mandatory| Description | | ----------- | --- | ---- | ----------------------------- | ---- | ------------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object to trigger. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | triggerInfo | Yes | No | TriggerInfo | Yes | **TriggerInfo** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1052,7 +1058,7 @@ WantAgent.getOperationType(wantAgent).then((OperationType) => { | Name | Readable| Writable| Type | Mandatory| Description | | -------------- | --- | ---- | ------------------------------- | ---- | ---------------------- | | wants | Yes | Yes | Array\ | Yes | Array of all **Want** objects. | -| operationType | Yes | Yes | wantAgent.OperationType | Yes | Action type. | +| operationType | Yes | Yes | wantAgent.OperationType | Yes | Operation type. | | requestCode | Yes | Yes | number | Yes | Request code defined by the user.| | wantAgentFlags | Yes | Yes | Array | No | Array of flags for using the **WantAgent** object. | | extraInfo | Yes | Yes | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index e71562765f7b0a4330cfce26a8c57f835f8ed055..95738321bc5717e97657191b416e3ceca220d75d 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -1,11 +1,13 @@ -# webgl - -> **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. +# WebGL +The **WebGL** module provides the graphics drawing capability, such as processing the graphics position and color. This module provides WebGL APIs that correspond to the OpenGL ES 2.0 feature set. For more information, see [WebGL™](https://www.khronos.org/registry/webgl/specs/latest/1.0/). +> **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. + ## Invoking Method @@ -37,7 +39,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); **System capability**: SystemCapability.Graphic.Graphic2D.WebGL - **Table 1** Type +**Table 1** Type | Name| Type| | -------- | -------- | @@ -61,11 +63,11 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | WebGLPowerPreference | string | -## Interface +## APIs **System capability**: SystemCapability.Graphic.Graphic2D.WebGL - **Table 2** Interface +**Table 2** APIs | Name| | -------- | @@ -566,7 +568,7 @@ WebGLRenderingContextOverloads | bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | | compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | | compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void; | | texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | | texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | | texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index 386d1c53dad0df97a9fd0fbbeac33aec45492d5c..0052505dfb6d127a7081b35b01f3b302b74b2deb 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -1,11 +1,13 @@ -# webgl2 - -> **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. +# WebGL2 +The **WebGL2** module supports graphics drawing, such as processing the graphics position and color. WebGL2 provides enhanced capabilities in the rendering pipeline and shader language than WebGL. This module provides WebGL APIs that correspond to the OpenGL ES 3.0 feature set. For more information, see [WebGL™](https://www.khronos.org/registry/webgl/specs/latest/2.0/). +> **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. + ## Invoking Method @@ -37,7 +39,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); **System capability**: SystemCapability.Graphic.Graphic2D.WebGL2 - **Table 1** Type +**Table 1** Type | Name| Type| | -------- | -------- | @@ -47,11 +49,11 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | Uint32List | array | -## Interface +## APIs **System capability**: SystemCapability.Graphic.Graphic2D.WebGL2 - **Table 2** Interface +**Table 2** APIs | Name| | -------- | @@ -71,409 +73,409 @@ WebGL2RenderingContextBase ### Attributes - | Name| Type| Mandatory| +| Name| Type| Mandatory| | -------- | -------- | -------- | -| READ_BUFFER | GLenum | Yes| -| UNPACK_ROW_LENGTH | GLenum | Yes| -| UNPACK_SKIP_ROWS | GLenum | Yes| -| UNPACK_SKIP_PIXELS | GLenum | Yes| -| PACK_ROW_LENGTH | GLenum | Yes| -| PACK_SKIP_ROWS | GLenum | Yes| -| PACK_SKIP_PIXELS | GLenum | Yes| -| COLOR | GLenum | Yes| -| DEPTH | GLenum | Yes| -| STENCIL | GLenum | Yes| -| RED | GLenum | Yes| -| RGB8 | GLenum | Yes| -| RGBA8 | GLenum | Yes| -| RGB10_A2 | GLenum | Yes| -| TEXTURE_BINDING_3D | GLenum | Yes| -| UNPACK_SKIP_IMAGES | GLenum | Yes| -| UNPACK_IMAGE_HEIGHT | GLenum | Yes| -| TEXTURE_3D | GLenum | Yes| -| TEXTURE_WRAP_R | GLenum | Yes| -| MAX_3D_TEXTURE_SIZE | GLenum | Yes| -| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| -| MAX_ELEMENTS_VERTICES | GLenum | Yes| -| MAX_ELEMENTS_INDICES | GLenum | Yes| -| TEXTURE_MIN_LOD | GLenum | Yes| -| TEXTURE_MAX_LOD | GLenum | Yes| -| TEXTURE_BASE_LEVEL | GLenum | Yes| -| TEXTURE_MAX_LEVEL | GLenum | Yes| -| MIN | GLenum | Yes| -| MAX | GLenum | Yes| -| DEPTH_COMPONENT24 | GLenum | Yes| -| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| -| TEXTURE_COMPARE_MODE | GLenum | Yes| -| TEXTURE_COMPARE_FUNC | GLenum | Yes| -| CURRENT_QUERY | GLenum | Yes| -| QUERY_RESULT | GLenum | Yes| -| QUERY_RESULT_AVAILABLE | GLenum | Yes| -| STREAM_READ | GLenum | Yes| -| STREAM_COPY | GLenum | Yes| -| STATIC_READ | GLenum | Yes| -| STATIC_COPY | GLenum | Yes| -| DYNAMIC_READ | GLenum | Yes| -| DYNAMIC_COPY | GLenum | Yes| -| MAX_DRAW_BUFFERS | GLenum | Yes| -| DRAW_BUFFER0 | GLenum | Yes| -| DRAW_BUFFER1 | GLenum | Yes| -| DRAW_BUFFER2 | GLenum | Yes| -| DRAW_BUFFER3 | GLenum | Yes| -| DRAW_BUFFER4 | GLenum | Yes| -| DRAW_BUFFER5 | GLenum | Yes| -| DRAW_BUFFER6 | GLenum | Yes| -| DRAW_BUFFER7 | GLenum | Yes| -| DRAW_BUFFER8 | GLenum | Yes| -| DRAW_BUFFER9 | GLenum | Yes| -| DRAW_BUFFER10 | GLenum | Yes| -| DRAW_BUFFER11 | GLenum | Yes| -| DRAW_BUFFER12 | GLenum | Yes| -| DRAW_BUFFER13 | GLenum | Yes| -| DRAW_BUFFER14 | GLenum | Yes| -| DRAW_BUFFER15 | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| SAMPLER_3D | GLenum | Yes| -| SAMPLER_2D_SHADOW | GLenum | Yes| -| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| -| PIXEL_PACK_BUFFER | GLenum | Yes| -| PIXEL_UNPACK_BUFFER | GLenum | Yes| -| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| -| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| -| FLOAT_MAT2x3 | GLenum | Yes| -| FLOAT_MAT2x4 | GLenum | Yes| -| FLOAT_MAT3x2 | GLenum | Yes| -| FLOAT_MAT3x4 | GLenum | Yes| -| FLOAT_MAT4x2 | GLenum | Yes| -| FLOAT_MAT4x3 | GLenum | Yes| -| SRGB | GLenum | Yes| -| SRGB8 | GLenum | Yes| -| SRGB8_ALPHA8 | GLenum | Yes| -| COMPARE_REF_TO_TEXTURE | GLenum | Yes| -| RGBA32F | GLenum | Yes| -| RGB32F | GLenum | Yes| -| RGBA16F | GLenum | Yes| -| RGB16F | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| -| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| -| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_VARYING_COMPONENTS | GLenum | Yes| -| TEXTURE_2D_ARRAY | GLenum | Yes| -| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| -| R11F_G11F_B10F | GLenum | Yes| -| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| -| RGB9_E5 | GLenum | Yes| -| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| -| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| -| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| -| RASTERIZER_DISCARD | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| -| INTERLEAVED_ATTRIBS | GLenum | Yes| -| SEPARATE_ATTRIBS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| -| RGBA32UI | GLenum | Yes| -| RGB32UI | GLenum | Yes| -| RGBA16UI | GLenum | Yes| -| RGB16UI | GLenum | Yes| -| RGBA8UI | GLenum | Yes| -| RGB8UI | GLenum | Yes| -| RGBA32I | GLenum | Yes| -| RGB32I | GLenum | Yes| -| RGBA16I | GLenum | Yes| -| RGB16I | GLenum | Yes| -| RGBA8I | GLenum | Yes| -| RGB8I | GLenum | Yes| -| RED_INTEGER | GLenum | Yes| -| RGB_INTEGER | GLenum | Yes| -| RGBA_INTEGER | GLenum | Yes| -| SAMPLER_2D_ARRAY | GLenum | Yes| -| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| -| SAMPLER_CUBE_SHADOW | GLenum | Yes| -| UNSIGNED_INT_VEC2 | GLenum | Yes| -| UNSIGNED_INT_VEC3 | GLenum | Yes| -| UNSIGNED_INT_VEC4 | GLenum | Yes| -| INT_SAMPLER_2D | GLenum | Yes| -| INT_SAMPLER_3D | GLenum | Yes| -| INT_SAMPLER_CUBE | GLenum | Yes| -| INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| DEPTH_COMPONENT32F | GLenum | Yes| -| DEPTH32F_STENCIL8 | GLenum | Yes| -| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| -| FRAMEBUFFER_DEFAULT | GLenum | Yes| -| UNSIGNED_INT_24_8 | GLenum | Yes| -| DEPTH24_STENCIL8 | GLenum | Yes| -| UNSIGNED_NORMALIZED | GLenum | Yes| -| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| -| READ_FRAMEBUFFER | GLenum | Yes| -| DRAW_FRAMEBUFFER | GLenum | Yes| -| READ_FRAMEBUFFER_BINDING | GLenum | Yes| -| RENDERBUFFER_SAMPLES | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| -| MAX_COLOR_ATTACHMENTS | GLenum | Yes| -| COLOR_ATTACHMENT1 | GLenum | Yes| -| COLOR_ATTACHMENT2 | GLenum | Yes| -| COLOR_ATTACHMENT3 | GLenum | Yes| -| COLOR_ATTACHMENT4 | GLenum | Yes| -| COLOR_ATTACHMENT5 | GLenum | Yes| -| COLOR_ATTACHMENT6 | GLenum | Yes| -| COLOR_ATTACHMENT7 | GLenum | Yes| -| COLOR_ATTACHMENT8 | GLenum | Yes| -| COLOR_ATTACHMENT9 | GLenum | Yes| -| COLOR_ATTACHMENT10 | GLenum | Yes| -| COLOR_ATTACHMENT11 | GLenum | Yes| -| COLOR_ATTACHMENT12 | GLenum | Yes| -| COLOR_ATTACHMENT13 | GLenum | Yes| -| COLOR_ATTACHMENT14 | GLenum | Yes| -| COLOR_ATTACHMENT15 | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| -| MAX_SAMPLES | GLenum | Yes| -| HALF_FLOAT | GLenum | Yes| -| RG | GLenum | Yes| -| RG_INTEGER | GLenum | Yes| -| R8 | GLenum | Yes| -| RG8 | GLenum | Yes| -| R16F | GLenum | Yes| -| R32F | GLenum | Yes| -| RG16F | GLenum | Yes| -| RG32F | GLenum | Yes| -| R8I | GLenum | Yes| -| R8UI | GLenum | Yes| -| R16I | GLenum | Yes| -| R16UI | GLenum | Yes| -| R32I | GLenum | Yes| -| R32UI | GLenum | Yes| -| RG8I | GLenum | Yes| -| RG8UI | GLenum | Yes| -| RG16I | GLenum | Yes| -| RG16UI | GLenum | Yes| -| RG32I | GLenum | Yes| -| RG32UI | GLenum | Yes| -| VERTEX_ARRAY_BINDING | GLenum | Yes| -| R8_SNORM | GLenum | Yes| -| RG8_SNORM | GLenum | Yes| -| RGB8_SNORM | GLenum | Yes| -| SIGNED_NORMALIZED | GLenum | Yes| -| COPY_READ_BUFFER | GLenum | Yes| -| COPY_WRITE_BUFFER | GLenum | Yes| -| COPY_READ_BUFFER_BINDING | GLenum | Yes| -| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER | GLenum | Yes| -| UNIFORM_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER_START | GLenum | Yes| -| UNIFORM_BUFFER_SIZE | GLenum | Yes| -| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| -| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| -| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| -| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| -| UNIFORM_TYPE | GLenum | Yes| -| UNIFORM_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_INDEX | GLenum | Yes| -| UNIFORM_OFFSET | GLenum | Yes| -| UNIFORM_ARRAY_STRIDE | GLenum | Yes| -| UNIFORM_MATRIX_STRIDE | GLenum | Yes| -| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| -| UNIFORM_BLOCK_BINDING | GLenum | Yes| -| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| -| INVALID_INDEX | GLenum | Yes| -| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| -| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| -| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| -| OBJECT_TYPE | GLenum | Yes| -| SYNC_CONDITION | GLenum | Yes| -| SYNC_STATUS | GLenum | Yes| -| SYNC_FLAGS | GLenum | Yes| -| SYNC_FENCE | GLenum | Yes| -| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| -| UNSIGNALED | GLenum | Yes| -| SIGNALED | GLenum | Yes| -| ALREADY_SIGNALED | GLenum | Yes| -| TIMEOUT_EXPIRED | GLenum | Yes| -| CONDITION_SATISFIED | GLenum | Yes| -| WAIT_FAILED | GLenum | Yes| -| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| -| ANY_SAMPLES_PASSED | GLenum | Yes| -| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| -| SAMPLER_BINDING | GLenum | Yes| -| RGB10_A2UI | GLenum | Yes| -| INT_2_10_10_10_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK | GLenum | Yes| -| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| -| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| -| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| -| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| -| MAX_ELEMENT_INDEX | GLenum | Yes| -| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| -| TIMEOUT_IGNORED | GLint64 | Yes| -| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| +| READ_BUFFER | GLenum | Yes| +| UNPACK_ROW_LENGTH | GLenum | Yes| +| UNPACK_SKIP_ROWS | GLenum | Yes| +| UNPACK_SKIP_PIXELS | GLenum | Yes| +| PACK_ROW_LENGTH | GLenum | Yes| +| PACK_SKIP_ROWS | GLenum | Yes| +| PACK_SKIP_PIXELS | GLenum | Yes| +| COLOR | GLenum | Yes| +| DEPTH | GLenum | Yes| +| STENCIL | GLenum | Yes| +| RED | GLenum | Yes| +| RGB8 | GLenum | Yes| +| RGBA8 | GLenum | Yes| +| RGB10_A2 | GLenum | Yes| +| TEXTURE_BINDING_3D | GLenum | Yes| +| UNPACK_SKIP_IMAGES | GLenum | Yes| +| UNPACK_IMAGE_HEIGHT | GLenum | Yes| +| TEXTURE_3D | GLenum | Yes| +| TEXTURE_WRAP_R | GLenum | Yes| +| MAX_3D_TEXTURE_SIZE | GLenum | Yes| +| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| +| MAX_ELEMENTS_VERTICES | GLenum | Yes| +| MAX_ELEMENTS_INDICES | GLenum | Yes| +| TEXTURE_MIN_LOD | GLenum | Yes| +| TEXTURE_MAX_LOD | GLenum | Yes| +| TEXTURE_BASE_LEVEL | GLenum | Yes| +| TEXTURE_MAX_LEVEL | GLenum | Yes| +| MIN | GLenum | Yes| +| MAX | GLenum | Yes| +| DEPTH_COMPONENT24 | GLenum | Yes| +| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| +| TEXTURE_COMPARE_MODE | GLenum | Yes| +| TEXTURE_COMPARE_FUNC | GLenum | Yes| +| CURRENT_QUERY | GLenum | Yes| +| QUERY_RESULT | GLenum | Yes| +| QUERY_RESULT_AVAILABLE | GLenum | Yes| +| STREAM_READ | GLenum | Yes| +| STREAM_COPY | GLenum | Yes| +| STATIC_READ | GLenum | Yes| +| STATIC_COPY | GLenum | Yes| +| DYNAMIC_READ | GLenum | Yes| +| DYNAMIC_COPY | GLenum | Yes| +| MAX_DRAW_BUFFERS | GLenum | Yes| +| DRAW_BUFFER0 | GLenum | Yes| +| DRAW_BUFFER1 | GLenum | Yes| +| DRAW_BUFFER2 | GLenum | Yes| +| DRAW_BUFFER3 | GLenum | Yes| +| DRAW_BUFFER4 | GLenum | Yes| +| DRAW_BUFFER5 | GLenum | Yes| +| DRAW_BUFFER6 | GLenum | Yes| +| DRAW_BUFFER7 | GLenum | Yes| +| DRAW_BUFFER8 | GLenum | Yes| +| DRAW_BUFFER9 | GLenum | Yes| +| DRAW_BUFFER10 | GLenum | Yes| +| DRAW_BUFFER11 | GLenum | Yes| +| DRAW_BUFFER12 | GLenum | Yes| +| DRAW_BUFFER13 | GLenum | Yes| +| DRAW_BUFFER14 | GLenum | Yes| +| DRAW_BUFFER15 | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| SAMPLER_3D | GLenum | Yes| +| SAMPLER_2D_SHADOW | GLenum | Yes| +| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| +| PIXEL_PACK_BUFFER | GLenum | Yes| +| PIXEL_UNPACK_BUFFER | GLenum | Yes| +| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| +| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| +| FLOAT_MAT2x3 | GLenum | Yes| +| FLOAT_MAT2x4 | GLenum | Yes| +| FLOAT_MAT3x2 | GLenum | Yes| +| FLOAT_MAT3x4 | GLenum | Yes| +| FLOAT_MAT4x2 | GLenum | Yes| +| FLOAT_MAT4x3 | GLenum | Yes| +| SRGB | GLenum | Yes| +| SRGB8 | GLenum | Yes| +| SRGB8_ALPHA8 | GLenum | Yes| +| COMPARE_REF_TO_TEXTURE | GLenum | Yes| +| RGBA32F | GLenum | Yes| +| RGB32F | GLenum | Yes| +| RGBA16F | GLenum | Yes| +| RGB16F | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| +| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| +| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_VARYING_COMPONENTS | GLenum | Yes| +| TEXTURE_2D_ARRAY | GLenum | Yes| +| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| +| R11F_G11F_B10F | GLenum | Yes| +| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| +| RGB9_E5 | GLenum | Yes| +| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| +| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| +| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| +| RASTERIZER_DISCARD | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| +| INTERLEAVED_ATTRIBS | GLenum | Yes| +| SEPARATE_ATTRIBS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| +| RGBA32UI | GLenum | Yes| +| RGB32UI | GLenum | Yes| +| RGBA16UI | GLenum | Yes| +| RGB16UI | GLenum | Yes| +| RGBA8UI | GLenum | Yes| +| RGB8UI | GLenum | Yes| +| RGBA32I | GLenum | Yes| +| RGB32I | GLenum | Yes| +| RGBA16I | GLenum | Yes| +| RGB16I | GLenum | Yes| +| RGBA8I | GLenum | Yes| +| RGB8I | GLenum | Yes| +| RED_INTEGER | GLenum | Yes| +| RGB_INTEGER | GLenum | Yes| +| RGBA_INTEGER | GLenum | Yes| +| SAMPLER_2D_ARRAY | GLenum | Yes| +| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| +| SAMPLER_CUBE_SHADOW | GLenum | Yes| +| UNSIGNED_INT_VEC2 | GLenum | Yes| +| UNSIGNED_INT_VEC3 | GLenum | Yes| +| UNSIGNED_INT_VEC4 | GLenum | Yes| +| INT_SAMPLER_2D | GLenum | Yes| +| INT_SAMPLER_3D | GLenum | Yes| +| INT_SAMPLER_CUBE | GLenum | Yes| +| INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| DEPTH_COMPONENT32F | GLenum | Yes| +| DEPTH32F_STENCIL8 | GLenum | Yes| +| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| +| FRAMEBUFFER_DEFAULT | GLenum | Yes| +| UNSIGNED_INT_24_8 | GLenum | Yes| +| DEPTH24_STENCIL8 | GLenum | Yes| +| UNSIGNED_NORMALIZED | GLenum | Yes| +| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| +| READ_FRAMEBUFFER | GLenum | Yes| +| DRAW_FRAMEBUFFER | GLenum | Yes| +| READ_FRAMEBUFFER_BINDING | GLenum | Yes| +| RENDERBUFFER_SAMPLES | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| +| MAX_COLOR_ATTACHMENTS | GLenum | Yes| +| COLOR_ATTACHMENT1 | GLenum | Yes| +| COLOR_ATTACHMENT2 | GLenum | Yes| +| COLOR_ATTACHMENT3 | GLenum | Yes| +| COLOR_ATTACHMENT4 | GLenum | Yes| +| COLOR_ATTACHMENT5 | GLenum | Yes| +| COLOR_ATTACHMENT6 | GLenum | Yes| +| COLOR_ATTACHMENT7 | GLenum | Yes| +| COLOR_ATTACHMENT8 | GLenum | Yes| +| COLOR_ATTACHMENT9 | GLenum | Yes| +| COLOR_ATTACHMENT10 | GLenum | Yes| +| COLOR_ATTACHMENT11 | GLenum | Yes| +| COLOR_ATTACHMENT12 | GLenum | Yes| +| COLOR_ATTACHMENT13 | GLenum | Yes| +| COLOR_ATTACHMENT14 | GLenum | Yes| +| COLOR_ATTACHMENT15 | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| +| MAX_SAMPLES | GLenum | Yes| +| HALF_FLOAT | GLenum | Yes| +| RG | GLenum | Yes| +| RG_INTEGER | GLenum | Yes| +| R8 | GLenum | Yes| +| RG8 | GLenum | Yes| +| R16F | GLenum | Yes| +| R32F | GLenum | Yes| +| RG16F | GLenum | Yes| +| RG32F | GLenum | Yes| +| R8I | GLenum | Yes| +| R8UI | GLenum | Yes| +| R16I | GLenum | Yes| +| R16UI | GLenum | Yes| +| R32I | GLenum | Yes| +| R32UI | GLenum | Yes| +| RG8I | GLenum | Yes| +| RG8UI | GLenum | Yes| +| RG16I | GLenum | Yes| +| RG16UI | GLenum | Yes| +| RG32I | GLenum | Yes| +| RG32UI | GLenum | Yes| +| VERTEX_ARRAY_BINDING | GLenum | Yes| +| R8_SNORM | GLenum | Yes| +| RG8_SNORM | GLenum | Yes| +| RGB8_SNORM | GLenum | Yes| +| SIGNED_NORMALIZED | GLenum | Yes| +| COPY_READ_BUFFER | GLenum | Yes| +| COPY_WRITE_BUFFER | GLenum | Yes| +| COPY_READ_BUFFER_BINDING | GLenum | Yes| +| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER | GLenum | Yes| +| UNIFORM_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER_START | GLenum | Yes| +| UNIFORM_BUFFER_SIZE | GLenum | Yes| +| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| +| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| +| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| +| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| +| UNIFORM_TYPE | GLenum | Yes| +| UNIFORM_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_INDEX | GLenum | Yes| +| UNIFORM_OFFSET | GLenum | Yes| +| UNIFORM_ARRAY_STRIDE | GLenum | Yes| +| UNIFORM_MATRIX_STRIDE | GLenum | Yes| +| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| +| UNIFORM_BLOCK_BINDING | GLenum | Yes| +| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| +| INVALID_INDEX | GLenum | Yes| +| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| +| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| +| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| +| OBJECT_TYPE | GLenum | Yes| +| SYNC_CONDITION | GLenum | Yes| +| SYNC_STATUS | GLenum | Yes| +| SYNC_FLAGS | GLenum | Yes| +| SYNC_FENCE | GLenum | Yes| +| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| +| UNSIGNALED | GLenum | Yes| +| SIGNALED | GLenum | Yes| +| ALREADY_SIGNALED | GLenum | Yes| +| TIMEOUT_EXPIRED | GLenum | Yes| +| CONDITION_SATISFIED | GLenum | Yes| +| WAIT_FAILED | GLenum | Yes| +| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| +| ANY_SAMPLES_PASSED | GLenum | Yes| +| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| +| SAMPLER_BINDING | GLenum | Yes| +| RGB10_A2UI | GLenum | Yes| +| INT_2_10_10_10_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK | GLenum | Yes| +| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| +| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| +| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| +| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| +| MAX_ELEMENT_INDEX | GLenum | Yes| +| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| +| TIMEOUT_IGNORED | GLint64 | Yes| +| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| ### Methods - | Method| Return Value Type| +| Method| Return Value Type| | -------- | -------- | -| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | -| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | -| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | -| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | -| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | -| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| readBuffer(src: GLenum) | void | -| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | -| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | -| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| getFragDataLocation(program: WebGLProgram, name: string) | GLint | -| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | -| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | -| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | -| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | -| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| vertexAttribI4iv(index: GLuint, values: Int32List) | void | -| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | -| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | -| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | -| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | -| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | -| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | -| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| drawBuffers(buffers: GLenum[]) | void | -| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | -| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | -| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | -| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | -| createQuery() | WebGLQuery \| null | -| deleteQuery(query: WebGLQuery \| null) | void | -| isQuery(query: WebGLQuery \| null) | GLboolean | -| beginQuery(target: GLenum, query: WebGLQuery) | void | -| endQuery(target: GLenum) | void | -| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | -| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | -| createSampler() | WebGLSampler \| null | -| deleteSampler(sampler: WebGLSampler \| null) | void | -| isSampler(sampler: WebGLSampler \| null) | GLboolean | -| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | -| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | -| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | -| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | -| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | -| isSync(sync: WebGLSync \| null) | GLboolean | -| deleteSync(sync: WebGLSync \| null) | void | -| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | -| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | -| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | -| createTransformFeedback() | WebGLTransformFeedback \| null | -| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | -| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | -| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | -| beginTransformFeedback(primitiveMode: GLenum) | void | -| endTransformFeedback() | void | -| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | -| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| pauseTransformFeedback() | void | -| resumeTransformFeedback() | void | -| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | -| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | -| getIndexedParameter(target: GLenum, index: GLuint) | any | -| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | -| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | -| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | -| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | -| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | -| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | -| createVertexArray() | WebGLVertexArrayObject \| null | -| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | -| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | -| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | +| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | +| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | +| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | +| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | +| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | +| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| readBuffer(src: GLenum) | void | +| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | +| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | +| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| getFragDataLocation(program: WebGLProgram, name: string) | GLint | +| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | +| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | +| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | +| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | +| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| vertexAttribI4iv(index: GLuint, values: Int32List) | void | +| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | +| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | +| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | +| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | +| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | +| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | +| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| drawBuffers(buffers: GLenum[]) | void | +| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | +| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | +| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | +| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | +| createQuery() | WebGLQuery \| null | +| deleteQuery(query: WebGLQuery \| null) | void | +| isQuery(query: WebGLQuery \| null) | GLboolean | +| beginQuery(target: GLenum, query: WebGLQuery) | void | +| endQuery(target: GLenum) | void | +| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | +| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | +| createSampler() | WebGLSampler \| null | +| deleteSampler(sampler: WebGLSampler \| null) | void | +| isSampler(sampler: WebGLSampler \| null) | GLboolean | +| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | +| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | +| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | +| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | +| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | +| isSync(sync: WebGLSync \| null) | GLboolean | +| deleteSync(sync: WebGLSync \| null) | void | +| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | +| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | +| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | +| createTransformFeedback() | WebGLTransformFeedback \| null | +| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | +| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | +| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | +| beginTransformFeedback(primitiveMode: GLenum) | void | +| endTransformFeedback() | void | +| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | +| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| pauseTransformFeedback() | void | +| resumeTransformFeedback() | void | +| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | +| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | +| getIndexedParameter(target: GLenum, index: GLuint) | any | +| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | +| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | +| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | +| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | +| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | +| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | +| createVertexArray() | WebGLVertexArrayObject \| null | +| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | +| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | +| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | ## WebGL2RenderingContextOverloads WebGL2RenderingContextOverloads - | Method| Return Value Type| +| Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | -| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | +| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index e89a471130d3fc8d50350fd33bee3bfbcaf8b6ef..21e43edc10b5e4fd5acf567ceabb822f26935ade 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -1,6 +1,7 @@ # XML Parsing and Generation -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/arkui-js/Readme-EN.md b/en/application-dev/reference/arkui-js/Readme-EN.md index 521ca33eff38eb7656529f0f32b85f4a7d37f35a..46e4b416c4bc0ee3389c493a540e2a7bb375bd3a 100644 --- a/en/application-dev/reference/arkui-js/Readme-EN.md +++ b/en/application-dev/reference/arkui-js/Readme-EN.md @@ -1,111 +1,105 @@ # JavaScript-based Web-like Development Paradigm -- Components - - Common - - [Universal Attributes](js-components-common-attributes.md) - - [Universal Styles](js-components-common-styles.md) - - [Universal Events](js-components-common-events.md) - - [Universal Methods](js-components-common-methods.md) - - [Animation Styles](js-components-common-animation.md) - - [Gradient Styles](js-components-common-gradient.md) - - [Transition Styles](js-components-common-transition.md) - - [Media Query](js-components-common-mediaquery.md) - - [Custom Font Styles](js-components-common-customizing-font.md) - - [Atomic Layout](js-components-common-atomic-layout.md) +- Universal Component Information + - [Universal Attributes](js-components-common-attributes.md) + - [Universal Styles](js-components-common-styles.md) + - [Universal Events](js-components-common-events.md) + - [Universal Methods](js-components-common-methods.md) + - [Animation Styles](js-components-common-animation.md) + - [Gradient Styles](js-components-common-gradient.md) + - [Transition Styles](js-components-common-transition.md) + - [Media Query](js-components-common-mediaquery.md) + - [Custom Font Styles](js-components-common-customizing-font.md) + - [Atomic Layout](js-components-common-atomic-layout.md) +- Container Components + - [badge](js-components-container-badge.md) + - [dialog](js-components-container-dialog.md) + - [div](js-components-container-div.md) + - [form](js-components-container-form.md) + - [list](js-components-container-list.md) + - [list-item](js-components-container-list-item.md) + - [list-item-group](js-components-container-list-item-group.md) + - [panel](js-components-container-panel.md) + - [popup](js-components-container-popup.md) + - [refresh](js-components-container-refresh.md) + - [stack](js-components-container-stack.md) + - [stepper](js-components-container-stepper.md) + - [stepper-item](js-components-container-stepper-item.md) + - [swiper](js-components-container-swiper.md) + - [tabs](js-components-container-tabs.md) + - [tab-bar](js-components-container-tab-bar.md) + - [tab-content](js-components-container-tab-content.md) +- Basic Components + - [button](js-components-basic-button.md) + - [chart](js-components-basic-chart.md) + - [divider](js-components-basic-divider.md) + - [image](js-components-basic-image.md) + - [image-animator](js-components-basic-image-animator.md) + - [input](js-components-basic-input.md) + - [label](js-components-basic-label.md) + - [marquee](js-components-basic-marquee.md) + - [menu](js-components-basic-menu.md) + - [option](js-components-basic-option.md) + - [picker](js-components-basic-picker.md) + - [picker-view](js-components-basic-picker-view.md) + - [piece](js-components-basic-piece.md) + - [progress](js-components-basic-progress.md) + - [qrcode](js-components-basic-qrcode.md) + - [rating](js-components-basic-rating.md) + - [richtext](js-components-basic-richtext.md) + - [search](js-components-basic-search.md) + - [select](js-components-basic-select.md) + - [slider](js-components-basic-slider.md) + - [span](js-components-basic-span.md) + - [switch](js-components-basic-switch.md) + - [text](js-components-basic-text.md) + - [textarea](js-components-basic-textarea.md) + - [toolbar](js-components-basic-toolbar.md) + - [toolbar-item](js-components-basic-toolbar-item.md) + - [toggle](js-components-basic-toggle.md) + - [web](js-components-basic-web.md) + - [xcomponent](js-components-basic-xcomponent.md) +- Media Components + - [video](js-components-media-video.md) +- Canvas Components + - [canvas](js-components-canvas-canvas.md) + - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) + - [Image](js-components-canvas-image.md) + - [CanvasGradient](js-components-canvas-canvasgradient.md) + - [ImageData](js-components-canvas-imagedata.md) + - [Path2D](js-components-canvas-path2d.md) + - [ImageBitmap](js-components-canvas-imagebitmap.md) + - [OffscreenCanvas](js-components-canvas-offscreencanvas.md) + - [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md) +- Grid Components + - [Basic Concepts](js-components-grid-basic-concepts.md) + - [grid-container](js-components-grid-container.md) + - [grid-row](js-components-grid-row.md) + - [grid-col](js-components-grid-col.md) +- SVG Components + - [Universal Attributes](js-components-svg-common-attributes.md) + - [svg](js-components-svg.md) + - [rect](js-components-svg-rect.md) + - [circle](js-components-svg-circle.md) + - [ellipse](js-components-svg-ellipse.md) + - [path](js-components-svg-path.md) + - [line](js-components-svg-line.md) + - [polyline](js-components-svg-polyline.md) + - [polygon](js-components-svg-polygon.md) + - [text](js-components-svg-text.md) + - [tspan](js-components-svg-tspan.md) + - [textPath](js-components-svg-textpath.md) + - [animate](js-components-svg-animate.md) + - [animateMotion](js-components-svg-animatemotion.md) + - [animateTransform](js-components-svg-animatetransform.md) - - Container Component - - [badge](js-components-container-badge.md) - - [dialog](js-components-container-dialog.md) - - [div](js-components-container-div.md) - - [form](js-components-container-form.md) - - [list](js-components-container-list.md) - - [list-item](js-components-container-list-item.md) - - [list-item-group](js-components-container-list-item-group.md) - - [panel](js-components-container-panel.md) - - [popup](js-components-container-popup.md) - - [refresh](js-components-container-refresh.md) - - [stack](js-components-container-stack.md) - - [stepper](js-components-container-stepper.md) - - [stepper-item](js-components-container-stepper-item.md) - - [swiper](js-components-container-swiper.md) - - [tabs](js-components-container-tabs.md) - - [tab-bar](js-components-container-tab-bar.md) - - [tab-content](js-components-container-tab-content.md) - - - Basic Components - - [button](js-components-basic-button.md) - - [chart](js-components-basic-chart.md) - - [divider](js-components-basic-divider.md) - - [image](js-components-basic-image.md) - - [image-animator](js-components-basic-image-animator.md) - - [input](js-components-basic-input.md) - - [label](js-components-basic-label.md) - - [marquee](js-components-basic-marquee.md) - - [menu](js-components-basic-menu.md) - - [option](js-components-basic-option.md) - - [picker](js-components-basic-picker.md) - - [picker-view](js-components-basic-picker-view.md) - - [piece](js-components-basic-piece.md) - - [progress](js-components-basic-progress.md) - - [qrcode](js-components-basic-qrcode.md) - - [rating](js-components-basic-rating.md) - - [richtext](js-components-basic-richtext.md) - - [search](js-components-basic-search.md) - - [select](js-components-basic-select.md) - - [slider](js-components-basic-slider.md) - - [span](js-components-basic-span.md) - - [switch](js-components-basic-switch.md) - - [text](js-components-basic-text.md) - - [textarea](js-components-basic-textarea.md) - - [toolbar](js-components-basic-toolbar.md) - - [toolbar-item](js-components-basic-toolbar-item.md) - - [toggle](js-components-basic-toggle.md) - - [web](js-components-basic-web.md) - - [xcomponent](js-components-basic-xcomponent.md) - - Media Components - - [video](js-components-media-video.md) - - - Canvas Components - - [canvas](js-components-canvas-canvas.md) - - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) - - [Image](js-components-canvas-image.md) - - [CanvasGradient](js-components-canvas-canvasgradient.md) - - [ImageData](js-components-canvas-imagedata.md) - - [Path2D](js-components-canvas-path2d.md) - - [ImageBitmap](js-components-canvas-imagebitmap.md) - - [OffscreenCanvas](js-components-canvas-offscreencanvas.md) - - [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md) - - - Grid - - [Basic Concepts](js-components-grid-basic-concepts.md) - - [grid-container](js-components-grid-container.md) - - [grid-row](js-components-grid-row.md) - - [grid-col](js-components-grid-col.md) - - - SVG Components - - [Universal Attributes](js-components-svg-common-attributes.md) - - [svg](js-components-svg.md) - - [rect](js-components-svg-rect.md) - - [circle](js-components-svg-circle.md) - - [ellipse](js-components-svg-ellipse.md) - - [path](js-components-svg-path.md) - - [line](js-components-svg-line.md) - - [polyline](js-components-svg-polyline.md) - - [polygon](js-components-svg-polygon.md) - - [text](js-components-svg-text.md) - - [tspan](js-components-svg-tspan.md) - - [textPath](js-components-svg-textpath.md) - - [animate](js-components-svg-animate.md) - - [animateMotion](js-components-svg-animatemotion.md) - - [animateTransform](js-components-svg-animatetransform.md) - Custom Components - - [Basic Usage](js-components-custom-basic-usage.md) - - [Style Inheritance](js-components-custom-style.md) - - [Custom Events](js-components-custom-events.md) - - [props](js-components-custom-props.md) - - [Event Parameter](js-components-custom-event-parameter.md) - - [slot](js-components-custom-slot.md) - - [Lifecycle Definition](js-components-custom-lifecycle.md) -- Appendix - - [Type Attributes](js-appendix-types.md) + - [Basic Usage](js-components-custom-basic-usage.md) + - [Style Inheritance](js-components-custom-style.md) + - [Custom Events](js-components-custom-events.md) + - [props](js-components-custom-props.md) + - [Event Parameter](js-components-custom-event-parameter.md) + - [slot](js-components-custom-slot.md) + - [Lifecycle Definition](js-components-custom-lifecycle.md) +- [Data Type Attributes](js-appendix-types.md) diff --git a/en/application-dev/reference/arkui-js/js-appendix-types.md b/en/application-dev/reference/arkui-js/js-appendix-types.md index b491d59c5fef5c948bf5119fcac48e302a83f3ff..335bb726f6a1e9d3cd86adf0b5d54c493f4eb15e 100644 --- a/en/application-dev/reference/arkui-js/js-appendix-types.md +++ b/en/application-dev/reference/arkui-js/js-appendix-types.md @@ -1,4 +1,4 @@ -# Type Attributes +# Data Type Attributes ## Length Type diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 6b9270ec688ba6470e5bcde047ea964c15b209bb..ee169162cdeeeeb0be3c4c717d74d6bb231b74ff 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -1,133 +1,138 @@ # TypeScript-based Declarative Development Paradigm -- Components - - Universal Components - - Universal Events - - [Click Event](ts-universal-events-click.md) - - [Touch Event](ts-universal-events-touch.md) - - [Show/Hide Event](ts-universal-events-show-hide.md) - - [Drag/Drop Event](ts-universal-events-drag-drop.md) - - [Key Event](ts-universal-events-key.md) - - [Focus Event](ts-universal-focus-event.md) - - [Mouse Event](ts-universal-mouse-key.md) - - [Component Area Change Event](ts-universal-component-area-change-event.md) - - Universal Attributes - - [Size](ts-universal-attributes-size.md) - - [Location](ts-universal-attributes-location.md) - - [Layout Constraints](ts-universal-attributes-layout-constraints.md) - - [Flex Layout](ts-universal-attributes-flex-layout.md) - - [Border](ts-universal-attributes-border.md) - - [Background](ts-universal-attributes-background.md) - - [Opacity](ts-universal-attributes-opacity.md) - - [Visibility](ts-universal-attributes-visibility.md) - - [Enable/Disable](ts-universal-attributes-enable.md) - - [Overlay](ts-universal-attributes-overlay.md) - - [Z-order Control](ts-universal-attributes-z-order.md) - - [Transformation](ts-universal-attributes-transformation.md) - - [Image Effect Configuration](ts-universal-attributes-image-effect.md) - - [Shape Clipping](ts-universal-attributes-sharp-clipping.md) - - [Text Style](ts-universal-attributes-text-style.md) - - [Grid](ts-universal-attributes-grid.md) - - [Gradient Color](ts-universal-attributes-gradient-color.md) - - [Popup Control](ts-universal-attributes-popup.md) - - [Menu Control](ts-universal-attributes-menu.md) - - [Click Control](ts-universal-attributes-click.md) - - [Focus Control](ts-universal-attributes-focus.md) - - [Hover Effect](ts-universal-attributes-hover-effect.md) - - [Component ID](ts-universal-attributes-component-id.md) - - [Touch Target](ts-universal-attributes-touch-target.md) - - [Polymorphic Style](ts-universal-attributes-polymorphic-style.md) - - Gesture Processing - - [Gesture Binding Methods](ts-gesture-settings.md) - - Basic Gestures - - [TapGesture](ts-basic-gestures-tapgesture.md) - - [LongPressGesture](ts-basic-gestures-longpressgesture.md) - - [PanGesture](ts-basic-gestures-pangesture.md) - - [PinchGesture](ts-basic-gestures-pinchgesture.md) - - [RotationGesture](ts-basic-gestures-rotationgesture.md) - - [SwipeGesture](ts-basic-gestures-swipegesture.md) - - [Combined Gestures](ts-combined-gestures.md) - - Basic Components - - [Blank](ts-basic-components-blank.md) - - [Button](ts-basic-components-button.md) - - [Checkbox](ts-basic-components-checkbox.md) - - [CheckboxGroup](ts-basic-components-checkboxgroup.md) - - [DataPanel](ts-basic-components-datapanel.md) - - [DatePicker](ts-basic-components-datepicker.md) - - [Divider](ts-basic-components-divider.md) - - [Gauge](ts-basic-components-gauge.md) - - [Image](ts-basic-components-image.md) - - [ImageAnimator](ts-basic-components-imageanimator.md) - - [LoadingProgress](ts-basic-components-loadingprogress.md) - - [Marquee](ts-basic-components-marquee.md) - - [Navigation](ts-basic-components-navigation.md) - - [PatternLock](ts-basic-components-patternlock.md) - - [PluginComponent](ts-basic-components-plugincomponent.md) - - [Progress](ts-basic-components-progress.md) - - [QRCode](ts-basic-components-qrcode.md) - - [Radio](ts-basic-components-radio.md) - - [Rating](ts-basic-components-rating.md) - - [RichText](ts-basic-components-richtext.md) - - [ScrollBar](ts-basic-components-scrollbar.md) - - [Search](ts-basic-components-search.md) - - [Select](ts-basic-components-select.md) - - [Slider](ts-basic-components-slider.md) - - [Span](ts-basic-components-span.md) - - [Stepper](ts-basic-components-stepper.md) - - [StepperItem](ts-basic-components-stepperitem.md) - - [Text](ts-basic-components-text.md) - - [TextArea](ts-basic-components-textarea.md) - - [TextClock](ts-basic-components-textclock.md) - - [TextInput](ts-basic-components-textinput.md) - - [TextPicker](ts-basic-components-textpicker.md) - - [TextTimer](ts-basic-components-texttimer.md) - - [TimePicker](ts-basic-components-timepicker.md) - - [Toggle](ts-basic-components-toggle.md) - - [Web](ts-basic-components-web.md) - - [XComponent](ts-basic-components-xcomponent.md) - - Container Components - - [AlphabetIndexer](ts-container-alphabet-indexer.md) - - [Badge](ts-container-badge.md) - - [Column](ts-container-column.md) - - [ColumnSplit](ts-container-columnsplit.md) - - [Counter](ts-container-counter.md) - - [Flex](ts-container-flex.md) - - [GridContainer](ts-container-gridcontainer.md) - - [Grid](ts-container-grid.md) - - [GridItem](ts-container-griditem.md) - - [List](ts-container-list.md) - - [ListItem](ts-container-listitem.md) - - [Navigator](ts-container-navigator.md) - - [Panel](ts-container-panel.md) - - [Refresh](ts-container-refresh.md) - - [Row](ts-container-row.md) - - [RowSplit](ts-container-rowsplit.md) - - [Scroll](ts-container-scroll.md) - - [SideBarContainer](ts-container-sidebarcontainer.md) - - [Stack](ts-container-stack.md) - - [Swiper](ts-container-swiper.md) - - [Tabs](ts-container-tabs.md) - - [TabContent](ts-container-tabcontent.md) - - Media Components - - [Video](ts-media-components-video.md) - - Drawing Components - - [Circle](ts-drawing-components-circle.md) - - [Ellipse](ts-drawing-components-ellipse.md) - - [Line](ts-drawing-components-line.md) - - [Polyline](ts-drawing-components-polyline.md) - - [Polygon](ts-drawing-components-polygon.md) - - [Path](ts-drawing-components-path.md) - - [Rect](ts-drawing-components-rect.md) - - [Shape](ts-drawing-components-shape.md) - - Canvas Components - - [Canvas](ts-components-canvas-canvas.md) - - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) - - [OffscreenCanvasRenderingConxt2D](ts-offscreencanvasrenderingcontext2d.md) - - [Lottie](ts-components-canvas-lottie.md) - - [Path2D](ts-components-canvas-path2d.md) - - [CanvasGradient](ts-components-canvas-canvasgradient.md) - - [ImageBitmap](ts-components-canvas-imagebitmap.md) - - [ImageData](ts-components-canvas-imagedata.md) +- Universal Component Information + - Universal Events + - [Click Event](ts-universal-events-click.md) + - [Touch Event](ts-universal-events-touch.md) + - [Show/Hide Event](ts-universal-events-show-hide.md) + - [Drag/Drop Event](ts-universal-events-drag-drop.md) + - [Key Event](ts-universal-events-key.md) + - [Focus Event](ts-universal-focus-event.md) + - [Mouse Event](ts-universal-mouse-key.md) + - [Component Area Change Event](ts-universal-component-area-change-event.md) + - [Visible Area Change Event](ts-universal-component-visible-area-change-event.md) + - Universal Attributes + - [Size](ts-universal-attributes-size.md) + - [Location](ts-universal-attributes-location.md) + - [Layout Constraints](ts-universal-attributes-layout-constraints.md) + - [Flex Layout](ts-universal-attributes-flex-layout.md) + - [Border](ts-universal-attributes-border.md) + - [Border Image](ts-universal-attributes-border-image.md) + - [Background](ts-universal-attributes-background.md) + - [Opacity](ts-universal-attributes-opacity.md) + - [Visibility](ts-universal-attributes-visibility.md) + - [Enable/Disable](ts-universal-attributes-enable.md) + - [Overlay](ts-universal-attributes-overlay.md) + - [Z-order Control](ts-universal-attributes-z-order.md) + - [Transformation](ts-universal-attributes-transformation.md) + - [Image Effect Configuration](ts-universal-attributes-image-effect.md) + - [Shape Clipping](ts-universal-attributes-sharp-clipping.md) + - [Text Style](ts-universal-attributes-text-style.md) + - [Grid](ts-universal-attributes-grid.md) + - [Gradient Color](ts-universal-attributes-gradient-color.md) + - [Popup Control](ts-universal-attributes-popup.md) + - [Menu Control](ts-universal-attributes-menu.md) + - [Click Control](ts-universal-attributes-click.md) + - [Focus Control](ts-universal-attributes-focus.md) + - [Hover Effect](ts-universal-attributes-hover-effect.md) + - [Component ID](ts-universal-attributes-component-id.md) + - [Touch Target](ts-universal-attributes-touch-target.md) + - [Polymorphic Style](ts-universal-attributes-polymorphic-style.md) + - Gesture Processing + - [Gesture Binding Methods](ts-gesture-settings.md) + - Basic Gestures + - [TapGesture](ts-basic-gestures-tapgesture.md) + - [LongPressGesture](ts-basic-gestures-longpressgesture.md) + - [PanGesture](ts-basic-gestures-pangesture.md) + - [PinchGesture](ts-basic-gestures-pinchgesture.md) + - [RotationGesture](ts-basic-gestures-rotationgesture.md) + - [SwipeGesture](ts-basic-gestures-swipegesture.md) + - [Combined Gestures](ts-combined-gestures.md) +- Basic Components + - [Blank](ts-basic-components-blank.md) + - [Button](ts-basic-components-button.md) + - [Checkbox](ts-basic-components-checkbox.md) + - [CheckboxGroup](ts-basic-components-checkboxgroup.md) + - [DataPanel](ts-basic-components-datapanel.md) + - [DatePicker](ts-basic-components-datepicker.md) + - [Divider](ts-basic-components-divider.md) + - [Gauge](ts-basic-components-gauge.md) + - [Image](ts-basic-components-image.md) + - [ImageAnimator](ts-basic-components-imageanimator.md) + - [LoadingProgress](ts-basic-components-loadingprogress.md) + - [Marquee](ts-basic-components-marquee.md) + - [Navigation](ts-basic-components-navigation.md) + - [PatternLock](ts-basic-components-patternlock.md) + - [PluginComponent](ts-basic-components-plugincomponent.md) + - [Progress](ts-basic-components-progress.md) + - [QRCode](ts-basic-components-qrcode.md) + - [Radio](ts-basic-components-radio.md) + - [Rating](ts-basic-components-rating.md) + - [RemoteWindow](ts-basic-components-remotewindow.md) + - [RichText](ts-basic-components-richtext.md) + - [ScrollBar](ts-basic-components-scrollbar.md) + - [Search](ts-basic-components-search.md) + - [Select](ts-basic-components-select.md) + - [Slider](ts-basic-components-slider.md) + - [Span](ts-basic-components-span.md) + - [Stepper](ts-basic-components-stepper.md) + - [StepperItem](ts-basic-components-stepperitem.md) + - [Text](ts-basic-components-text.md) + - [TextArea](ts-basic-components-textarea.md) + - [TextClock](ts-basic-components-textclock.md) + - [TextInput](ts-basic-components-textinput.md) + - [TextPicker](ts-basic-components-textpicker.md) + - [TextTimer](ts-basic-components-texttimer.md) + - [TimePicker](ts-basic-components-timepicker.md) + - [Toggle](ts-basic-components-toggle.md) + - [Web](ts-basic-components-web.md) + - [XComponent](ts-basic-components-xcomponent.md) +- Container Components + - [AbilityComponent](ts-container-ability-component.md) + - [AlphabetIndexer](ts-container-alphabet-indexer.md) + - [Badge](ts-container-badge.md) + - [Column](ts-container-column.md) + - [ColumnSplit](ts-container-columnsplit.md) + - [Counter](ts-container-counter.md) + - [Flex](ts-container-flex.md) + - [GridContainer](ts-container-gridcontainer.md) + - [Grid](ts-container-grid.md) + - [GridItem](ts-container-griditem.md) + - [List](ts-container-list.md) + - [ListItem](ts-container-listitem.md) + - [Navigator](ts-container-navigator.md) + - [Panel](ts-container-panel.md) + - [Refresh](ts-container-refresh.md) + - [RelativeContainer](ts-container-relativecontainer.md) + - [Row](ts-container-row.md) + - [RowSplit](ts-container-rowsplit.md) + - [Scroll](ts-container-scroll.md) + - [SideBarContainer](ts-container-sidebarcontainer.md) + - [Stack](ts-container-stack.md) + - [Swiper](ts-container-swiper.md) + - [Tabs](ts-container-tabs.md) + - [TabContent](ts-container-tabcontent.md) +- Media Components + + - [Video](ts-media-components-video.md) +- Drawing Components + - [Circle](ts-drawing-components-circle.md) + - [Ellipse](ts-drawing-components-ellipse.md) + - [Line](ts-drawing-components-line.md) + - [Polyline](ts-drawing-components-polyline.md) + - [Polygon](ts-drawing-components-polygon.md) + - [Path](ts-drawing-components-path.md) + - [Rect](ts-drawing-components-rect.md) + - [Shape](ts-drawing-components-shape.md) +- Canvas Components + - [Canvas](ts-components-canvas-canvas.md) + - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) + - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) + - [Lottie](ts-components-canvas-lottie.md) + - [Path2D](ts-components-canvas-path2d.md) + - [CanvasGradient](ts-components-canvas-canvasgradient.md) + - [ImageBitmap](ts-components-canvas-imagebitmap.md) + - [ImageData](ts-components-canvas-imagedata.md) - Animation - [AnimatorProperty](ts-animatorproperty.md) - [Explicit Animation](ts-explicit-animation.md) diff --git a/en/application-dev/reference/arkui-ts/figures/borderImageGradient.png b/en/application-dev/reference/arkui-ts/figures/borderImageGradient.png new file mode 100644 index 0000000000000000000000000000000000000000..edf91d4844deeee4f997f65d2d88b45bf7ff7f1d Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/borderImageGradient.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193499234.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193499234.gif index 52fed39eeae057043dbd00abce9ff29d2c35a56a..15849e6bc210ed2bb7f7a798b145c9794972643c 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193499234.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001193499234.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_visible_area_change.gif b/en/application-dev/reference/arkui-ts/figures/en-us_visible_area_change.gif new file mode 100644 index 0000000000000000000000000000000000000000..3b82bc987ff6d8bbe42f00e73148b35c445fa8c8 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_visible_area_change.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/relativecontainer.png b/en/application-dev/reference/arkui-ts/figures/relativecontainer.png new file mode 100644 index 0000000000000000000000000000000000000000..ebe9c3c7f6ba5ba6756b61f757894cc3f69014bf Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/relativecontainer.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md index 3eeec830107e6896a2bb07ba4cdb0a31028ecae6..af6866db3835823c394d536f5f0b5efcb4213c22 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-blank.md @@ -6,7 +6,7 @@ > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -The **<Blank>** component supports automatic filling of the empty part of the container along the main axis. This component is valid only when the parent component is **<Row>** or **<Column>**. +The **\** component supports automatic filling of the empty part of the container along the main axis. This component is valid only when the parent component is **\** or **\**. ## Required Permissions @@ -24,7 +24,7 @@ Not supported Blank(min?: Length) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | | min | Length | No | 0 | Minimum size of the **<Blank>** component in the container along the main axis. | @@ -33,9 +33,10 @@ Blank(min?: Length) | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| color | Color | 0x00000000 | Color to fill the blank. | +| color | [ResourceColor](../../ui/ts-types.md) | 0x00000000 | Color to fill the blank. | -> **NOTE**
+> **NOTE** +> > Universal attribute methods are not supported. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-button.md b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md index 42ac10339280af072effe49c7850c0a5fc1087d3..5f7d75d5406fd705e5a0716ff9d94fd3dd73de22 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-button.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-button.md @@ -1,13 +1,12 @@ # Button +The **\