diff --git a/CODEOWNERS b/CODEOWNERS index ca2ba48baa68fb4990cc3e34fcf9ee5537ef1c28..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 @@ -200,7 +211,7 @@ zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen 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..6d25dfc5658b20f7005c59287d4475f3eb4e5071 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). + +| System Type| Board Model| Chip Model| Function Description and Use Case| Application Scenario| Code Repository and Daily Build| | -------- | -------- | -------- | -------- | -------- | -------- | -| 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.| 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 | +| 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.| 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 | +| 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.| 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 | -## 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/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..fadb084eecebc65fe59fba9245829d28ce7b6095 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -33,7 +33,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat

IRemoteProxy

-   +

Service proxy classes are derived from the IRemoteProxy class.

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-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index c9fd1c05fd6dc959c8cdfcab155d785833bc631f..24faeb9de8ed3ee35e773668cd110310feadc9ef 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -9,6 +9,8 @@ The distributed data objects support basic data types, such as number, string, a ## Available APIs +For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). + ### Creating a Distributed Data Object Instance Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**. @@ -216,40 +218,39 @@ The following example shows how to implement distributed data object synchroniza 10. Save a distributed data object and revoke the data saving operation. - Callback - - ```js - // Save a distributed data object. - local_object.save("local", (result, data)=>{ - console.log("save callback"); - console.info("save sessionId " + data.sessionId); - console.info("save version " + data.version); - console.info("save deviceId " + data.deviceId); - }); - // Revoke the data saving operation. - local_object.revokeSave((result, data) =>{ - console.log("revokeSave callback"); - console.info("revokeSave sessionId " + data.sessionId); - }); - ``` - - Promise - - ```js - // Save a distributed data object. - g_object.save("local").then((result)=>{ - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); - }, (result)=>{ - console.info("save local failed."); - }); - // Revoke the data saving operation. - g_object.revokeSave().then((result)=>{ - console.info("revokeSave success."); - }, (result)=>{ - console.info("revokeSave failed."); - }); - ``` -11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregister all callbacks of this distributed data object. + + ```js + // Save a distributed data object. + local_object.save("local", (result, data)=>{ + console.log("save callback"); + console.info("save sessionId " + data.sessionId); + console.info("save version " + data.version); + console.info("save deviceId " + data.deviceId); + }); + // Revoke the data saving operation. + local_object.revokeSave((result, data) =>{ + console.log("revokeSave callback"); + console.info("revokeSave sessionId " + data.sessionId); + }); + ``` + - Promise + ```js + // Save a distributed data object. + g_object.save("local").then((result)=>{ + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); + }, (result)=>{ + console.info("save local failed."); + }); + // Revoke the data saving operation. + g_object.revokeSave().then((result)=>{ + console.info("revokeSave success."); + }, (result)=>{ + console.info("revokeSave failed."); + }); + ``` +11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object. The sample code is as follows: ```js diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index 309d2a38e4cbcab79a102b809bb9444cf9a8e1ee..c5608c6eabd526c38a87bd3907fba89fb1a11629 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat ## Available APIs +For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). + The table below describes the APIs provided by the OpenHarmony DDS module. **Table 1** APIs provided by the DDS -| Category | API | Description | -| -------- | --- | ----------- | -| Creating a distributed database | createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| -| Obtaining a distributed KV store | getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Obtains the KV store with the specified **Options** and **storeId**. | -| Managing data in a distributed KV store | put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array \| string \| number \| boolean): Promise<void> | Inserts and updates data. | +| Category | API | Description | +| ------------ | ------------- | ------------- | +| Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| +| Obtaining a distributed KV store| getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Obtains the KV store with the specified **Options** and **storeId**.| +| Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array \| string \| number \| boolean): Promise<void> | Inserts and updates data.| | Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | -| Managing data in a distributed KV store | get(key: string, callback: AsyncCallback<Uint8Array \| string \| boolean \| number>): void
get(key: string): Promise<Uint8Array \| string \| boolean \| number> | Queries data. | -| Subscribing to changes in the distributed data | on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void | Subscribes to data changes in the KV store. | -| Synchronizing data across devices | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | +| Managing data in a distributed KV store| get(key: string, callback: AsyncCallback<Uint8Array \| string \| boolean \| number>): void
get(key: string): Promise<Uint8Array \| string \| boolean \| number> | Queries data. | +| Subscribing to changes in the distributed data| on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void | Subscribes to data changes in the KV store.| +| Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | @@ -29,14 +31,13 @@ The table below describes the APIs provided by the OpenHarmony DDS module. The following uses a single KV store as an example to describe the development procedure. 1. Import the distributed data module. - ```js import distributedData from '@ohos.data.distributedData'; ``` 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. - 1. Create a **KvManagerConfig** object based on the application context. - 2. Create a **KvManager** instance. + (1) Create a **KvManagerConfig** object based on the application context. + (2) Create a **KvManager** instance. The sample code is as follows: ```js @@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p ``` 3. Create and obtain a single KV store. - 1. Declare the ID of the single KV store to create. - 2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. + (1) Declare the ID of the single KV store to create. + (2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. The sample code is as follows: ```js @@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p } ``` - > ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
+ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. -4. Subscribe to changes in the distributed data.
+4. Subscribe to changes in the distributed data.
The following is the sample code for subscribing to the data changes of a single KV store: - ```js kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { console.log("dataChange callback call data: " + JSON.stringify(data)); @@ -104,8 +104,8 @@ The following uses a single KV store as an example to describe the development p ``` 5. Write data to the single KV store. - 1. Construct the key and value to be written into the single KV store. - 2. Write key-value pairs into the single KV store. + (1) Construct the key and value to be written into the single KV store. + (2) Write key-value pairs into the single KV store. The following is the sample code for writing key-value pairs of the string type into the single KV store: @@ -126,11 +126,10 @@ The following uses a single KV store as an example to describe the development p ``` 6. Query data in the single KV store. - 1. Construct the key to be queried from the single KV store. - 2. Query data from the single KV store. + (1) Construct the key to be queried from the single KV store. + (2) Query data from the single KV store. The following is the sample code for querying data of the string type from the single KV store: - ```js const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; @@ -178,3 +177,7 @@ The following uses a single KV store as an example to describe the development p } }); ``` +## Samples +The following samples are provided to help you better understand the distributed data development: +- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) +- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData) diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 50d34b56ce3309b953285083d9ce97405e0721d2..53bba062801ec1b8bcf1f65cdc4119fa53757f10 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class| API| Description| | -------- | -------- | -------- | - | RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This API uses a callback to return the result.
- **table**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + | RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This API uses a callback to return the result.
- **table**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.| | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating data** @@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local | -------- | -------- | -------- | | RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| -### Backing Up and Restore an RDB Store +### Backing Up and Restoring an RDB Store **Backing Up an RDB Store** @@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |backup(destName:string, callback: AsyncCallback<void>):void| Backs up the RDB store with the specified name. This API uses an asynchronous callback to return the result.
- **destName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| -| RdbStore |backup(destName:string): Promise<void>| Backs up the RDB store with the specified name. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| +| RdbStore |backup(destName:string, callback: AsyncCallback<void>):void| Backs up an RDB store. This API uses an asynchronous callback to return the result.
- **destName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| +| RdbStore |backup(destName:string): Promise<void>| Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| **Restoring an RDB Store** @@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |restore(srcName:string, callback: AsyncCallback<void>):void| Restores an RDB store using the specified backup file. This API uses an asynchronous callback to return the result.
- **srcName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| -| RdbStore |restore(srcName:string): Promise<void>| Restores an RDB store using the specified backup file. This API uses a promise to return the result.
- **srcName**: name of the RDB backup file.| +| RdbStore |restore(srcName:string, callback: AsyncCallback<void>):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.
- **srcName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| +| RdbStore |restore(srcName:string): Promise<void>| Restores an RDB store using a backup file. This API uses a promise to return the result.
- **srcName**: name of the RDB backup file.| ## How to Develop @@ -270,7 +270,7 @@ You can obtain the distributed table name for a remote device based on the local const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) resultSet.close() }) - ``` + ``` 4. Set the distributed tables to be synchronized. diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md index c4e4fdf3850f4bd3b1b8f6902133835764414cb3..fb107049c515d0ff1961313a9f0bebb39c4e4c9d 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md @@ -3,7 +3,6 @@ ## When to Use With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group. - The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported. ## Available APIs @@ -23,7 +22,7 @@ import stats from '@ohos.bundleState'; | function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.| | function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. | -| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**.| +| function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used.| | function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries the number of notifications from all applications based on the specified start time and end time.| | function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.| | function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.| @@ -45,7 +44,7 @@ import stats from '@ohos.bundleState'; ..., "reqPermissions": [ { - "name": "ohos.permission.BUNDLE_ACTIVE_INFO" + "name": "ohos.permission.BUNDLE_ACTIVE_INFO" } ] } @@ -57,13 +56,13 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Promise mode - stats.queryBundleActiveStates(0, 20000000000000).then( res => { + stats.queryBundleActiveStates(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code); }); @@ -87,7 +86,7 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Promise mode - stats.queryBundleStateInfos(0, 20000000000000).then( res => { + stats.queryBundleStateInfos(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); let i = 1; for (let key in res){ @@ -95,7 +94,7 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); i++; } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); }); @@ -121,13 +120,13 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Promise mode - stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { + stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); }); @@ -151,13 +150,13 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Promise mode - stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { + stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); }); @@ -179,14 +178,14 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - + // Promise mode - stats.queryAppUsagePriorityGroup().then( res => { + stats.queryAppUsagePriorityGroup().then(res => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); }); - + // Callback mode stats.queryAppUsagePriorityGroup((err, res) => { if (err) { @@ -196,16 +195,16 @@ import stats from '@ohos.bundleState'; } }); ``` - + 7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself. ```js import stats from '@ohos.bundleState' // Promise mode - stats.isIdleState("com.ohos.camera").then( res => { + stats.isIdleState("com.ohos.camera").then(res => { console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); }); @@ -225,18 +224,18 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Promise mode - stats.getRecentlyUsedModules(1000).then( res => { + stats.getRecentlyUsedModules(1000).then(res => { console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i])); } - }).catch( err=> { + }).catch(err=> { console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code); }); // Promise mode when maxNum is not specified - stats.getRecentlyUsedModules().then( res => { + stats.getRecentlyUsedModules().then(res => { console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); @@ -247,7 +246,7 @@ import stats from '@ohos.bundleState'; }); // Asynchronous callback mode - stats.getRecentlyUsedModules(1000,(err, res) => { + stats.getRecentlyUsedModules(1000, (err, res) => { if(err) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); } else { @@ -261,7 +260,7 @@ import stats from '@ohos.bundleState'; // Asynchronous callback mode when maxNum is not specified stats.getRecentlyUsedModules((err, res) => { - if(err) { + if (err) { console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); } else { console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.'); @@ -279,10 +278,10 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Promise mode - stats.queryAppNotificationNumber(0, 20000000000000).then( res => { + stats.queryAppNotificationNumber(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.'); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code); }); @@ -301,15 +300,15 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - + // Promise mode - stats.queryBundleActiveEventStates(0, 20000000000000).then( res => { + stats.queryBundleActiveEventStates(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code); }); - + // Asynchronous callback mode stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => { if (err) { @@ -325,14 +324,14 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - + // Promise mode without parameters - stats.queryAppUsagePriorityGroup().then( res => { + stats.queryAppUsagePriorityGroup().then(res => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); }); - + // Asynchronous callback mode without parameters stats.queryAppUsagePriorityGroup((err, res) => { if (err) { @@ -341,17 +340,17 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); } }); - + // Promise mode with parameters - stats.queryAppUsagePriorityGroup(this.bundleName).then( res => { + stats.queryAppUsagePriorityGroup(this.bundleName).then(res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); }); - + // Asynchronous callback mode with parameters stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { - if(err) { + if (err) { console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); } else { console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); @@ -363,16 +362,16 @@ import stats from '@ohos.bundleState'; ```javascript import stats from '@ohos.bundleState' - + // Promise mode - stats.setBundleGroup(this.bundleName, this.newGroup).then( () => { + stats.setBundleGroup(this.bundleName, this.newGroup).then(() => { console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.'); }).catch( err => { console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code); }); // Asynchronous callback mode stats.setBundleGroup(this.bundleName, this.newGroup, (err) => { - if(err) { + if (err) { console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); } else { console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.'); @@ -384,9 +383,9 @@ import stats from '@ohos.bundleState'; ```javascript import stats from '@ohos.bundleState' - + // Promise mode - let onBundleGroupChanged = (err,res) =>{ + let onBundleGroupChanged = (err,res) => { console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup); @@ -394,13 +393,13 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName); }; - stats.registerGroupCallBack(onBundleGroupChanged).then( () => { + stats.registerGroupCallBack(onBundleGroupChanged).then(() => { console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.'); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code); }); // Asynchronous callback mode - let onBundleGroupChanged = (err,res) =>{ + let onBundleGroupChanged = (err,res) => { console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup); @@ -408,29 +407,29 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName); }; - stats.registerGroupCallBack(onBundleGroupChanged, (err)=>{ - if(err) { + stats.registerGroupCallBack(onBundleGroupChanged, (err) => { + if (err) { console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code); } else { console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.'); } }); ``` - + 13. Deregister the callback for application group changes. ```javascript import stats from '@ohos.bundleState' - + //promise - stats.unRegisterGroupCallBack().then( () => { + stats.unRegisterGroupCallBack().then(() => { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); }); //callback - stats.unRegisterGroupCallBack((err)=>{ - if(err) { + stats.unRegisterGroupCallBack((err) => { + if (err) { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); } else { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.'); diff --git a/en/application-dev/device/device-location-geocoding.md b/en/application-dev/device/device-location-geocoding.md index 30f647d98a368168ba945e11f11bb59f65a5b455..f95df63eebe64eedb6063ae193f4b141bfd946c6 100644 --- a/en/application-dev/device/device-location-geocoding.md +++ b/en/application-dev/device/device-location-geocoding.md @@ -3,9 +3,9 @@ ## When to Use -Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. +Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. -With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc. +The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address. ## Available APIs @@ -36,13 +36,29 @@ The following table describes APIs available for mutual conversion between coord import geolocation from '@ohos.geolocation'; ``` -2. Obtain the conversion result. +2. Query whether geocoder service is available. + - Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3. + ``` + geolocation.isGeoServiceAvailable((err, data) => { + if (err) { + console.log('isGeoServiceAvailable err: ' + JSON.stringify(err)); + } else { + console.log('isGeoServiceAvailable data: ' + JSON.stringify(data)); + } + }); + ``` + +3. Obtain the conversion result. - Call **getAddressesFromLocation** to convert coordinates into geographical location information. ``` var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; - geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => { - console.log('getAddressesFromLocation: ' + JSON.stringify(data)); + geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); + } else { + console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); + } }); ``` @@ -51,8 +67,12 @@ The following table describes APIs available for mutual conversion between coord ``` var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; - geolocation.getAddressesFromLocationName(geocodeRequest, (data) => { - console.log('getAddressesFromLocationName: ' + JSON.stringify(data)); + geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); + } else { + console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); + } }); ``` diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index 84f189d7f247bd9516204c7dd0d76aafb6438dbb..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,18 +112,18 @@ 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': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` **Method 2:** @@ -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': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + 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,11 +176,15 @@ 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((data) => { - console.log('getLastLocation: data: ' + JSON.stringify(data)); + geolocation.getLastLocation((err, data) => { + if (err) { + console.log('getLastLocation: err: ' + JSON.stringify(err)); + } else { + console.log('getLastLocation: data: ' + JSON.stringify(data)); + } }); ``` 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-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/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index f2b6fe0e20564626d7a37d03832fae69f7f7866a..e58eed34cccb7dd820e1144a616dfb93a10f4d34 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -1,10 +1,10 @@ # Using Native APIs in Application Projects -OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the **arkui_napi** repository are used to implement the interaction with JS. Currently, the **arkui_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository. +OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. Currently, the **ace_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository. ## How to Develop -The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **arkui_napi** repository for development. +The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development. You can `import` the native .so that contains the JS processing logic. For example, `import hello from 'libhello.so'` to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the `hello` object of the application to call the native capability. @@ -74,7 +74,7 @@ export default storage; ### Implementation -You can obtain the complete code from `sample/native_module_storage/` in the **arkui_napi** repository. +You can obtain the complete code from `sample/native_module_storage/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. #### Registering the Module @@ -212,7 +212,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info) napi_create_async_work( env, nullptr, resource, - // Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using theNAPI because the execution is asynchronous. + // Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using the NAPI because the execution is asynchronous. [](napi_env env, void* data) { StorageAsyncContext* asyncContext = (StorageAsyncContext*)data; auto itr = gKeyValueStorage.find(asyncContext->key); @@ -307,7 +307,7 @@ export class NetServer { ### Implementation -You can obtain the complete code from `sample/native_module_netserver/` in the **arkui_napi** repository. +You can obtain the complete code from `sample/native_module_netserver/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. #### Registering the Module @@ -494,7 +494,7 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp ### Implementation -You can obtain the complete code from `sample/native_module_callback/` in the **arkui_napi** repository. +You can obtain the complete code from `sample/native_module_callback/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. #### Registering the Module @@ -562,7 +562,7 @@ void callbackTest(CallbackContext* context) uv_queue_work( loop, work, - // This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, the callback does not need to execute any task. + // This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, this callback does not need to execute any task. [](uv_work_t* work) {}, // This callback is executed in the JS thread bound to env. [](uv_work_t* work, int status) { 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 4646544abd6e22a632a35faeba6184819d601097..6b5bbc8aa3d671c4cf0b01316db441d33c0f189f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,53 +1,61 @@ # APIs +- [API Reference Document Description](development-intro.md) + - 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.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) @@ -55,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) @@ -66,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) @@ -93,41 +105,46 @@ - [@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) + - [@ohos.data.dataShare](js-apis-data-dataShare.md) + - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) + - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.rdb](js-apis-data-rdb.md) - - [@ohos.settings](js-apis-settings.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) @@ -138,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) @@ -148,14 +165,15 @@ - [@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) - [@ohos.net.http](js-apis-http.md) - [@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) @@ -166,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) @@ -185,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) @@ -205,18 +223,19 @@ - [@ohos.power](js-apis-power.md) - [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.sensor](js-apis-sensor.md) + - [@ohos.settings](js-apis-settings.md) - [@ohos.systemParameter](js-apis-system-parameter.md) - [@ohos.thermal](js-apis-thermal.md) - [@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) @@ -240,11 +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/development-intro.md b/en/application-dev/reference/apis/development-intro.md new file mode 100644 index 0000000000000000000000000000000000000000..8528a10ab6f4ba3dd14186079357ce28e650ee6a --- /dev/null +++ b/en/application-dev/reference/apis/development-intro.md @@ -0,0 +1,51 @@ +# API Reference Document Description + +API references provide the description of APIs used for application development. This topic describes common fields in the API references to help you better use the reference document. + +## Version Description + +In API references, the earliest versions of APIs and components are specified in the following ways: + +- For a new API or component, the version information is provided at the beginning of the reference document. Example: "The initial APIs of this module are supported since API version 7." +- For a new feature of an existing API or component, a superscript is added following the feature. For example, "uid8+" indicates that the **uid** attribute is supported since API version 8. + +## Ability Framework Model Description + +Ability is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability framework models are classified into the FA model and stage model. For details, see [Ability Framework Overview](../../ability/ability-brief.md). + +- If all the APIs of a module support only one model, the following description is provided at the beginning of the reference document: "The APIs of this module can be used only in the FA model." or "The APIs of this module can be used only in the stage model." +- If certain APIs of a module support only one model, the following description is provided individually for these APIs: "This API can be used only in the FA model." or "This API can be used only in the stage model." +- If both models are supported, no special description is provided. + +## Available APIs + +Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by non-system applications. + +A description regarding system APIs will be provided in the document. + +- If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs." +- If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API." + +## Permission Description + +By default, applications can access limited system resources. However, in some cases, an application needs to access excess data (including personal data) and functions of the system or another application to implement extended functions. For details, see [Access Control Overview](../../security/accesstoken-overview.md). + +To call APIs to access these resources, you must apply for the corresponding permissions by following the instructions provided in [Access Control Development](../../security/accesstoken-guidelines.md). + +- If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx" +- If an application can call an API without any permission, no special description is provided. + +To determine whether an application can apply for a specific permission, see [Permission List](../../security/permission-list.md). + +## System Capability Description + +System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SysCap](../../quick-start/syscap.md). + +The following description is provided for each API in the reference document to describe the system capability of the API: "**System capability**: SystemCapability.xxx.xxx" + +## Sample Code Language Description + +OpenHarmony supports two development languages: JS and TS. + +- When a code block is labeled with `js`, the sample code can be used in the JS and eTS projects. +- When a code block is labeled with `ts`, the sample code can be used only in the eTS project. 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 60f404c4b0510809a4c1d515c3cc99c184796ab9..2a3dc0d9e34fd7ba2dd3e37c018292bec6da8be9 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -21,7 +21,7 @@ Creates an **AppAccountManager** instance. **System capability**: SystemCapability.Account.AppAccount -**Return Value** +**Return value** | Type | Description | | ----------------- | ------------ | @@ -102,7 +102,7 @@ Adds an app account name and additional information (information that can be con | name | string | Yes | Name of the app account to add. | | extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| -**Return Value** +**Return value** | Type | Description | | ------------------- | --------------------- | @@ -198,7 +198,7 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p | ---- | ------ | ---- | ----------- | | name | string | Yes | Name of the app account to delete.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -255,7 +255,7 @@ Disables an app account from accessing an app with the given bundle name. This A | name | string | Yes | Name of the target app account.| | bundleName | string | Yes | Bundle name of the app. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -312,7 +312,7 @@ Enables an app account to access an app with the given bundle name. This API use | name | string | Yes | Name of the target app account. | | bundleName | string | Yes | Bundle name of the app.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -371,7 +371,7 @@ Checks whether an app account allows app data synchronization. This API uses a p | ---- | ------ | ---- | ------- | | name | string | Yes | Name of the target app account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :-------------------- | @@ -430,7 +430,7 @@ Sets a credential for an app account. This API uses a promise to return the resu | credentialType | string | Yes | Type of the credential to set.| | credential | string | Yes | Credential to set. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -487,7 +487,7 @@ Sets additional information for an app account. This API uses a promise to retur | name | string | Yes | Name of the target app account. | | extraInfo | string | Yes | Additional information to set.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -548,7 +548,7 @@ Sets whether to enable app data synchronization for an app account. This API use | name | string | Yes | Name of the target app account. | | isEnable | boolean | Yes | Whether to enable app data synchronization.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -606,7 +606,7 @@ Sets data to be associated with an app account. This API uses a promise to retur | key | string | Yes | Key of the data to set. The private key can be customized.| | value | string | Yes | Value of the data to be set. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -664,7 +664,7 @@ Obtains the credential of an app account. This API uses a promise to return the | name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to obtain.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :-------------------- | @@ -720,7 +720,7 @@ Obtains additional information of an app account. This API uses a promise to ret | ---- | ------ | ---- | ------- | | name | string | Yes | Name of the target app account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :-------------------- | @@ -778,7 +778,7 @@ Obtains data associated with an app account. This API uses a promise to return t | name | string | Yes | Name of the target app account. | | key | string | Yes | Key of the data to obtain.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :-------------------- | diff --git a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..3289f1d2efc43a5af0a8fa3266f41b1ff3139aaa --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @@ -0,0 +1,429 @@ +# Data Share Extension Ability + +The **DataShareExtensionAbility** module provides Extension abilities for data share services. + +>**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 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 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 + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----- | ------ | ------ | ------ | +| want | [Want](js-apis-application-Want.md#want) | Yes | **Want** information, including the ability name and bundle name.| +| callback | AsyncCallback<void> | Yes| Callback that returns no value.| + +**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 { + onCreate(want, callback) { + rdb.getRdbStore(this.context, { + name: DB_NAME + }, 1, function (err, data) { + console.log('getRdbStore done, data : ' + data); + rdbStore = data; + rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { + console.log('executeSql done, error message : ' + err); + }); + if (callback) { + callback(); + } + }); + } +}; +``` + +## getFileTypes + +getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void + +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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | ---------------------------------- | +| uri | string | Yes | URI of the file. | +| mimeTypeFilter | string | Yes | MIME types to match. | +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the MIME types obtained.| + +**Example** + +```ts +export default class DataShareExtAbility extends DataShareExtensionAbility { + getFileTypes(uri, mimeTypeFilter, callback) { + let err = {"code":0}; + let ret = new Array("type01", "type02", "type03"); + callback(err, ret); + } +}; +``` + +## openFile + +openFile?(uri: string, mode: string, callback: AsyncCallback<number>): void + +Opens a file. This API is called by the server and can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------------ | +| uri | string | Yes | URI of the file to open. | +| 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, mode, callback) { + let err = {"code":0}; + let fd = 0; + callback(err,fd); + } +}; +``` + +## insert + +insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void + +Inserts data into the database. This API can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----- | ------ | ------ | ------ | +| uri |string | Yes | URI of the data to insert.| +| valueBucket |[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| Data to insert.| +| callback |AsyncCallback<number> | Yes| Callback invoked to return the index of the data inserted.| + +**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, valueBucket, callback) { + if (valueBucket == null) { + console.info('invalid valueBuckets'); + return; + } + rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) { + console.info('callback ret:' + ret); + if (callback != undefined) { + callback(err, ret); + } + }); + } +}; +``` + +## update + +update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void + +Updates data in the database. This API can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| 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.| +| 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, predicates, valueBucket, callback) { + if (predicates == null || predicates == undefined) { + return; + } + rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) { + if (callback != undefined) { + callback(err, ret); + } + }); + } +}; +``` + +## delete + +delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void + +Deletes data from the database. This API can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| 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. | +| 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, predicates, callback) { + if (predicates == null || predicates == undefined) { + return; + } + rdbStore.delete(TBL_NAME, predicates, function (err, ret) { + if (callback != undefined) { + callback(err, ret); + } + }); + } +}; +``` + +## query + +query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void + +Queries data from the database. This API can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| 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.| +| 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, predicates, columns, callback) { + if (predicates == null || predicates == undefined) { + return; + } + rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { + if (resultSet != undefined) { + console.info('resultSet.rowCount: ' + resultSet.rowCount); + } + if (callback != undefined) { + callback(err, resultSet); + } + }); + } +}; +``` + +## getType + +getType?(uri: string, callback: AsyncCallback<string>): void + +Obtains the MIME type corresponding to the given URI. This API can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----- | ------ | ------ | ------ | +| uri | string | Yes | URI of the target data.| +| callback | AsyncCallback<string> | Yes| Callback invoked to return the MIME type obtained.| + +**Example** + +```ts +export default class DataShareExtAbility extends DataShareExtensionAbility { + getType(uri, callback) { + let err = {"code":0}; + let ret = "image"; + callback(err, ret); + } +}; +``` + +## batchInsert + +batchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: AsyncCallback<number>): void + +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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------------------------ | ---- | -------------------------------- | +| uri | string | Yes | URI of the data to insert. | +| valueBuckets | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of inserted 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 { + batchInsert(uri, valueBuckets, callback) { + if (valueBuckets == null || valueBuckets.length == undefined) { + console.info('invalid valueBuckets'); + return; + } + let resultNum = valueBuckets.length + valueBuckets.forEach(vb => { + rdbStore.insert(TBL_NAME, vb, function (err, ret) { + if (callback != undefined) { + callback(err, resultNum); + } + }); + }); + } +}; +``` + +## normalizeUri + +normalizeUri?(uri: string, callback: AsyncCallback<string>): void + +Normalizes a URI. This API can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ----------------------- | +| uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize.| +| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, the normalized URI is returned. Otherwise, **null** is returned.| + +**Example** + +```ts +export default class DataShareExtAbility extends DataShareExtensionAbility { + normalizeUri(uri, callback) { + let err = {"code":0}; + let ret = "normalize+" + uri; + callback(err, ret); + } +}; +``` + +## denormalizeUri + +denormalizeUri?(uri: string, callback: AsyncCallback<string>): void + +Denormalizes a URI. This API can be overridden as required. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| 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 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, 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-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-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md similarity index 94% rename from en/application-dev/reference/apis/js-apis-abilityManager.md rename to en/application-dev/reference/apis/js-apis-application-abilityManager.md index 28c5cd31b0350ca0e8b24c8bfbda21fb039adcd7..e1bf96bae511de4e1fb83d92df6ee05bdddbf990 100644 --- a/en/application-dev/reference/apis/js-apis-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -7,7 +7,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module are system APIs and cannot be called by third-party applications. -# Modules to Import +## Modules to Import ```js import AbilityManager from '@ohos.application.abilityManager' @@ -21,24 +21,24 @@ Enumerates the ability states. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Value| Description| +| 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. | +| 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 -Obtains the ability running information. This API uses an asynchronous callback to return the result. +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 | @@ -80,7 +80,7 @@ Updates the configuration. This API uses a promise to return the result. | Type | Description | | ---------------------------------------- | ------- | -| Promise\ | Promise used to return the result. | +| Promise\ | Promise used to return the result.| **Example** @@ -138,7 +138,7 @@ Obtains the ability running information. This API uses a promise to return the r | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result. | +| Promise\> | Promise used to return the result.| **Example** @@ -186,7 +186,7 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { 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 @@ -201,7 +201,7 @@ Obtains the extension running information. This API uses a promise to return the | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result. | +| Promise\> | Promise used to return the result.| **Example** @@ -246,14 +246,14 @@ abilitymanager.getTopAbility((err,data) => { 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. | +| Promise\| Promise used to return the result.| **Example** 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..7a76626655a193e7f146190df319fbbeafe8430d 100644 --- a/en/application-dev/reference/apis/js-apis-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-application-applicationContext.md @@ -1,18 +1,12 @@ # 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 Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance. @@ -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 @@ -61,47 +103,86 @@ Deregisters the listener that monitors the ability lifecycle of the application. **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 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 | +| ------------------------ | -------- | ---- | ------------------------------ | +| [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | callback | 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. | +| AsyncCallback | callback | Yes | Callback used to return the result. | + +**Example** + + ```js + 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-missionInfo.md b/en/application-dev/reference/apis/js-apis-application-missionInfo.md deleted file mode 100644 index 05938521e10970192409f856e68b816c18d3f3f0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-missionInfo.md +++ /dev/null @@ -1,28 +0,0 @@ -# MissionInfo - -> **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 MissionInfo from '@ohos.application.missionInfo' -``` - -## MissionInfo - -Provides the mission information. - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| missionId | number | Yes| Yes| Mission ID.| -| runningState | number | Yes| Yes| Running state of the mission.| -| lockedState | boolean | Yes| Yes| Locked state of the mission.| -| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| -| 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 is continuable.| 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-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 894370d603afe13fef35c965beb2adaec6f1ef8b..68d01ed3f45885cf6b53fb3de35fc9b3e6c45da5 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result. ``` import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; +import featureAbility from '@ohos.ability.featureAbility' +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data)=> { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); +var bufferSize; +audioRenderer.getBufferSize().then((data)=> { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); + }); +console.info('Buffer size:'+bufferSize); +var context = featureAbility.getContext(); +var path = await context.getCacheDir(); +var filePath = path+"/StarWars10s-2C-48000-4SW.wav" let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); @@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result. ``` import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; +import featureAbility from '@ohos.ability.featureAbility' + +var audioStreamInfo = { + samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels:audio.AudioChannel.CHANNEL_2, + sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 +} +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data) => { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); +var bufferSize; +audioRenderer.getBufferSize().then((data) => { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); + }); +console.info('BufferSize: ' + bufferSize); +var context = featureAbility.getContext(); +var path = await context.getCacheDir(); var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); @@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Example** ``` +import audio from '@ohos.multimedia.audio'; +import fileio from '@ohos.fileio'; + +var audioStreamInfo = { + samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels:audio.AudioChannel.CHANNEL_2, + sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data) => { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); var bufferSize; -await audioRenderer.getBufferSize().then(async function (data) => { - console.info('AudioFrameworkRenderLog: getBufferSize :SUCCESS '+data); +audioRenderer.getBufferSize().then((data) => { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); bufferSize=data; }).catch((err) => { - console.info('AudioFrameworkRenderLog: getBufferSize :ERROR : '+err.message); + console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); }); ``` @@ -2542,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to **Example** ``` -audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE).then(() => { +const audioManager = audio.getAudioManager(); +audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE).then(() => { console.log('Promise returned to indicate a successful volume setting.'); }); ``` @@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t **Example** ``` -audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE,()=>{ +const audioManager = audio.getAudioManager(); +audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE,()=>{ console.log('Callback returned to indicate a successful volume setting.'); }); ``` @@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th ``` audioRenderer.on('markReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches ``` audioRenderer.on('periodReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result. **Example** ``` +import audio from '@ohos.multimedia.audio'; +import fileio from '@ohos.fileio'; + +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags = 1 +} + +var audioCapturer; +audio.createAudioCapturer(audioCapturerOptions).then((data) => { + audioCapturer = data; + console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message); + }); audioCapturer.start().then(() => { console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); - console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); - console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS '); if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - stateFlag = true; + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); } }).catch((err) => { console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message); @@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result. ``` audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped : SUCCESS'); + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - stateFlag=true; - console.info('AudioFrameworkRecLog: resultFlag : '+stateFlag); + console.info('AudioFrameworkRecLog: State is Stopped': '); } }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); - stateFlag=false; + console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); }); ``` @@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => { console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); - stateFlag=true; console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag); }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); - stateFlag=false + console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); }); ``` @@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result. **Example** ``` +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message); + }); audioCapturer.read(bufferSize, true, async(err, buffer) => { if (!err) { console.log("Success in reading the buffer data"); @@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result. **Example** ``` +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message); + }); +console.info('Buffer size: ' + bufferSize); audioCapturer.read(bufferSize, true).then((buffer) => { console.info('buffer read successfully'); }).catch((err) => { @@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Example** ``` -await audioCapturer.getBufferSize().then(async function (bufferSize) { - console.info('AudioFrameworkRecordLog: getBufferSize :SUCCESS '+ bufferSize); - var buffer = await audioCapturer.read(bufferSize, true); - console.info('Buffer read is ' + buffer ); - }).catch((err) => { - console.info('AudioFrameworkRecordLog: getBufferSize :ERROR : '+err.message); +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data); + bufferSize = data; +}).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message); }); ``` @@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th ``` audioCapturer.on('markReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th ``` audioCapturer.on('periodReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); 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-bundle-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e80cf7f78b02192642a29794feaf794052bd4dc4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md @@ -0,0 +1,474 @@ +# DefaultAppManager + +The **DefaultAppManager** module provides APIs to query whether the current application is the default application of a specific type. + +> **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 + +``` +import defaultAppMgr from '@ohos.bundle.defaultAppManager' +``` +## defaultAppMgr.ApplicationType + +Enumerates the application types. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Description | +| -------- | -------- | -------------------------------------- | +| BROWSER | string | Default browser. | +| IMAGE | string | Default image viewer. | +| AUDIO | string | Default audio player. | +| VIDEO | string | Default video player. | +| PDF | string | Default PDF reader. | +| WORD | string | Default Word viewer. | +| EXCEL | string | Default Excel viewer. | +| PPT | string | Default PowerPoint viewer. | + +## defaultAppMgr.isDefaultApplication + +isDefaultApplication(type: string): Promise\ + +Checks whether this application is the default application of a system-defined application type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| + +**Example** + +```js +defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) +.then((data) => { + console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data)); +}).catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); +``` + +## defaultAppMgr.isDefaultApplication + +isDefaultApplication(type: string, callback: AsyncCallback\): void + +Checks whether this application is the default application of a system-defined application type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| + +**Example** + +```js +defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data)); + }); +``` + +## defaultAppMgr.getDefaultApplication + +getDefaultApplication(type: string, userId?: number): Promise\ + +Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| userId | number | No | User ID. The default value is the user ID of the caller. | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the default application.| + +**Example** + +```js +defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) +.then((data) => { + console.info('Operation successful. bundleInfo: ' + JSON.stringify(data)); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +defaultAppMgr.getDefaultApplication("image/png") +.then((data) => { + console.info('Operation successful. bundleInfo: ' + JSON.stringify(data)); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); +``` + +## defaultAppMgr.getDefaultApplication + +getDefaultApplication(type: string, userId: number, callback: AsyncCallback\) : void + +Obtains the default application of a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| userId | number | Yes | User ID. | +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. | + +**Example** + +```js +defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. bundleInfo:' + JSON.stringify(data)); +}); + +defaultAppMgr.getDefaultApplication("image/png", 100, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. bundleInfo:' + JSON.stringify(data)); +}); +``` + +## defaultAppMgr.getDefaultApplication + +getDefaultApplication(type: string, callback: AsyncCallback\) : void + +Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. | + +**Example** + +```js +defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. bundleInfo:' + JSON.stringify(data)); +}); + +defaultAppMgr.getDefaultApplication("image/png", (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful. bundleInfo:' + JSON.stringify(data)); +}); +``` + +## defaultAppMgr.setDefaultApplication + +setDefaultApplication(type: string, elementName: ElementName, userId?: number): Promise\ + +Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. | +| userId | number | No | User ID. The default value is the user ID of the caller. | + +**Example** + +```js +defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { + bundleName: "com.test.app", + moduleName: "module01", + abilityName: "MainAbility" +}) +.then((data) => { + console.info('Operation successful.'); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +defaultAppMgr.setDefaultApplication("image/png", { + bundleName: "com.test.app", + moduleName: "module01", + abilityName: "MainAbility" +}) +.then((data) => { + console.info('Operation successful.'); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); +``` + +## defaultAppMgr.setDefaultApplication + +setDefaultApplication(type: string, elementName: ElementName, userId: number, callback: AsyncCallback\) : void; + +Sets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. | +| userId | number | Yes | User ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { + bundleName: "com.test.app", + moduleName: "module01", + abilityName: "MainAbility" +}, 100, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); + }); + +defaultAppMgr.setDefaultApplication("image/png", { + bundleName: "com.test.app", + moduleName: "module01", + abilityName: "MainAbility" +}, 100, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); + }); +``` + +## defaultAppMgr.setDefaultApplication + +setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCallback\) : void; + +Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { + bundleName: "com.test.app", + moduleName: "module01", + abilityName: "MainAbility" +}, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); + }); + +defaultAppMgr.setDefaultApplication("image/png", { + bundleName: "com.test.app", + moduleName: "module01", + abilityName: "MainAbility" +}, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); + }); +``` + +## defaultAppMgr.resetDefaultApplication + +resetDefaultApplication(type: string, userId?: number): Promise\ + +Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| userId | number | No | User ID. The default value is the user ID of the caller. | + +**Example** + +```js +defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) +.then((data) => { + console.info('Operation successful.'); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +defaultAppMgr.resetDefaultApplication("image/png") +.then((data) => { + console.info('Operation successful.'); +}) +.catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); +``` + +## defaultAppMgr.resetDefaultApplication + +resetDefaultApplication(type: string, userId: number, callback: AsyncCallback\) : void; + +Resets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| userId | number | Yes | User ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); +}); + +defaultAppMgr.resetDefaultApplication("image/png", 100, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); +}); +``` + +## defaultAppMgr.resetDefaultApplication + +resetDefaultApplication(type: string, callback: AsyncCallback\) : void; + +Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION + +**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 | +| ----------- | ------ | ---- | --------------------------------------- | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); +}); + +defaultAppMgr.resetDefaultApplication("image/png", (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Operation successful.'); +}); +``` 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-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 43f15f6c7b3666fc53f69deadb0043e6adacca46..1298f29856048924fd2a7e8397724aa9fc0df8ee 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -347,7 +347,7 @@ After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera ```js async function getCameraInfo("cameraId") { - var cameraManager = await camera.getCameraManager(); + var cameraManager = await camera.getCameraManager(context); var cameras = await cameraManager.getCameras(); var cameraObj = cameras[0]; var cameraId = cameraObj.cameraId; @@ -2231,6 +2231,10 @@ Captures a photo with the specified capture settings. This API uses an asynchron **Example** ```js +let settings:PhotoCaptureSetting = { + quality = 1, + rotation = 0 +} photoOutput.capture(settings, (err) => { if (err) { console.error('Failed to capture the photo ${err.message}'); @@ -2359,7 +2363,7 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu **Example** ```js -photoOutput.on('frameShutter', (frameShutterInfo) => { +photoOutput.on('frameShutter', (err, frameShutterInfo) => { console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); }) @@ -2383,7 +2387,7 @@ Listens for photo capture end events. This API uses an asynchronous callback to **Example** ```js -photoOutput.on('captureEnd', (captureEndInfo) => { +photoOutput.on('captureEnd', (err, captureEndInfo) => { console.log('photo capture end, captureId : ' + captureEndInfo.captureId); console.log('frameCount : ' + captureEndInfo.frameCount); }) @@ -2407,7 +2411,7 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error **Example** ```js -photoOutput.on('error', (photoOutputError) => { +photoOutput.on('error', (err, photoOutputError) => { console.log('Photo output error code: ' + photoOutputError.code); }) ``` 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..755557fba6455122d78e1bc4c8f09c12e305521a --- /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 manager 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-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md new file mode 100644 index 0000000000000000000000000000000000000000..6adaa00f48cfb7f2e685841e013e3d719bc58548 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -0,0 +1,424 @@ +# Data Share Result Set + +The **DataShareResultSet** module provides methods for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. + +>**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 + +```ts +import DataShareResultSet from '@ohos.data.DataShareResultSet'; +``` + +## How to Use + +You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShareResultSet** object. + +```ts +import dataShare from '@ohos.data.dataShare'; +import dataSharePredicates from '@ohos.data.dataSharePredicates' + +let dataShareHelper; +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +await dataShare.createDataShareHelper(this.context, uri, (err, data) => { + if (err != undefined) { + console.info("createDataShareHelper fail, error message : " + err); + } else { + console.info("createDataShareHelper end, data : " + data); + dataShareHelper = data; + } +}); + +let columns = ["*"]; +let da = new dataSharePredicates.DataSharePredicates(); +let resultSet; +da.equalTo("name", "ZhangSan"); +dataShareHelper.query(uri, da, columns).then((data) => { + console.log("query end, data : " + data); + resultSet = data; +}).catch((err) => { + console.log("query fail, error message : " + err); +}); +``` + +## Attributes + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +| Name | Type | Mandatory| Description | +| ----------- | ------------- | ---- | ------------------------ | +| columnNames | Array<string> | Yes | Names of all columns in the result set. | +| columnCount | number | Yes | Number of columns in the result set. | +| rowCount | number | Yes | Number of rows in the result set. | +| isClosed | boolean | Yes | Whether the result set is closed.| + +## goToFirstRow + +goToFirstRow(): boolean + +Moves to the first row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| :------ | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```ts +let isGoTOFirstRow = resultSet.goToFirstRow(); +console.info('resultSet.goToFirstRow: ' + isGoTOFirstRow); +``` + +## goToLastRow + +goToLastRow(): boolean + +Moves to the last row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```ts +let isGoToLastRow = resultSet.goToLastRow(); +console.info('resultSet.goToLastRow: ' + isGoToLastRow); +``` + +## goToNextRow + +goToNextRow(): boolean + +Moves to the next row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```ts +let isGoToNextRow = resultSet.goToNextRow(); +console.info('resultSet.goToNextRow: ' + isGoToNextRow); +``` + +## goToPreviousRow + +goToPreviousRow(): boolean + +Moves to the previous row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```ts +let isGoToPreviousRow = resultSet.goToPreviousRow(); +console.info('resultSet.goToPreviousRow: ' + isGoToPreviousRow); +``` + +## goTo + +goTo(offset:number): boolean + +Moves based on the specified offset. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| Description | +| ---------- | -------- | -------- | ------------------------------------------------------------ | +| offset | number | Yes | Offset relative to the current 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** + +```ts +let goToNum = 1; +let isGoTo = resultSet.goTo(goToNum); +console.info('resultSet.goTo: ' + isGoTo); +``` + +## goToRow + +goToRow(position: number): boolean + +Moves to the specified row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| Description | +| ---------- | -------- | -------- | ------------------------ | +| position | number | Yes | Destination position to move.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```ts +let goToRowNum = 2 +let isGoToRow = resultSet.goToRow(goToRowNum); +console.info('resultSet.goToRow: ' + isGoToRow); +``` + +## getBlob + +getBlob(columnIndex: number): Uint8Array + +Obtains the value in the specified column in the current row as a byte array. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name** | **Type**| **Mandatory**| Description | +| ----------- | -------- | -------- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ---------- | -------------------------------- | +| Uint8Array | Value obtained.| + +**Example** + +```ts +let columnIndex = 1 +let goToFirstRow = resultSet.goToFirstRow(); +let getBlob = resultSet.getBlob(columnIndex); +console.info('resultSet.getBlob: ' + getBlob); +``` + +## getString + +getString(columnIndex: number): *string* + +Obtains the value in the specified column in the current row as a string. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name** | **Type**| **Mandatory**| Description | +| ----------- | -------- | -------- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | Value obtained.| + +**Example** + +```ts +let columnIndex = 1 +let goToFirstRow = resultSet.goToFirstRow(); +let getString = resultSet.getString(columnIndex); +console.info('resultSet.getString: ' + getString); +``` + +## getLong + +getLong(columnIndex: number): number + +Obtains the value in the specified column in the current row as a long integer. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name** | **Type**| **Mandatory**| Description | +| ----------- | -------- | -------- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Value obtained.| + +**Example** + +```ts +let columnIndex = 1 +let goToFirstRow = resultSet.goToFirstRow(); +let getLong = resultSet.getLong(columnIndex); +console.info('resultSet.getLong: ' + getLong); +``` + +## getDouble + +getDouble(columnIndex: number): number + +Obtains the value in the specified column in the current row as a double-precision floating-point number. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name** | **Type**| **Mandatory**| Description | +| ----------- | -------- | -------- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| number | Value obtained.| + +**Example** + +```ts +let columnIndex = 1 +let goToFirstRow = resultSet.goToFirstRow(); +let getDouble = resultSet.getDouble(columnIndex); +console.info('resultSet.getDouble: ' + getDouble); +``` + +## close + +close(): void + +Closes this result set. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Example** + +```ts +resultSet.close(); +``` + +## getColumnIndex + +getColumnIndex(columnName: string): number + +Obtains the column index based on the column name. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| Description | +| ---------- | -------- | -------- | -------------------------- | +| columnName | string | Yes | Column name.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Column index obtained.| + +**Example** + +```ts +let ColumnName = "name" +let getColumnIndex = resultSet.getColumnIndex(ColumnName) +console.info('resultSet.getColumnIndex: ' + getColumnIndex); +``` + +## getColumnName + +getColumnName(columnIndex: number): *string* + +Obtains the column name based on the column index. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name** | **Type**| **Mandatory**| Description | +| ----------- | -------- | -------- | -------------------------- | +| columnIndex | number | Yes | Column index.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Column name obtained.| + +**Example** + +```ts +let columnIndex = 1 +let getColumnName = resultSet.getColumnName(columnIndex) +console.info('resultSet.getColumnName: ' + getColumnName); +``` + +## getDataType + +getDataType(columnIndex: number): DataType + +Obtains the data type based on the specified column index. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| **Name** | **Type**| **Mandatory**| Description | +| ----------- | -------- | -------- | -------------------------- | +| columnIndex | number | Yes | Column index.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------ | +| [DataType](#datatype) | Data type obtained.| + +**Example** + +```ts +let columnIndex = 1; +let getDataType = resultSet.getDataType(columnIndex); +console.info('resultSet.getDataType: ' + getDataType); +``` + +## DataType + +Enumerates the data types. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +| Name | Value| Description | +| ----------- | ------ | -------------------- | +| TYPE_NULL | 0 | Null. | +| TYPE_LONG | 1 | Long integer. | +| TYPE_DOUBLE | 2 | Double-precision floating-point number.| +| TYPE_STRING | 3 | String.| +| TYPE_BLOB | 4 | Byte array.| diff --git a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md new file mode 100644 index 0000000000000000000000000000000000000000..dc239c35cbe017f7c5edc0a9fd8ff1bd74b3c366 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md @@ -0,0 +1,37 @@ +# Value Bucket + +The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. + +>**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 + +```ts +import { ValueType } from '@ohos.data.ValuesBucket'; +import { ValuesBucket } from '@ohos.data.ValuesBucket'; +``` + +## ValueType + +Enumerates the value types allowed by the database. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +| Type | Description | +| ------- | -------------------- | +| number | The value is a number. | +| string | The value is a string.| +| boolean | The value is of Boolean type.| + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +| 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 new file mode 100644 index 0000000000000000000000000000000000000000..c3b59a85ab9e2945a8375a61b44c7e45c5d1c385 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -0,0 +1,932 @@ +# Data Sharing + +The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. + +>**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 + +```ts +import dataShare from '@ohos.data.dataShare' +``` + + +## dataShare.createDataShareHelper + +createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void + +Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | [Context](js-apis-application-context.md#context) | Yes | Context of an application. | +| uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | +| callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' + +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +let dataShareHelper; +dataShare.createDataShareHelper(this.context, uri, (err, data) => { + if (err != undefined) { + console.info("createDataShareHelper failed, error message : " + err); + } else { + console.info("createDataShareHelper succeed, data : " + data); + dataShareHelper = data; + } +}); +``` + +## dataShare.createDataShareHelper + +createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper> + +Creates a **DataShareHelper** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------- | ---- | ------------------------------ | +| context | [Context](js-apis-application-context.md#context) | Yes | Context of an application. | +| uri | string | Yes | URI of the server application to connect.| + +**Return value** + +| Type | Description | +| -------------------------------------------------- | -------------------------------------- | +| Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' + +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +let dataShareHelper; +dataShare.createDataShareHelper(this.context, uri).then((data) => { + console.info("createDataShareHelper succeed, data : " + data); + dataShareHelper = data; +}).catch((err) => { + console.info("createDataShareHelper failed, error message : " + err); +}) +``` + +## DataShareHelper + +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 + +openFile(uri: string, mode: string, callback: AsyncCallback<number>): void + +Opens a file. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------- | +| uri | string | Yes | URI of the file to open. | +| mode | string | Yes | File open mode.
**r** means to open a file for reading; **w** means to open a file for writing (erasing any data in the file); **wa** means to open a file in append mode for writing at the end of the file; **rw** means to open a file for both reading and writing.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the file descriptor. Otherwise, **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.openFile(uri, "rwt", (err, data) => { + if (err != undefined) { + console.info("openFile failed, error message : " + err); + }else { + console.info("openFile succeed, data : " + data); + let fd = data; + } +}); +``` + +### openFile + +openFile(uri: string, mode: string): Promise<number> + +Opens a file. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------------------------------------------------------ | +| uri | string | Yes | URI of the file to open. | +| mode | string | Yes | File open mode.
**r** means to open a file for reading; **w** means to open a file for writing (erasing any data in the file); **wa** means to open a file in append mode for writing at the end of the file; **rw** means to open a file for both reading and writing.| + +**Return value** + +| Type | Description | +| --------------- | ---------------- | +| Promise<number> | Promise used to return the file descriptor.| + +**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); + let fd = data; +}).catch((err) => { + console.info("openFile failed, error message : " + err); +}) +``` + +### on('dataChange') + +on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void + +Subscribes to changes of the specified data. After an observer is registered, the subscriber will receive a notification when the change notification is triggered (the **notifyChange()** method is called). This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.| +| uri | string | Yes | URI of the data.| +| callback | AsyncCallback<void> | Yes | Called when the change notification is triggered. In this case, **err** is **undefined**. Otherwise, it is not called or **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +function onCallback() { + console.info("**** Observer on callback ****"); +} +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.on("dataChange", uri, onCallback); +``` + +### off('dataChange') + +off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void + +Unsubscribes from the changes of the specified data. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| +| uri | string | Yes | URI of the data.| +| callback | AsyncCallback<void> | No | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +function offCallback() { + console.info("**** Observer off callback ****"); +} +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.off("dataChange", uri, offCallback); +``` + +### insert + +insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void + +Inserts a single data record into the database. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| uri | string | Yes | URI of the data to insert. | +| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the index of the inserted data record. Otherwise, **err** is an error object.
The data index is not returned if the APIs of the database in use, for example, the key-value database (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": "rose", + "age": 22, + "salary": 200.5, +} +dataShareHelper.insert(uri, valueBucket, (err, data) => { + if (err != undefined) { + console.log("insert failed, error message : " + err); + }else{ + console.log("insert succeed, data : " + data); + } +}); +``` + +### insert + +insert(uri: string, value: ValuesBucket): Promise<number> + +Inserts a single data record into the database. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | +| uri | string | Yes | URI of the data to insert. | +| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| + +**Return value** + +| 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 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", + "age": 221, + "salary": 20.5, +} +dataShareHelper.insert(uri, valueBucket).then((data) => { + console.log("insert succeed, data : " + data); +}).catch((err) => { + console.log("insert failed, error message : " + err); +}); +``` + +### delete + +delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void + +Deletes one or more data records from the database. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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 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"); +let da = new dataSharePredicates.DataSharePredicates(); +da.equalTo("name", "ZhangSan"); +dataShareHelper.delete(uri, da, (err, data) => { + if (err != undefined) { + console.log("delete failed, error message : " + err); + }else{ + console.log("delete succeed, data : " + data); + } +}); +``` + +### delete + +delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promise<number> + +Deletes one or more data records from the database. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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 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 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"); +let da = new dataSharePredicates.DataSharePredicates(); +da.equalTo("name", "ZhangSan"); +dataShareHelper.delete(uri, da).then((data) => { + console.log("delete succeed, data : " + data); +}).catch((err) => { + console.log("delete failed, error message : " + err); +}); +``` + +### query + +query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void + +Queries data in the database. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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**.| +| 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"); +let columns = ["*"]; +let da = new dataSharePredicates.DataSharePredicates(); +da.equalTo("name", "ZhangSan"); +dataShareHelper.query(uri, da, columns, (err, data) => { + if (err != undefined) { + console.log("query failed, error message : " + err); + }else{ + console.log("query succeed, rowCount : " + data.rowCount); + } +}); +``` + +### query + +query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>): Promise<DataShareResultSet> + +Queries data in the database. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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**.| +| columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Promise used to return the result set obtained.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +import dataSharePredicates from '@ohos.data.dataSharePredicates' + +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +let columns = ["*"]; +let da = new dataSharePredicates.DataSharePredicates(); +da.equalTo("name", "ZhangSan"); +dataShareHelper.query(uri, da, columns).then((data) => { + console.log("query succeed, rowCount : " + data.rowCount); +}).catch((err) => { + console.log("query failed, error message : " + err); +}); +``` + +### update + +update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void + +Updates data in the database. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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 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 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"); +let da = new dataSharePredicates.DataSharePredicates(); +da.equalTo("name", "ZhangSan"); +const va = { + "name": "roe1", + "age": 21, + "salary": 20.5, + +} +dataShareHelper.update(uri, da, va, (err, data) => { + if (err != undefined) { + console.log("update failed, error message : " + err); + }else{ + console.log("update succeed, data : " + data); + } +}); +``` + +### update + +update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket): Promise<number> + +Updates data in the database. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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 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 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"); +let da = new dataSharePredicates.DataSharePredicates(); +da.equalTo("name", "ZhangSan"); +const va = { + "name": "roe1", + "age": 21, + "salary": 20.5, + +} +dataShareHelper.update(uri, da, va).then((data) => { + console.log("update succeed, data : " + data); +}).catch((err) => { + console.log("update failed, error message : " + err); +}); +``` + +### batchInsert + +batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void + +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. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| 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 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,}, + {"name": "roe13", "age": 21, "salary": 20.5,}) +dataShareHelper.batchInsert(uri, vbs, (err, data) => { + if (err != undefined) { + console.log("batchInsert failed, error message : " + err); + }else{ + console.log("batchInsert succeed, data : " + data); + } +}); +``` + +### batchInsert + +batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number> + +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. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------ | +| uri | string | Yes | URI of the data to insert.| +| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | + +**Return value** + +| 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 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,}, + {"name": "roe13", "age": 21, "salary": 20.5,}) +dataShareHelper.batchInsert(uri, vbs).then((data) => { + console.log("batchInsert succeed, data : " + data); +}).catch((err) => { + console.log("batchInsert failed, error message : " + err); +}); +``` + +### getType + +getType(uri: string, callback: AsyncCallback<string>): void + +Obtains the Multipurpose Internet Mail Extensions (MIME) type of the specified data. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | --------------------------------------------- | +| uri | string | Yes | URI of the data. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the MIME type obtained. Otherwise, **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.getType(uri, (err, data)=>{ + if (err != undefined) { + console.log("getType failed, error message : " + err); + }else{ + console.log("getType succeed, data : " + data); + let result = data; + } +}); +``` + +### getType + +getType(uri: string): Promise<string> + +Obtains the MIME type of the specified data. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | -------------------- | +| uri | string | Yes | URI of the data.| + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------- | +| Promise<string> | Promise used to return the MIME type obtained.| + +**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); +}).catch((err) => { + console.log("getType failed, error message : " + err); +}); +``` + +### getFileTypes + +getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void + +Obtains the supported MIME types. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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**: 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) => { + if (err != undefined) { + console.log("getFileTypes failed, error message : " + err); + }else{ + console.log("getFileTypes succeed, data : " + data); + } +}); +``` + +### getFileTypes + +getFileTypes(uri: string, mimeTypeFilter: string): Promise<Array<string>> + +Obtains the supported MIME types. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| 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**: Obtain the MIMEs with the subtype of **jpg**.| + +**Return value** + +| Type | Description | +| ------------------------ | ------------------------ | +| Promise<Array<string>> | Promise used to return the MIME types obtained.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +let mimeTypeFilter = "image/*"; +dataShareHelper.getFileTypes(uri, mimeTypeFilter).then((data) => { + console.log("getFileTypes succeed, data : " + data); +}).catch((err) => { + console.log("getFileTypes failed, error message : " + err); +}); +``` + +### normalizeUri + +normalizeUri(uri: string, callback: AsyncCallback<string>): void + +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. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------------------------- | +| uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the normalized URI (if **null** is returned, URI normalization is not supported). Otherwise, **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.normalizeUri(uri, (err, data) => { + if (err != undefined) { + console.log("normalizeUri failed, error message : " + err); + }else{ + console.log("normalizeUri = " + data); + } +}); +``` + +### normalizeUri + +normalizeUri(uri: string): Promise<string> + +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. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ----------------------------------------- | +| uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------------------------------------- | +| Promise<string> | Promise used to return the result. If URI normalization is supported, the normalized URI is returned. Otherwise, **null** is returned.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.normalizeUri(uri).then((data) => { + console.log("normalizeUri = " + data); +}).catch((err) => { + console.log("normalizeUri failed, error message : " + err); +}); +``` + +### denormalizeUri + +denormalizeUri(uri: string, callback: AsyncCallback<string>): void + +Denormalizes a URI. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | --------------------------------------------------- | +| uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the URI obtained. If the original URI is returned, denormalization is not required. If **null** is returned, denormalization is not supported. If the operation fails, **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.denormalizeUri(uri, (err, data) => { + if (err != undefined) { + console.log("denormalizeUri failed, error message : " + err); + }else{ + console.log("denormalizeUri = " + data); + } +}); +``` + +### denormalizeUri + +denormalizeUri(uri: string): Promise<string> + +Denormalizes a URI. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------------------------------------- | +| uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.| + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------------- | +| Promise<string> | Promise used to return the result. If the denormalization is successful, the URI obtained is returned. If no operation is required, the original URI is returned. If denormalization is not supported, **null** is returned.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.denormalizeUri(uri).then((data) => { + console.log("denormalizeUri = " + data); +}).catch((err) => { + console.log("denormalizeUri failed, error message : " + err); +}); +``` + +### notifyChange + +notifyChange(uri: string, callback: AsyncCallback<void>): void + +Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| uri | string | Yes | URI of the data.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```ts +import Ability from '@ohos.application.Ability' +let uri = ("datashare:///com.samples.datasharetest.DataShare"); +dataShareHelper.notifyChange(uri, () => { + console.log("***** notifyChange *****"); +}); +``` + +### notifyChange + +notifyChange(uri: string): Promise<void> + +Notifies the registered observer of data changes. This API uses a promise to return the result. + +This API can be used only in the stage model. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | -------------------- | +| uri | string | Yes | URI of the data.| + +**Return value** + +| Type | Description | +| -------------- | --------------------- | +| Promise<void> | Promise that returns no value.| + +**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-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md new file mode 100644 index 0000000000000000000000000000000000000000..16c1c1c7b622782a577719bae992d10b1f4634a0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -0,0 +1,861 @@ +# Data Share Predicates + +You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data with **DataShare**. + +>**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 + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +``` + +## equalTo + +equalTo(field: string, value: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value equal to the specified value. + +Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +``` + +## notEqualTo + +notEqualTo(field: string, value: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value not equal to the specified value. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.notEqualTo("NAME", "Rose") +``` + +## beginWrap + +beginWrap(): DataSharePredicates + +Adds a left parenthesis to this **DataSharePredicates**. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ---------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object with a left parenthesis.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +## endWrap + +endWrap(): DataSharePredicates + +Adds a right parenthesis to this **DataSharePredicates** object. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ---------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object with a right parenthesis.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +## or + +or(): DataSharePredicates + +Adds the OR condition to this **DataSharePredicates** object. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ---------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object with the OR condition.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "lisi") + .or() + .equalTo("NAME", "Rose") +``` + +## and + +and(): DataSharePredicates + +Adds the AND condition to this **DataSharePredicates** object. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | ---------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object with the AND condition.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "lisi") + .and() + .equalTo("SALARY", 200.5) +``` + +## contains + +contains(field: string, value: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match the string that contains the specified value. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value contained in the string.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.contains("NAME", "os") +``` + +## beginsWith + +beginsWith(field: string, value: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match a string that starts with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Start value of the string.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.beginsWith("NAME", "os") +``` + +## endsWith + +endsWith(field: string, value: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match a string that ends with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | End value of the string.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.endsWith("NAME", "os") +``` + +## isNull + +isNull(field: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field whose value is null. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.isNull("NAME") +``` + +## isNotNull + +isNotNull(field: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field whose value is not null. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.isNotNull("NAME") +``` + +## like + +like(field: string, value: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match a string that is similar to the specified value. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.like("NAME", "%os%") +``` + +## unlike + +unlike(field: string, value: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match a string that is not similar to the specified value. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.unlike("NAME", "%os%") +``` + +## glob + +glob(field: string, value: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match the specified string. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified string.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.glob("NAME", "?h*g") +``` + +## between + +between(field: string, low: ValueType, high: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value within the specified range. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------------- | ---- | ------------------------ | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.between("AGE", 10, 50) +``` + +## notBetween + +notBetween(field: string, low: ValueType, high: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value out of the specified range. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------------- | ---- | ------------------------ | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.notBetween("AGE", 10, 50) +``` + +## greaterThan + +greaterThan(field: string, value: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than the specified value. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.greaterThan("AGE", 10) +``` + +## lessThan + +lessThan(field: string, value: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than the specified value. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.lessThan("AGE", 50) +``` + +## greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.greaterThanOrEqualTo("AGE", 10) +``` + +## lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: ValueType): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.lessThanOrEqualTo("AGE", 50) +``` + +## orderByAsc + +orderByAsc(field: string): DataSharePredicates + +Sets a **DataSharePredicates** object that sorts the values in a column in ascending order. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.orderByAsc("AGE") +``` + +## orderByDesc + +orderByDesc(field: string): DataSharePredicates + +Sets a **DataSharePredicates** object that sorts the values in a column in descending order. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.orderByDesc("AGE") +``` + +## distinct + +distinct(): DataSharePredicates + +Sets a **DataSharePredicates** object to filter out duplicate records. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose").distinct() +``` + +## limit + +limit(total: number, offset: number): DataSharePredicates + +Sets a **DataSharePredicates** object to specify the number of results and the start position. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------- | +| total | number | Yes | Number of results. | +| offset | number | Yes | Start position.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose").limit(10, 3) +``` + +## groupBy + +groupBy(fields: Array<string>): DataSharePredicates + +Sets a **DataSharePredicates** object to group the records according to the specified parameters. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | -------------------- | +| fields | Array<string> | Yes | Names of the columns to group.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.groupBy(["AGE", "NAME"]) +``` + +## indexedBy + +indexedBy(field: string): DataSharePredicates + +Sets a **DataSharePredicates** object to specify the index column. Currently, only the RDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| field | string | Yes | Name of the index column.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.indexedBy("SALARY_INDEX") +``` + +## in + +in(field: string, value: Array<ValueType>): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **Array** and value within the specified range. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | --------------------------------------- | +| field | string | Yes| Column name in the database table. | +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.in("AGE", [18, 20]) +``` + +## notIn + +notIn(field: string, value: Array<ValueType>): DataSharePredicates + +Sets a **DataSharePredicates** object to match the field with data type **Array** and value out of the specified range. + +Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | --------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.notIn("NAME", ["Lisa", "Rose"]) +``` + +## prefixKey + +prefixKey(prefix: string): DataSharePredicates + +Sets a **DataSharePredicates** object to match a field with the specified key prefix. Currently, only the KVDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| prefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.prefixKey("NAME") +``` + +## inKeys + +inKeys(keys: Array<string>): DataSharePredicates + +Sets a **DataSharePredicates** object to match the fields whose keys are within the given range. Currently, only the KVDB supports this **DataSharePredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------ | +| inKeys | Array<string> | Yes | Array of the keys to match.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | -------------------------- | +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| + +**Example** + +```ts +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.inKeys(["Lisa", "Rose"]) +``` diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index a58a4583a1db69548342f0c63b8a13aec0dfb623..83875a6edb8aa2395b8750e70fb86b7fa596b03d 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,6 +1,6 @@ # Distributed Data Object -Provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. +The distributedDataObject module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. > **NOTE**
> @@ -23,9 +23,9 @@ Creates a distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| source | object | Yes| Attribute of the distributed data object to create.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | source | object | Yes| Attribute of the distributed data object to create.| **Return value** | Type| Description| @@ -33,12 +33,11 @@ Creates a distributed data object. | [DistributedObject](#distributedobject) | Distributed data object created.| **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject'; - // Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, - parent:{mother:"jack mom",father:"jack Dad"}}); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +``` ## distributedObject.genSessionId @@ -50,15 +49,15 @@ Creates a random session ID. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Return value** -| Type| Description| -| -------- | -------- | -| string | Session ID created.| + | Type| Description| + | -------- | -------- | + | string | Session ID created.| **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject'; - var sessionId = distributedObject.genSessionId(); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var sessionId = distributedObject.genSessionId(); +``` ## SaveSuccessResponse9+ @@ -98,27 +97,26 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, - parent:{mother:"jack mom",father:"jack Dad"}}); - // Add g_object to the distributed network. - g_object.setSessionId(distributedObject.genSessionId()); - // Remove g_object from the distributed network. - g_object.setSessionId(""); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId()); +// Remove g_object from the distributed network. +g_object.setSessionId(""); +``` ### on('change') @@ -130,15 +128,15 @@ Subscribes to the changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| -| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.changeCallback = (sessionId, changeData) => { console.info("change" + sessionId); if (changeData != null && changeData != undefined) { @@ -159,16 +157,16 @@ Unsubscribes from the changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| -| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // Unregister the specified data change callback. g_object.off("change", globalThis.changeCallback); // Unregister all data change callbacks. @@ -184,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| -| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| + | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** ```js @@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject'; globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); g_object.on("status", globalThis.statusCallback); ``` @@ -209,16 +207,16 @@ Unsubscribes from the status change (online or offline) of this distributed data **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| -| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| + | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); globalThis.statusCallback = (sessionId, networkId, status) => { globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } @@ -245,24 +243,24 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| -| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| + | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** - - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.save("local", (result)=>{ - console.log("save callback"); - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local", (status, result)=>{ + console.log("save status = " + status); + console.log("save callback"); + console.info("save sessionId: " + result.sessionId); + console.info("save version: " + result.version); + console.info("save deviceId: " + result.deviceId); +}); +``` ### save9+ @@ -281,31 +279,31 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | - **Return value** +**Return value** -| Type| Description| -| -------- | -------- | -| Promise<[SaveSuccessResponse](#savesuccessresponse)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| + | Type| Description| + | -------- | -------- | + | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.save("local").then((result)=>{ - console.log("save callback"); - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); - }, ()=>{ - console.error("save failed"); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.save("local").then((result)=>{ + console.log("save callback"); + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, ()=>{ + console.error("save failed"); +}); +``` ### revokeSave9+ @@ -319,20 +317,20 @@ If the object is stored on another device, the data on the local device will be **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.revokeSave((result, data) =>{ - console.log("revokeSave callback"); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.revokeSave((result, data) =>{ + console.log("revokeSave callback"); +}); +``` ### revokeSave9+ @@ -345,22 +343,22 @@ If the object is stored on another device, the data on the local device will be **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject - **Return value** +**Return value** -| Type| Description| -| -------- | -------- | -| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| + | Type| Description| + | -------- | -------- | + | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** - ```ts - import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); - g_object.setSessionId("123456"); - g_object.revokeSave("local").then((result)=>{ - console.log("revokeSave callback"); - console.log("sessionId" + result.sessionId); - }, ()=>{ - console.error("revokeSave failed"); - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +g_object.setSessionId("123456"); +g_object.revokeSave().then((result)=>{ + console.log("revokeSave callback"); + console.log("sessionId" + result.sessionId); +}, ()=>{ + console.error("revokeSave failed"); +}); +``` 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-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 2ae6d7b5a18696850e13d8d088f9a1300561742c..8d18622ce2eb432210858545308e2a607891b1f0 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -1,6 +1,24 @@ # Device Usage Statistics -> **NOTE**
+This module provides APIs for collecting statistics on device usage. + +System applications can call these APIs to implement the following features: + +- Query the usage duration in different time segments, events (foreground, background, start and end of continuous tasks), and the number of notifications, on a per application basis. +- Query statistics about system events (sleep, wakeup, unlock, and screen lock). +- Query the bundle group information of applications, including the invoking application itself. +- Query the idle status of applications, including the invoking application itself. +- Set the bundle group for other applications. +- Register and deregister the callback for application group changes. + +Third-party applications can call these APIs to implement the following features: + +- Query the idle status of the invoking application itself. +- Query the bundle group information of the invoking application itself. +- Query the events of the invoking application itself. + +> **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. @@ -23,7 +41,7 @@ Checks whether the application specified by **bundleName** is in the idle state. | Name | Type | Mandatory | Description | | ---------- | ---------------------------- | ---- | ---------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the value of **bundleName** is valid, **null** will be returned.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the value of bundleName is valid, null will be returned.| **Example** @@ -69,7 +87,7 @@ Checks whether the application specified by **bundleName** is in the idle state. ## bundleState.queryAppUsagePriorityGroup -queryAppUsagePriorityGroup(): Promise\ +queryAppUsagePriorityGroup(): Promise<number> Queries the priority group of this application. This API uses a promise to return the result. @@ -79,7 +97,7 @@ Queries the priority group of this application. This API uses a promise to retur | Type | Description | | --------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Promise<number> | Promise used to return the result.| **Example** @@ -93,7 +111,7 @@ bundleState.queryAppUsagePriorityGroup().then( res => { ## bundleState.queryAppUsagePriorityGroup -queryAppUsagePriorityGroup(callback: AsyncCallback\): void +queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void Queries the priority group of this application. This API uses an asynchronous callback to return the result. @@ -103,20 +121,11 @@ Queries the priority group of this application. This API uses an asynchronous ca | Name | Type | Mandatory | Description | | -------- | --------------------- | ---- | -------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| **Example** ```javascript -// Callback with bundleName -bundleState.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { - if(err) { - console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); - } else { - console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); - } -}); -// Callback without bundleName bundleState.queryAppUsagePriorityGroup((err, res) => { if(err) { console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); @@ -523,7 +532,7 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an ## bundleState.queryAppUsagePriorityGroup9+ -queryAppUsagePriorityGroup(bundleName? : string): Promise +queryAppUsagePriorityGroup(bundleName? : string): Promise<number> Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses a promise to return the result. @@ -543,13 +552,14 @@ Queries the priority group of the application specified by **bundleName**. If ** | Type | Description | | --------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Promise<number> | Promise used to return the result.| **Example** ```javascript // Promise with bundleName -bundleState.queryAppUsagePriorityGroup(this.bundleName).then( res => { +let bundleName = "com.ohos.camera"; +bundleState.queryAppUsagePriorityGroup(bundleName).then( res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( err => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); @@ -564,7 +574,7 @@ bundleState.queryAppUsagePriorityGroup().then( res => { ## bundleState.queryAppUsagePriorityGroup9+ -queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback\): void +queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result. @@ -579,13 +589,14 @@ Queries the priority group of the application specified by **bundleName**. If ** | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------------------------------------- | | bundleName | string | No | Bundle name of the target application. If this parameter is not specified, the priority group of the current application is queried.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | **Example** ```javascript // Callback with bundleName -bundleState.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { +let bundleName = "com.ohos.camera"; +bundleState.queryAppUsagePriorityGroup(bundleName, (err, res) => { if(err) { console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); } else { @@ -604,7 +615,7 @@ bundleState.queryAppUsagePriorityGroup((err, res) => { ## bundleState.setBundleGroup9+ -setBundleGroup(bundleName: string, newGroup: GroupType): Promise\ +setBundleGroup(bundleName: string, newGroup: GroupType): Promise<void> Sets the group for the application specified by **bundleName**. This API uses a promise to return the result. @@ -618,22 +629,22 @@ Sets the group for the application specified by **bundleName**. This API uses a | Name | Type | Mandatory | Description | | ---------- | --------- | ---- | ---- | -| bundleName | string | Yes | Bundle name of the target application.| -| newGroup | GroupType | Yes | Application group.| +| bundleName | string | Yes | Bundle name of an application.| +| newGroup | [GroupType](#grouptype) | Yes | Application group.| **Return value** | Type | Description | | ------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** ```javascript -this.bundleName = "com.example.deviceUsageStatistics"; -this.newGroup = stats.GroupType.ACTIVE_GROUP_DAILY; +let bundleName = "com.example.deviceUsageStatistics"; +let newGroup = bundleState.GroupType.ACTIVE_GROUP_DAILY; -bundleState.setBundleGroup(this.bundleName, this.newGroup).then( () => { +bundleState.setBundleGroup(bundleName, newGroup).then( () => { console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.'); }).catch( err => { console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code); @@ -642,7 +653,7 @@ bundleState.setBundleGroup(this.bundleName, this.newGroup).then( () => { ## bundleState.setBundleGroup9+ -setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback\): void +setBundleGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback<void>): void Sets the group for the application specified by **bundleName**. This API uses an asynchronous callback to return the result. @@ -656,17 +667,17 @@ Sets the group for the application specified by **bundleName**. This API uses an | Name | Type | Mandatory | Description | | ---------- | ------------------- | ---- | ------------------------- | -| bundleName | string | Yes | Bundle name of the target application. | -| newGroup | GroupType | Yes | Application group. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| bundleName | string | Yes | Bundle name of an application. | +| newGroup | [GroupType](#grouptype) | Yes | Application group. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```javascript -this.bundleName = "com.example.deviceUsageStatistics"; -this.newGroup = stats.GroupType.ACTIVE_GROUP_DAILY; +let bundleName = "com.example.deviceUsageStatistics"; +let newGroup = bundleState.GroupType.ACTIVE_GROUP_DAILY; -bundleState.setBundleGroup(this.bundleName, this.newGroup, (err) => { +bundleState.setBundleGroup(bundleName, newGroup, (err) => { if(err) { console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); } else { @@ -677,9 +688,9 @@ bundleState.setBundleGroup(this.bundleName, this.newGroup, (err) => { ## bundleState.registerGroupCallBack9+ -registerGroupCallBack(callback: Callback\): Promise\ +registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>): Promise<void> -Registers a callback for application group changes. When an application group of the user changes, **BundleActiveGroupCallbackInfo** is returned to all applications that have registered the callback. This API uses a promise to return the result. +Registers a callback for application group changes. When an application group of the user changes, a **[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)** instance is returned to all applications that have registered the callback. This API uses a promise to return the result. **Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO @@ -689,26 +700,26 @@ Registers a callback for application group changes. When an application group of **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------- | ---- | ----------- | -| callback | Callback\ | Yes | Callback for application group changes.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | Callback<[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)> | Yes | Callback used to return the application group changes.| **Return value** | Type | Description | | ------------- | ----------------------- | -| Promise\ | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** ```javascript let onBundleGroupChanged = (err,res) =>{ console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result changeReason is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result appUsageOldGroup is : ' + res.appUsageOldGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result appUsageNewGroup is : ' + res.appUsageNewGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result changeReason is : ' + res.changeReason); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result bundleName is : ' + res.bundleName); }; bundleState.registerGroupCallBack(onBundleGroupChanged).then( () => { console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.'); @@ -719,9 +730,9 @@ bundleState.registerGroupCallBack(onBundleGroupChanged).then( () => { ## bundleState.registerGroupCallBack9+ -registerGroupCallBack(callback: Callback\, callback: AsyncCallback\): void +registerGroupCallBack(callback: Callback<BundleActiveGroupCallbackInfo>, callback: AsyncCallback<void>): void -Registers a callback for application group changes. When an application group of the user changes, **BundleActiveGroupCallbackInfo** is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result. +Registers a callback for application group changes. When an application group of the user changes, a **[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)** instance is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO @@ -731,21 +742,21 @@ Registers a callback for application group changes. When an application group of **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------- | ---- | ------------- | -| callback | Callback\ | Yes | Callback for application group changes. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | +| callback | Callback<[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)> | Yes | Callback used to return the application group changes. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```javascript let onBundleGroupChanged = (err,res) =>{ console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's changeReason is : ' + res.newGroup); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId); - console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result appUsageOldGroup is : ' + res.appUsageOldGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result appUsageNewGroup is : ' + res.appUsageNewGroup); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result changeReason is : ' + res.changeReason); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE RegisterGroupCallBack result bundleName is : ' + res.bundleName); }; bundleState.registerGroupCallBack(onBundleGroupChanged, (err)=>{ if(err) { @@ -758,7 +769,7 @@ bundleState.registerGroupCallBack(onBundleGroupChanged, (err)=>{ ## bundleState.unRegisterGroupCallBack9+ -unRegisterGroupCallBack(): Promise\ +unRegisterGroupCallBack(): Promise<void> Deregisters the callback for application group changes. This API uses a promise to return the result. @@ -774,7 +785,7 @@ Deregisters the callback for application group changes. This API uses a promise | Type | Description | | ------------- | ------------------------ | -| Promise\ | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** @@ -788,7 +799,7 @@ bundleState.unRegisterGroupCallBack().then( () => { ## bundleState.unRegisterGroupCallBack9+ -unRegisterGroupCallBack(callback: AsyncCallback\): void; +unRegisterGroupCallBack(callback: AsyncCallback<void>): void; Deregisters the callback for application group changes. This API uses an asynchronous callback to return the result. @@ -802,7 +813,7 @@ Deregisters the callback for application group changes. This API uses an asynchr | Name | Type | Mandatory | Description | | -------- | ------------------- | ---- | -------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -870,7 +881,7 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Promise used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result.| **Example** @@ -982,7 +993,7 @@ Provides the FA widget usage information. | Name | Type | Mandatory | Description | | ---------------- | ------ | ---- | ----------- | -| formName | number | Yes | Widget name. | +| formName | string | Yes | Widget name. | | formDimension | number | Yes | Widget dimensions. | | formId | number | Yes | Widget ID. | | formLastUsedTime | number | Yes | Last time when the widget was clicked.| @@ -992,15 +1003,15 @@ Provides the FA widget usage information. Provides the application group changes returned through a callback. -**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup -| Name | Type | Mandatory | Description | -| ---------------- | ------ | ---- | -------- | -| appUsageOldGroup | number | Yes | Application group before the change.| -| appUsageNewGroup | number | Yes | Application group after the change.| -| useId | number | Yes | User ID. | -| changeReason | number | Yes | Reason for the group change. | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------------- | ------ | ---- | ---------------- | +| appUsageOldGroup | number | Yes | Application group before the change.| +| appUsageNewGroup | number | Yes | Application group after the change.| +| userId | number | Yes | User ID. | +| changeReason | number | Yes | Reason for the group change. | +| bundleName | string | Yes | Bundle name of an application. | ## BundleStateInfo @@ -1008,11 +1019,11 @@ Provides the usage duration information of applications. ### Attributes -**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App | Name | Type | Mandatory | Description | | ------------------------ | ------ | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityPrevAccessTime | number | Yes | Last time when the application was used. | | abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. | | id | number | No | User ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| @@ -1029,8 +1040,6 @@ merge(toMerge: BundleStateInfo): void Merges the application usage information that has the same bundle name. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. - **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App **Parameters** @@ -1047,7 +1056,7 @@ Provides information about an application event. | Name | Type | Mandatory | Description | | --------------------- | ------ | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | stateType | number | Yes | Application event type. | | stateOccurredTime | number | Yes | Timestamp when the application event occurs. | | appUsagePriorityGroup | number | No | Usage priority group of the application.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| @@ -1092,7 +1101,7 @@ Enumerates the interval types for querying the application usage duration. | BY_MONTHLY | 3 | The system obtains the application usage duration statistics in the specified time frame on a monthly basis. | | BY_ANNUALLY | 4 | The system obtains the application usage duration statistics in the specified time frame on an annual basis. | -## GroupType +## GroupType9+ Enumerates the application group types. diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index ffbc73ff530a4d8f9ec39fd6e824760df9448644..25cf9ed242f66a0983303065dcea527989444223 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,5 +1,5 @@ # Display -Provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. +The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. > **NOTE** > @@ -14,11 +14,11 @@ import display from '@ohos.display'; ## DisplayState -Provides the state of a display. +Enumerates the display states. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATE_UNKNOWN | 0 | Unknown.| | STATE_OFF | 1 | The display is shut down.| @@ -56,7 +56,7 @@ Describes the attributes of a display. getDefaultDisplay(callback: AsyncCallback<Display>): void -Obtains the default display object. +Obtains the default display object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -82,7 +82,7 @@ Obtains the default display object. getDefaultDisplay(): Promise<Display> -Obtains the default display object. +Obtains the default display object. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -103,11 +103,31 @@ Obtains the default display object. }); ``` +## display.getDefaultDisplaySync9+ + +getDefaultDisplaySync(): Display + +Obtains the default display object. This API returns the result synchronously. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------------------| ----------------------------------------------| +| [Display](#display) | Default display object.| + +**Example** + +```js +var displayClass = display.getDefaultDisplaySync(); +``` + ## display.getAllDisplay getAllDisplay(callback: AsyncCallback<Array<Display>>): void -Obtains all the display objects. +Obtains all display objects. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -133,7 +153,7 @@ Obtains all the display objects. getAllDisplay(): Promise<Array<Display>> -Obtains all the display objects. +Obtains all display objects. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -158,15 +178,15 @@ Obtains all the display objects. on(type: 'add'|'remove'|'change', callback: Callback<number>): void -Enables listening. +Subscribes to display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Listening type. The available values are as follows:
- **add**: listening for whether a display is added
- **remove**: listening for whether a display is removed
- **change**: listening for whether a display is changed| - | callback | Callback<number> | Yes| Callback used to return the ID of the display.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| +| callback | Callback<number> | Yes| Callback used to return the ID of the display.| **Example** ```js @@ -181,14 +201,14 @@ Enables listening. off(type: 'add'|'remove'|'change', callback?: Callback<number>): void -Disables listening. +Unsubscribes from display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Listening type. The available values are as follows:
- **add**: listening for whether a display is added
- **remove**: listening for whether a display is removed
- **change**: listening for whether a display is changed| + | type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| | callback | Callback<number> | No| Callback used to return the ID of the display.| **Example** 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 bc64da83d9a829da97b02be79a94804df498a670..dc674978d2c4b9491e860b13f1720787380cc53e 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -2,7 +2,7 @@ The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. -> ![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. diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index 154bba75b0c8172459b41725add26ce2fa96db34..bad85aee529e6f5b2bff68cd79fd4172c53e7969 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -489,7 +489,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) let kvManager; try { console.log('GetAllKVStoreId'); - kvManager.getAllKVStoreId('apppId').then((data) => { + kvManager.getAllKVStoreId('appId').then((data) => { console.log('getAllKVStoreId success'); console.log('size = ' + data.length); }).catch((err) => { @@ -775,7 +775,7 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeeed.'); + console.log('getResultSet succeeded.'); resultSet = result; }).catch((err) => { console.log('getResultSet failed: ' + err); @@ -2453,10 +2453,10 @@ try { 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,entrys) { + kvStore.getEntries('batch_test_string_key', function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); }catch(e) { @@ -2505,7 +2505,7 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entrys) => { + kvStore.getEntries('batch_test_string_key').then((entries) => { console.log('getEntries success'); console.log('PutBatch ' + JSON.stringify(entries)); }).catch((err) => { @@ -3245,10 +3245,10 @@ try { } kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - kvStore.getEntries('batch_test_number_key', function (err,entrys) { + kvStore.getEntries('batch_test_number_key', function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); }catch(e) { @@ -3297,12 +3297,12 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entrys) => { + kvStore.getEntries('batch_test_string_key').then((entries) => { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); - console.log('entrys[0].value.value: ' + entrys[0].value.value); + 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)); }); @@ -3353,10 +3353,10 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - kvStore.getEntries(query, function (err,entrys) { + kvStore.getEntries(query, function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); console.log('GetEntries success'); @@ -3409,7 +3409,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entrys) => { + kvStore.getEntries(query).then((entries) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -3650,7 +3650,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultsetsup8sup)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| **Example** @@ -4134,7 +4134,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail | ----- | ------ | ---- | ----------------------- | | 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](#querysup8sup) | Yes |**Query** object to match. | +| query |[Query](#query8) | Yes |**Query** object to match. | | delayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -4252,7 +4252,7 @@ try { console.log('getSecurityLevel success'); }); }catch(e) { - console.log('GetSecurityLeve e ' + e); + console.log('GetSecurityLevel e ' + e); } ``` @@ -4282,7 +4282,7 @@ try { console.log('getSecurityLevel fail ' + JSON.stringify(err)); }); }catch(e) { - console.log('GetSecurityLeve e ' + e); + console.log('GetSecurityLevel e ' + e); } ``` @@ -4412,10 +4412,10 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { + kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); }catch(e) { @@ -4465,12 +4465,12 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { + kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); - console.log('entrys[0].value.value: ' + entrys[0].value.value); + 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)); }); @@ -4522,10 +4522,10 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - kvStore.getEntries(query, function (err,entrys) { + kvStore.getEntries(query, function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); console.log('GetEntries success'); @@ -4578,7 +4578,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entrys) => { + kvStore.getEntries(query).then((entries) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -4633,10 +4633,10 @@ try { var query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query, function (err,entrys) { + kvStore.getEntries('localDeviceId', query, function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }) }); console.log('GetEntries success'); @@ -4691,7 +4691,7 @@ try { var query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query).then((entrys) => { + kvStore.getEntries('localDeviceId', query).then((entries) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); diff --git a/en/application-dev/reference/apis/js-apis-document.md b/en/application-dev/reference/apis/js-apis-document.md index 458685119e17635f1b5af60e27910808bf8f99d6..3fbdc4f46c5e28f74743575a12f23fc138350f58 100644 --- a/en/application-dev/reference/apis/js-apis-document.md +++ b/en/application-dev/reference/apis/js-apis-document.md @@ -14,21 +14,21 @@ import document from '@ohos.document'; choose(types? : string[]): Promise<string> -Chooses a file of the specified type using the file manager. This API uses a promise to return the result. +Chooses files of the specified types using the file manager. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileService **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------------------- | - | types | string[] | No | Type of the file to choose.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| types | string[] | No | Types of the files to choose. | **Return value** - | Type | Description | - | --------------------- | -------------- | - | Promise<string> | Promise used to return the result. An error code is returned.| +| Type | Description | +| --------------------- | -------------- | +| Promise<string> | Promise used to return the result. An error code is returned.| **Example** @@ -46,9 +46,9 @@ Chooses a file using the file manager. This API uses an asynchronous callback to **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| **Example** @@ -62,16 +62,16 @@ Chooses a file using the file manager. This API uses an asynchronous callback to choose(types:string[], callback:AsyncCallback<string>): void -Chooses a file using the file manager. This API uses an asynchronous callback to return the result. +Chooses files using the file manager. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | types | string[] | No | Type of the file to choose.| - | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| types | string[] | No | Types of the files to choose.| +| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| **Example** @@ -93,16 +93,16 @@ Opens a file. This API uses a promise to return the result. **Parameters** - | Name| Type | Mandatory| Description | - | ---- | ------ | ---- | ---------------------------- | - | uri | string | Yes | URI of the file to open.| - | type | string | Yes | Type of the file to open.| +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ---------------------------- | +| uri | string | Yes | URI of the file to open.| +| type | string | Yes | Type of the file to open.| **Return value** - | Type | Description | - | --------------------- | ------------ | - | Promise<void> | Promise used to return the result. An error code is returned.| +| Type | Description | +| --------------------- | ------------ | +| Promise<void> | Promise used to return the result. An error code is returned.| **Example** @@ -122,11 +122,11 @@ Opens a file. This API uses an asynchronous callback to return the result. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | uri | string | Yes | URI of the file to open.| - | type | string | Yes | Type of the file to open.| - | callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| uri | string | Yes | URI of the file to open.| +| type | string | Yes | Type of the file to open.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | **Example** 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 133276e077b78d22fb2c06222ba067611f9ee3c7..6e970785345a27be2c2c4d1051f87c13c4d8533f 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -16,6 +16,7 @@ import fileio from '@ohos.fileio'; ## Guidelines Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: + ```js import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); @@ -353,58 +354,11 @@ Synchronously closes a file. **Example** ```js + let fd = fileio.openSync(path); fileio.closeSync(fd); ``` -## fileio.close7+ - -close(): Promise<void> - -Closes the stream. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Return value** - - | Type | Description | - | ------------------- | ---------------------------- | - | Promise<void> | Promise that returns no value.| - -**Example** - - ```js - fileio.close().then(function(){ - console.info("File stream closed"); - }).catch(function(err){ - console.info("Failed to close the file stream. Error:"+ err); - }); - ``` - - -## fileio.close7+ - -close(callback: AsyncCallback<void>): void - -Closes the stream. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - - | Name | Type | Mandatory | Description | - | -------- | ------------------------- | ---- | ------------- | - | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| - -**Example** - - ```js - fileio.close(function(err){ - // Do something. - }); - ``` - - ## fileio.copyFile copyFile(src:string | number, dest:string | number, mode?:number):Promise<void> @@ -430,6 +384,8 @@ Copies a file. This API uses a promise to return the result. **Example** ```js + let src = path; + let dest = src + 'tgt'; fileio.copyFile(src, dest).then(function(){ console.info("File copied"); }).catch(function(err){ @@ -458,6 +414,8 @@ Copies a file. This API uses an asynchronous callback to return the result. **Example** ```js + let src = path; + let dest = src + 'tgt'; fileio.copyFile(src, dest, function (err) { // Do something. }); @@ -483,6 +441,8 @@ Synchronously copies a file. **Example** ```js + let src = path; + let dest = src + 'tgt'; fileio.copyFileSync(src, dest); ``` @@ -957,7 +917,7 @@ Writes data into a file. This API uses a promise to return the result. ```js let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world").then(function(number){ - console.info("Data written to file and size is:"+ number); + console.info("Data written to the file. Size is:"+ number); }).catch(function(err){ console.info("Failed to write data to the file. Error:"+ err); }); @@ -992,7 +952,7 @@ Writes data into a file. This API uses an asynchronous callback to return the re let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (bytesWritten) { - console.info("Data written to file and size is:"+ bytesWritten); + console.info("Data written to the file. Size is:"+ bytesWritten); } }); ``` @@ -1059,7 +1019,7 @@ Calculates the hash value of a file. This API uses a promise to return the resul ```js fileio.hash(path, "sha256").then(function(str){ console.info("Calculated file hash:"+ str); - }).catch(function(error){ + }).catch(function(err){ console.info("Failed to calculate the file hash. Error:"+ err); }); ``` @@ -1116,7 +1076,7 @@ Changes file permissions. This API uses a promise to return the result. **Example** ```js - fileio.chmod(path, mode).then(function() { + fileio.chmod(path, 0o700).then(function() { console.info("File permissions changed"); }).catch(function(err){ console.info("Failed to change file permissions. Error:"+ err); @@ -1143,7 +1103,7 @@ Changes file permissions. This API uses an asynchronous callback to return the r **Example** ```js - fileio.chmod(path, mode, function (err) { + fileio.chmod(path, 0o700, function (err) { // Do something. }); ``` @@ -1167,7 +1127,7 @@ Synchronously changes file permissions. **Example** ```js - fileio.chmodSync(path, mode); + fileio.chmodSync(path, 0o700); ``` @@ -1194,10 +1154,11 @@ Obtains file information based on the file descriptor. This API uses a promise t **Example** ```js + let fd = fileio.openSync(path); fileio.fstat(fd).then(function(stat){ - console.info("File information obtained:"+ JSON.stringify(stat)); + console.info("Obtained file info:"+ JSON.stringify(stat)); }).catch(function(err){ - console.info("Failed to obtain file information. Error:"+ err); + console.info("Failed to obtain file info. Error:"+ err); }); ``` @@ -1307,7 +1268,9 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal **Example** ```js - fileio.ftruncate(fd, len, function(err){ + let fd = fileio.openSync(path); + let len = 5; + fileio.ftruncate(fd, 5, function(err){ // Do something. }); ``` @@ -1331,6 +1294,8 @@ Synchronously truncates a file based on the file descriptor. **Example** ```js + let fd = fileio.openSync(path); + let len = 5; fileio.ftruncateSync(fd, len); ``` @@ -1347,7 +1312,7 @@ Truncates a file based on the file path. This API uses a promise to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to truncate. | +| path | string | Yes | Application sandbox path of the file to truncate.| | len | number | No | File length, in bytes, after truncation.| **Return value** @@ -1359,6 +1324,7 @@ Truncates a file based on the file path. This API uses a promise to return the r **Example** ```js + let len = 5; fileio.truncate(path, len).then(function(){ console.info("File truncated"); }).catch(function(err){ @@ -1386,6 +1352,7 @@ Truncates a file based on the file path. This API uses an asynchronous callback **Example** ```js + let len = 5; fileio.truncate(path, len, function(err){ // Do something. }); @@ -1410,6 +1377,7 @@ Synchronously truncates a file based on the file path. **Example** ```js + let len = 5; fileio.truncateSync(path, len); ``` @@ -1443,9 +1411,9 @@ 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 file text:"+ str); + console.info("Read text:"+ str); }).catch(function(err){ - console.info("Failed to read text. Error:"+ err); + console.info("Failed to read the text. Error:"+ err); }); ``` @@ -1467,13 +1435,13 @@ Reads the text content of a file. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | -| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
-  **encoding**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| +| options | Object | Yes | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
-  **encoding**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| | callback | AsyncCallback<string> | Yes | Callback used to return the content read. | **Example** ```js - fileio.readText(path, function(err, str){ + fileio.readText(path, { position: 1, encoding: 'UTF-8' }, function(err, str){ // Do something. }); ``` @@ -1537,7 +1505,7 @@ Obtains link information. This API uses a promise to return the result. fileio.lstat(path).then(function(stat){ console.info("Got link info:"+ JSON.stringify(stat)); }).catch(function(err){ - console.info("Failed to obtain the link status. Error:"+ err); + console.info("Failed to obtain link info. Error:"+ err); }); ``` @@ -1593,76 +1561,6 @@ Synchronously obtains the link information. ``` -## fileio.read7+ - -read(buffer: ArrayBuffer, options?: { - position?: number; - offset?: number; - length?: number; -}): Promise<ReadOut> - -Reads data from a file. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - - | Name | Type | Mandatory| Description | - | ------- | ----------- | ---- | ------------------------------------------------------------ | - | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | - | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
Constraints: offset + length <= Buffer size| - -**Return value** - - | Type | Description | - | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Promise used to return the data read.| - -**Example** - - ```js - fileio.read(new ArrayBuffer(4096)).then(function(readout){ - console.info("Read file data"); - console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - }).catch(function(err){ - console.info("Failed to read file data. Error:"+ err); - }); - ``` - - -## fileio.read7+ - -read(buffer: ArrayBuffer, options: { - position?: number; - offset?: number; - length?: number; -}, callback: AsyncCallback<ReadOut>): void - -Reads data from a file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - - | Name | Type | Mandatory | Description | - | -------- | ---------------------------------------- | ---- | ---------------------------------------- | - | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | - | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
Constraints: offset + length <= Buffer size| - | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously from the file. | - -**Example** - - ```js - let buf = new ArrayBuffer(4096); - fileio.read(buf, function (err, readOut) { - if (readOut) { - console.info("Read file data"); - console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - } - }); - ``` - - ## fileio.rename7+ rename(oldPath: string, newPath: string): Promise<void> @@ -1687,6 +1585,8 @@ Renames a file. This API uses a promise to return the result. **Example** ```js + let oldPath = path; + let newPath = oldPath + '123'; fileio.rename(oldPath, newPath).then(function() { console.info("File renamed"); }).catch(function(err){ @@ -1714,6 +1614,8 @@ Renames a file. This API uses an asynchronous callback to return the result. **Example** ```js + let oldPath = path; + let newPath = oldPath + '123'; fileio.rename(oldPath, newPath, function(err){ }); ``` @@ -1737,6 +1639,8 @@ Synchronously renames a file. **Example** ```js + let oldPath = path; + let newPath = oldPath + '123'; fileio.renameSync(oldPath, newPath); ``` @@ -1764,6 +1668,7 @@ Flushes data of a file to disk. This API uses a promise to return the result. **Example** ```js + let fd = fileio.openSync(path); fileio.fsync(fd).then(function(){ console.info("Data flushed"); }).catch(function(err){ @@ -1790,6 +1695,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Example** ```js + let fd = fileio.openSync(path); fileio.fsync(fd, function(err){ // Do something. }); @@ -1813,6 +1719,7 @@ Flushes data of a file to disk in synchronous mode. **Example** ```js + let fd = fileio.openSync(path); fileio.fsyncSync(fd); ``` @@ -1840,6 +1747,7 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** **Example** ```js + let fd = fileio.openSync(path); fileio.fdatasync(fd).then(function(err) { console.info("Data flushed"); }).catch(function(err){ @@ -1866,6 +1774,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Example** ```js + let fd = fileio.openSync(path); fileio.fdatasync (fd, function (err) { // Do something. }); @@ -1889,6 +1798,7 @@ Synchronizes data in a file in synchronous mode. **Example** ```js + let fd = fileio.openSync(path); let stat = fileio.fdatasyncSync(fd); ``` @@ -1917,6 +1827,8 @@ Creates a symbolic link based on the file path. This API uses a promise to retur **Example** ```js + let target = path; + let srcPath = target + 'aaa'; fileio.symlink(target, srcPath).then(function() { console.info("Symbolic link created"); }).catch(function(err){ @@ -1944,6 +1856,8 @@ Creates a symbolic link based on the file path. This API uses an asynchronous ca **Example** ```js + let target = path; + let srcPath = target + 'aaa'; fileio.symlink(target, srcPath, function (err) { // Do something. }); @@ -1968,6 +1882,8 @@ Synchronously creates a symbolic link based on a specified path. **Example** ```js + let target = path; + let srcPath = target + 'aaa'; fileio.symlinkSync(target, srcPath); ``` @@ -2083,7 +1999,7 @@ Creates a temporary directory. This API uses a promise to return the result. fileio.mkdtemp(path + "XXXX").then(function(path){ console.info("Temporary directory created:"+ path); }).catch(function(err){ - console.info("Failed to create a temporary directory. Error:"+ err); + console.info("Failed to create the temporary directory. Error:"+ err); }); ``` @@ -2163,6 +2079,8 @@ Changes file permissions based on the file descriptor. This API uses a promise t **Example** ```js + let fd = fileio.openSync(path); + let mode = 0o700; fileio.fchmod(fd, mode).then(function() { console.info("File permissions changed"); }).catch(function(err){ @@ -2190,6 +2108,8 @@ Changes file permissions based on the file descriptor. This API uses an asynchro **Example** ```js + let fd = fileio.openSync(path); + let mode = 0o700; fileio.fchmod(fd, mode, function (err) { // Do something. }); @@ -2214,6 +2134,8 @@ Synchronously changes the file permissions based on the file descriptor. **Example** ```js + let fd = fileio.openSync(path); + let mode = 0o700; fileio.fchmodSync(fd, mode); ``` @@ -2416,6 +2338,7 @@ Changes the file owner based on the file descriptor. This API uses a promise to **Example** ```js + let fd = fileio.openSync(path); let stat = fileio.statSync(path); fileio.fchown(fd, stat.uid, stat.gid).then(function() { console.info("File owner changed"); @@ -2445,6 +2368,7 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono **Example** ```js + let fd = fileio.openSync(path); let stat = fileio.statSync(path); fileio.fchown(fd, stat.uid, stat.gid, function (err){ // Do something. @@ -2471,6 +2395,7 @@ Synchronously changes the file owner based on the file descriptor. **Example** ```js + let fd = fileio.openSync(path); let stat = fileio.statSync(path); fileio.fchownSync(fd, stat.uid, stat.gid); ``` @@ -2854,7 +2779,7 @@ Closes the stream. This API uses a promise to return the result. ```js let ss= fileio.createStreamSync(path, "r+"); ss.close().then(function(){ - console.info("Stream closed"); + console.info("File stream closed"); }).catch(function(err){ console.info("Failed to close the file stream. Error:"+ err); }); @@ -3102,7 +3027,7 @@ Reads data from the stream. This API uses a promise to return the result. ```js let ss = fileio.createStreamSync(path, "r+"); - ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ + ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readOut){ console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); }).catch(function(err){ @@ -3179,7 +3104,7 @@ Synchronously reads data from the stream. ## Dir -Manages directories. Before calling a method of the **Dir** class, use the [opendir()](#fileioopendir) method synchronously or asynchronously to create a **Dir** instance. +Manages directories. Before calling a method of the **Dir** class, use the **opendir()** method synchronously or asynchronously to create a **Dir** instance. ### read @@ -3449,7 +3374,7 @@ Checks whether a directory entry is a socket. **Example** ```js - let dir = fileio.opendirSync(dpath); + let dir = fileio.opendirSync(path); let isSocket = dir.readSync().isSocket(); ``` 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-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index c1ec2c787a6f9e47c1c87715b5ea52171dbac85f..178313a1ff1a83a905895656793ff5977a486d0d 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -287,7 +287,7 @@ Defines the information about an input device. | Name | Type | Description | | -------- | ------------------------- | --------------------------------- | -| type | [ChangeType](#changetype) | Device change type, which indicates whether an input device is inserted or removed. | +| type | [ChangedType](#changedtype) | Device change type, which indicates whether an input device is inserted or removed. | | deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| ## InputDeviceData 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-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 7135d5666d3884667c0d7dee8ac98d832bf410ab..e1dbb5f4a54b3936dc4b52e76ab5ad0fc0a39265 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -20,7 +20,7 @@ Obtains an **AccountManager** instance. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | --------------------------------- | ------------------------ | | [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.| @@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the OS account to activate.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -141,7 +141,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -202,7 +202,7 @@ Checks whether an OS account is activated. This API uses a promise to return the | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -266,7 +266,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | localId | number | Yes | ID of the target OS account. | | constraint | string | Yes | [Constraint](#constraints) specified.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -316,7 +316,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -400,7 +400,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur | ------- | ------ | ---- | ------------------ | | localId | number | No | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -467,7 +467,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the OS account to remove.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -540,7 +540,7 @@ This is a system API and cannot be called by third-party applications. | constraints | Array<string> | Yes | List of [constraints](#constraints) to set or remove.| | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -608,7 +608,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | localName | string | Yes | Account name to set. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -663,7 +663,7 @@ Obtains the number of OS accounts created. This API uses a promise to return the **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -712,7 +712,7 @@ Obtains the ID of the OS account to which the current process belongs. This API **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -769,7 +769,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r | ------ | ------ | ---- | --------- | | uid | number | Yes | Process UID.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -831,7 +831,7 @@ Obtains the OS account ID based on domain account information. This API uses a p | ---------- | --------------------------------------- | ---- | ------------ | | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -885,7 +885,7 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -946,7 +946,7 @@ Obtains all constraints enabled for an OS account. This API uses a promise to re | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------- | :----------------------------------------------------------- | @@ -1004,7 +1004,7 @@ This is a system API and cannot be called by third-party applications. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS -**Return Value** +**Return value** | Type | Description | | :---------------------------------------------------------- | :----------------------------------------------------------- | @@ -1056,7 +1056,7 @@ Obtains information about all activated OS accounts. This API uses a promise to **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------- | :----------------------------------------------------------- | @@ -1122,7 +1122,7 @@ This is a system API and cannot be called by third-party applications. | localName | string | Yes | Name of the OS account to create.| | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1189,7 +1189,7 @@ This is a system API and cannot be called by third-party applications. | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| | domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1243,7 +1243,7 @@ Obtains information about the OS account to which the current process belongs. T **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1308,7 +1308,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1358,7 +1358,7 @@ Obtains the type of the OS account to which the current process belongs. This AP **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1411,7 +1411,7 @@ Obtains the ID of this distributed virtual device. This API uses a promise to re **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1476,7 +1476,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1547,7 +1547,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | photo | string | Yes | Profile photo information. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -1609,7 +1609,7 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the | ------------ | ------ | ---- | ---------- | | serialNumber | number | Yes | Account SN.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1667,7 +1667,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1787,7 +1787,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | ------------ | | uid | number | Yes | Process UID.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1836,7 +1836,7 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1898,7 +1898,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | constraint | string | Yes | Name of the [constraint](#constraints) to query.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | 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-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index e06a5536a8754922e0e82d14162296124f498665..42cf66fea697004eafe45bc775146e0aa77ce8ad 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -1,11 +1,11 @@ # Privacy Management -Provides APIs for privacy management, such as management of permission usage records. +The **PrivacyManager** module provides APIs for privacy management, such as management of permission usage records. > **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 are system APIs and cannot be called by third-party applications. +> +> 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 are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -19,7 +19,6 @@ import privacyManager from '@ohos.privacyManager'; addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise<number> Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result. - The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -41,10 +40,6 @@ The permission usage record includes the application identity of the invoker, na | :------------ | :---------------------------------- | | Promise<number> | Promise used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| -``` - -``` - **Example** ```js @@ -59,7 +54,6 @@ privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback<number>): void Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result. - The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -202,7 +196,7 @@ Represents the permission usage records of all applications. ## BundleUsedRecord -Represents the application access records of an application. +Represents the permission access records of an application. **System capability**: SystemCapability.Security.AccessToken @@ -212,11 +206,11 @@ Represents the application access records of an application. | isRemote | boolean | No | Whether the token ID belongs to a remote device. The default value is **false**.| | deviceId | string | No | ID of the device hosting the target application. | | bundleName | string | No | Bundle name of the target application.| -| permissionRecords | Array<[PermissionUsedRecord](#PermissionUsedRecord)> | No | Permission usage records of the specified application obtained. | +| permissionRecords | Array<[PermissionUsedRecord](#PermissionUsedRecord)> | No | Permission usage records of the target application. | ## PermissionUsedRecord -Represents the access records of a permission. +Represents the usage records of a permission. **System capability**: SystemCapability.Security.AccessToken @@ -225,8 +219,8 @@ Represents the access records of a permission. | permissionName | string | No | Name of the permission. | | accessCount | number | No | Total number of times that the permission is accessed.| | rejectCount | number | No | Total number of times that the access to the permission is rejected.| -| lastAccessTime | number | No | Last time when the permission was accessed, in ms.| -| lastRejectTime | number | No | Last time when the access to the permission was rejected, in ms.| +| lastAccessTime | number | No | Last time when the permission was accessed, accurate to ms.| +| lastRejectTime | number | No | Last time when the access to the permission was rejected, accurate to ms.| | lastAccessDuration | number | No | Last access duration, in ms.| | accessRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | No | Access records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | | rejectRecords | Array<[UsedRecordDetail](#usedrecorddetail)> | No | Rejected records. This parameter is valid only when **flag** is **FLAG_PERMISSION_USAGE_SUMMARY**. By default, 10 records are provided. | diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index e73c4fe303ebeaac19274d5214085fb8646fa651..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. @@ -92,7 +93,7 @@ This is a system API and cannot be called by third-party applications. ```js var child = process.runCmd('ls'); var result = child.wait(); -child.getOutput.then(val=>{ +child.getOutput().then(val=>{ console.log("child.getOutput = " + val); }) ``` @@ -119,7 +120,7 @@ This is a system API and cannot be called by third-party applications. ```js var child = process.runCmd('madir test.text'); var result = child.wait(); -child.getErrorOutput.then(val=>{ +child.getErrorOutput().then(val=>{ console.log("child.getErrorOutput= " + val); }) ``` @@ -286,7 +287,7 @@ Obtains the thread priority based on the specified TID. **Example** ```js -var tid = process.getTid(); +var tid = process.tid; var pres = process.getThreadPriority(tid); ``` @@ -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** @@ -617,5 +618,5 @@ Sends a signal to the specified process to terminate it. ```js var pres = process.pid -var result = that.kill(28, pres) +var result = process.kill(28, pres) ``` 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 335e31cdb21bacd975db26b726f503c0a44e431d..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,10 +1490,10 @@ Obtains the string corresponding to the specified resource name. This API return **Example** ``` - resourceManager.getStringByNameSync("test"); + this.context.resourceManager.getStringByNameSync("test"); ``` - ### getBoolean9+ +### getBoolean9+ getBoolean(resId: number): boolean @@ -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,10 +1563,10 @@ Obtains the Boolean result corresponding to the specified resource name. This AP **Example** ``` - resourceManager.getBooleanByName("boolean_test"); + this.context.resourceManager.getBooleanByName("boolean_test"); ``` - ### getNumber9+ +### getNumber9+ getNumber(resId: number): number @@ -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-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..d2c9431ec4c0a4c8c4228b74e3bf85a30c697c0f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -0,0 +1,713 @@ +# 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 + +**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 + +**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 + +**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 + +**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. | +| SENSOR | 5 | The screen orientation follows the sensor direction. | +| SENSOR_VERTICAL | 6 | The screen orientation follows the sensor direction vertically.| +| SENSOR_HORIZONTAL | 7 | The screen orientation follows the sensor direction horizontally.| + +## ScreenModeInfo +Defines the screen mode information. + +**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-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 5e2d47e03ba31ab4bae9118e3dc373359d56da11..7f83f0250c209dbd6b5d57970fe7beb8d9b9a494 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -1,5 +1,5 @@ # Screenshot -Provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen. +The **Screenshot** module provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen. > **NOTE** > @@ -57,7 +57,7 @@ Describes the size of the screen region to capture. save(options?: ScreenshotOptions, callback: AsyncCallback<image.PixelMap>): void -Takes a screenshot and saves it as a **PixelMap** object. This method uses a callback to return the result. +Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -67,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [ScreenshotOptions](#screenshotoptions) | No | Consists of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set them separately.| +| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | **Example** @@ -98,7 +98,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal save(options?: ScreenshotOptions): Promise<image.PixelMap> -Takes a screenshot and saves it as a **PixelMap** object. This method uses a promise to return the result. +Takes a screenshot and saves it as a **PixelMap** object. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -108,7 +108,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro | Name | Type | Mandatory| Description | | ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [ScreenshotOptions](#screenshotoptions) | No | Consists of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set them separately.| +| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-securityLabel.md b/en/application-dev/reference/apis/js-apis-securityLabel.md index a2219288f3b852337ee03ab9f7003adf02dd51b4..86ae51122132f39ce30fe8df4bebc626c8e07d3f 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 @@ -13,12 +13,15 @@ import securityLabel from '@ohos.securityLabel'; ## Usage -Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). +Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox as follows: ```js import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); -let path = context.getFilesDir(); +let path = ''; +context.getFilesDir().then((data) => { + path = data; +}) ``` ## securityLabel.setSecurityLabel 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 093d6cb8b578e66b4213d2f247a95c7c0b9a8643..5606a2e64372c3e002815d535f59851718e535e9 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 @@ -470,7 +470,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | - | userId | string | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| + | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| **Return value** @@ -481,7 +481,7 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - let userId = ""; + let userId = 1; storageStatistics.getUserStorageStats(userId).then(function(StorageStats){ console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); }).catch(function(err){ @@ -507,13 +507,13 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | - | userId | string | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | + | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| **Example** ```js - let userId = ""; + let userId = 1; storageStatistics.getUserStorageStats(userId, function(error, StorageStats){ // Do something. console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); 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-timer.md b/en/application-dev/reference/apis/js-apis-timer.md index d144a95db8f59ca0605fd228b351380afe6feac8..f9e174b5147370f465e140d03aeba6b3802380a0 100644 --- a/en/application-dev/reference/apis/js-apis-timer.md +++ b/en/application-dev/reference/apis/js-apis-timer.md @@ -3,13 +3,6 @@ ## setTimeout -## Modules to Import - - -``` -import Time from '@ohos.Time'; -``` - setTimeout(handler[,delay[,…args]]): number Sets a timer for the system to call a function after the timer goes off. 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-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index a6c8823599cfee6dba5288e6555d6c618fd414c8..60fd45f98209c718374e4a2633b074a531aa719c 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -72,8 +72,8 @@ Obtains the query string applicable to this URI. **Example** ```js -const uri = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -uri.toString() +const result = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +result.toString() ``` diff --git a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md b/en/application-dev/reference/apis/js-apis-uripermissionmanager.md deleted file mode 100644 index 6bbf0f941909786361f651546a3fab9fe129c69c..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md +++ /dev/null @@ -1,86 +0,0 @@ -# uriPermissionManager - -> **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. - - -Implements URI permission management. - - -## Modules to Import - - -``` -import UriPermissionManager from '@ohos.application.uriPermissionManager'; -``` - - -## uriPermissionManager.verifyUriPermission - -verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number, callback: AsyncCallback<number>): void - -Checks whether an application has the permission specified by **flag** for an URI. This API uses a callback to return the result. - -**System capability**: - -SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | uri | string | Yes| URI of a file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| - | flag | wantConstant.Flags | Yes| Read or write permission on the file specified by the URI.| - | accessTokenId | number | Yes| Unique ID of an application, which is obtained through the **BundleManager** API.| - | callback | AsyncCallback<number> | Yes| Callback used to return the check result. The value **0** means that the application has the specified permission, and **-1** means the opposite.| - -**Example** - - ```js - import WantConstant from '@ohos.ability.wantConstant'; - let accessTokenId =1 - let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10" - UriPermissionManager.verifyUriPermission(uri, WantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, accessTokenId, (result) => { - console.log("result.code = " + result.code) - }) // accessTokenId is obtained through the **BundleManager** API. - ``` - - -## uriPermissionManager.verifyUriPermission - -verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number): Promise<number> - -Checks whether an application has the permission specified by **flag** for an URI. This API uses a callback to return the result. - -**System capability**: - -SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | uri | string | Yes| URI of a file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| - | flag | wantConstant.Flags | Yes| Read or write permission on the file specified by the URI.| - | accessTokenId | number | Yes| Unique ID of an application, which is obtained through the **BundleManager** API.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the check result. The value **0** means that the application has the specified permission, and **-1** means the opposite.| - -**Example** - - ```js - import WantConstant from '@ohos.ability.wantConstant'; - let accessTokenId =1 - let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10" - UriPermissionManager.verifyUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, accessTokenId) - .then((data) => { - console.log('Verification succeeded.' + data) - }).catch((error) => { - console.log('Verification failed.'); - }) - ``` diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index fd826706700190a3d2f042a155cca1a2e1c96b81..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,13 +26,13 @@ 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** ```js var objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); -var objectParams1 = new Url.URLSearchParams({"fod" : 1 , "bard" : 2}); +var objectParams1 = new Url.URLSearchParams({"fod" : '1' , "bard" : '2'}); var objectParams2 = new Url.URLSearchParams('?fod=1&bard=2'); var urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); var params = new Url.URLSearchParams(urlObject.search); @@ -48,17 +49,17 @@ 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** ```js let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); -paramsObject.append('fod', 3); +paramsObject.append('fod', '3'); ``` @@ -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,23 +96,23 @@ 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** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); -paramsObject.append('fod', 3); // Add a second value for the fod parameter. -console.log(params.getAll('fod')) // Output ["1","3"]. +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let params = new Url.URLSearchParams(urlObject.search.slice(1)); +params.append('fod', '3'); // Add a second value for the fod parameter. +console.log(params.getAll('fod').toString()) // Output ["1","3"]. ``` @@ -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,24 +183,23 @@ 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** ```js -var paramsOject = new Url.URLSearchParams(document.location.search.substring(1)); +var paramsOject = new Url.URLSearchParams('name=Jonathan&age=18'); var name = paramsOject.get("name"); // is the string "Jonathan" var age = parseInt(paramsOject.get("age"), 10); // is the number 18 -var address = paramsOject.get("address"); // null ``` @@ -213,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** @@ -242,17 +242,17 @@ 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** ```js let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); -paramsObject.set('baz', 3); // Add a third parameter. +paramsObject.set('baz', '3'); // Add a third parameter. ``` @@ -283,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** @@ -307,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** @@ -331,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** @@ -355,16 +355,16 @@ 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** ```js let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); let params = new Url.URLSearchParams(url.search.slice(1)); -params.append('fod', 3); +params.append('fod', '3'); console.log(params.toString()); ``` @@ -401,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** @@ -434,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** @@ -456,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 63beaae8031c42ad274d2e151dad4c029f799761..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 @@ -126,8 +129,8 @@ Checks whether the application has the permission to access the device. - **Example** ```js - let divicesName="1-1"; - let bool = usb.hasRight(divicesName); + let devicesName="1-1"; + let bool = usb.hasRight(devicesName); console.log(bool); ``` @@ -152,8 +155,8 @@ Requests the temporary permission for the application to access the USB device. - **Example** ```js - let divicesName="1-1"; - usb.requestRight(divicesName).then((ret) => { + let devicesName="1-1"; + usb.requestRight(devicesName).then((ret) => { console.log(`requestRight = ${JSON.stringify(ret)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 2ac8daeb3799908d57a5b7a2c5fd456dcfee8f59..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); ``` @@ -91,23 +91,29 @@ Calls back an asynchronous function. In the callback, the first parameter indica async function promiseFn() { return Promise.reject('value'); } + var err = "type err"; var cb = util.callbackWrapper(promiseFn); cb((err, ret) => { console.log(err); console.log(ret); - }) + }, err) ``` -## util.promiseWrapper +## util.promiseWrapper(deprecated) promiseWrapper(original: (err: Object, value: Object) => void): Object +> **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.| @@ -119,19 +125,47 @@ Processes an asynchronous function and returns a promise version. **Example** ```js - function aysnFun(str1, str2, callback) { - if (typeof str1 === 'string' && typeof str2 === 'string') { - callback(null, str1 + str2); - } else { - callback('type err'); - } + function aysnFun() { + return 0; } - let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); - newPromiseObj.then(res => { - console.log(res); + let newPromiseObj = util.promiseWrapper(aysnFun); + newPromiseObj().then(res => { + console.log(res); }) ``` +## util.promisify9+ + +promisify(original: (err: Object, value: Object) => void): Function + +Processes an asynchronous function and returns a promise. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| original | Function | Yes| Asynchronous 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.| + +**Example** + ```js + function aysnFun(str1, str2) { + if (typeof str1 === 'object' && typeof str2 === 'object') { + return str2 + } else { + return str1 + } + } + let newPromiseObj = util.promisify(aysnFun); + newPromiseObj({ err: "type error" }, {value:'HelloWorld'}).then(res => { + console.log(res); + }) + ``` ## TextDecoder @@ -184,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 @@ -287,10 +321,11 @@ Stores the UTF-8 encoded text. **Example** ```js - var that = new util.TextEncoder(); - var buffer = new ArrayBuffer(4); - this.dest = new Uint8Array(buffer); - var result = that.encodeInto("abcd", this.dest); + var that = new util.TextEncoder() + var buffer = new ArrayBuffer(4) + var dest = new Uint8Array(buffer) + var result = new Object() + result = that.encodeInto('abcd', dest) ``` ## RationalNumber8+ @@ -337,7 +372,7 @@ Creates a **RationalNumber** object based on the given string. **Example** ```js var rationalNumber = new util.RationalNumber(1,2); - var rational = rationalNumer.creatRationalFromString("3/4"); + var rational = util.RationalNumber.createRationalFromString("3/4"); ``` @@ -362,7 +397,7 @@ Compares this **RationalNumber** object with a given object. **Example** ```js var rationalNumber = new util.RationalNumber(1,2); - var rational = rationalNumer.creatRationalFromString("3/4"); + var rational = util.RationalNumber.createRationalFromString("3/4"); var result = rationalNumber.compareTo(rational); ``` @@ -408,7 +443,7 @@ Checks whether this **RationalNumber** object equals the given object. **Example** ```js var rationalNumber = new util.RationalNumber(1,2); - var rational = rationalNumer.creatRationalFromString("3/4"); + var rational = util.RationalNumber.createRationalFromString("3/4"); var result = rationalNumber.equals(rational); ``` @@ -435,7 +470,7 @@ Obtains the greatest common divisor of two specified integers. **Example** ```js var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.getCommonDivisor(4,6); + var result = util.RationalNumber.getCommonDivisor(4,6); ``` @@ -672,7 +707,7 @@ Clears key-value pairs from this buffer. The **afterRemoval()** method will be c ```js var pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.size(); + var result = pro.length; pro.clear(); ``` @@ -954,14 +989,6 @@ Performs subsequent operations after a value is removed. { super(); } - static getInstance() - { - if(this.instance == null) - { - this.instance = new ChildLruBuffer(); - } - return this.instance; - } afterRemoval(isEvict, key, value, newValue) { if (isEvict === false) @@ -970,7 +997,8 @@ Performs subsequent operations after a value is removed. } } } - ChildLruBuffer.getInstance().afterRemoval(false,10,30,null); + var lru = new ChildLruBuffer(); + lru.afterRemoval(false,10,30,null); ``` @@ -1063,7 +1091,7 @@ Obtains a two-dimensional array in key-value pairs. ```js var pro = new util.LruBuffer(); pro.put(2,10); - var result = pro[symbol.iterator](); + var result = pro[Symbol.iterator](); ``` @@ -1551,7 +1579,7 @@ Encodes the input content asynchronously. var rarray = new Uint8Array([99,122,69,122]); that.encode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { - console.log(val[i]) + console.log(val[i].toString()) } }) ``` @@ -1610,7 +1638,7 @@ Decodes the input content asynchronously. var rarray = new Uint8Array([115,49,51]); that.decode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { - console.log(val[i]) + console.log(val[i].toString()) } }) ``` @@ -1654,7 +1682,7 @@ Checks whether the input value is of the **ArrayBuffer** type. **Example** ```js var that = new util.types(); - var result = that.isAnyArrayBuffer(new ArrayBuffer([])); + var result = that.isAnyArrayBuffer(new ArrayBuffer(0)); ``` @@ -1734,7 +1762,7 @@ Checks whether the input value is of the **ArrayBuffer** type. **Example** ```js var that = new util.types(); - var result = that.isArrayBuffer(new ArrayBuffer([])); + var result = that.isArrayBuffer(new ArrayBuffer(0)); ``` @@ -1885,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-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-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 875607d4fd022e5a9e91359bde83ee4d1d70a69b..602a3b7e2a318119b1e8dbfa80a59fdc65a6bede 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -21,9 +21,9 @@ Checks whether the WLAN is activated. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the WLAN is activated; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the WLAN is activated; returns **false** otherwise.| ## wifi.scan @@ -37,41 +37,41 @@ Starts a scan for WLAN. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the scan is successful; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the scan is successful; returns **false** otherwise.| ## wifi.getScanInfos getScanInfos(): Promise<Array<WifiScanInfo>> -Obtains the scan result. This method uses a promise to return the result. +Obtains the scan result. This API uses a promise to return the result. -**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, or ohos.permission.LOCATION +**Required permissions**: at least one of ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the scan result, which is a list of hotspots detected.| +| **Type**| **Description**| +| -------- | -------- | +| Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the hotspots detected.| ## wifi.getScanInfos getScanInfos(callback: AsyncCallback<Array<WifiScanInfo>>): void -Obtains the scan result. This method uses an asynchronous callback to return the result. +Obtains the scan result. This API uses an asynchronous callback to return the result. **Required permissions**: at least one of ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result, which is a list of hotspots detected.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the hotspots detected.| **Example** ```js @@ -126,10 +126,12 @@ Represents WLAN hotspot information. | bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| | capabilities | string | Read only| Hotspot capabilities.| | securityType | [WifiSecurityType](#WifiSecurityType) | Read only| WLAN security type.| -| rssi | number | Read only| Signal strength of the hotspot, in dBm.| +| rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| | band | number | Read only| Frequency band of the WLAN access point (AP).| | frequency | number | Read only| Frequency of the WLAN AP.| | channelWidth | number | Read only| Bandwidth of the WLAN AP.| +| centerFrequency0 | number | Read only| Center frequency.| +| centerFrequency1 | number | Read only| Center frequency.| | timestamp | number | Read only| Timestamp.| @@ -150,7 +152,7 @@ Enumerates the WLAN security types. addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> -Adds untrusted WLAN configuration. This method uses a promise to return the result. +Adds untrusted WLAN configuration. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_WIFI_INFO @@ -159,14 +161,14 @@ Adds untrusted WLAN configuration. This method uses a promise to return the resu SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| ## WifiDeviceConfig @@ -174,120 +176,120 @@ Represents the WLAN configuration. | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| +| ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| | preSharedKey | string | Read only| Private key of the hotspot.| | isHiddenSsid | boolean | Read only| Whether to hide the network.| -| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type| +| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type.| ## wifi.addUntrustedConfig7+ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void -Adds untrusted WLAN configuration. This method uses an asynchronous callback to return the result. +Adds untrusted WLAN configuration. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.SET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<boolean> | Yes| Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| ## wifi.removeUntrustedConfig7+ removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> -Removes untrusted WLAN configuration. This method uses a promise to return the result. +Removes untrusted WLAN configuration. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove. | **Return value** - | **Type**| **Description**| - | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| +| **Type**| **Description**| +| -------- | -------- | +| Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| ## wifi.removeUntrustedConfig7+ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void -Removes untrusted WLAN configuration. This method uses an asynchronous callback to return the result. +Removes untrusted WLAN configuration. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.SET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove.| - | callback | AsyncCallback<boolean> | Yes| Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| ## wifi.getSignalLevel getSignalLevel(rssi: number, band: number): number -Obtains the WLAN signal strength. +Obtains the WLAN signal level. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | rssi | number | Yes| Signal strength of the hotspot, in dBm.| - | band | number | Yes| Frequency band of the WLAN AP.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| rssi | number | Yes| RSSI of the hotspot, in dBm. | +| band | number | Yes| Frequency band of the WLAN AP.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | number | Signal strength obtained. The value range is [0, 4].| +| **Type**| **Description**| +| -------- | -------- | +| number | Signal level obtained. The value range is [0, 4].| ## wifi.getLinkedInfo getLinkedInfo(): Promise<WifiLinkedInfo> -Obtains WLAN connection information. This method uses a promise to return the result. +Obtains WLAN connection information. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiLinkedInfo](#WifiLinkedInfo)> | Promise used to return the WLAN connection information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiLinkedInfo](#WifiLinkedInfo)> | Promise used to return the WLAN connection information obtained.| ## wifi.getLinkedInfo getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void -Obtains WLAN connection information. This method uses a callback to return the result. +Obtains WLAN connection information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiLinkedInfo](#WifiLinkedInfo)> | Yes| Callback invoked to return the WLAN connection information obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiLinkedInfo](#WifiLinkedInfo)> | Yes| Callback invoked to return the WLAN connection information obtained.| **Example** ```js @@ -317,11 +319,11 @@ Represents the WLAN connection information. | -------- | -------- | -------- | -------- | | ssid | string | Read only| Hotspot SSID, in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| -| rssi | number | Read only| Signal strength of the hotspot, in dBm.| +| rssi | number | Read only| RSSI of the hotspot, in dBm. | | band | number | Read only| Frequency band of the WLAN AP.| | linkSpeed | number | Read only| Speed of the WLAN AP.| | frequency | number | Read only| Frequency of the WLAN AP.| -| isHidden | boolean | Read only| Whether the WLAN AP is hidden.| +| isHidden | boolean | Read only| Whether to hide the WLAN AP.| | isRestricted | boolean | Read only| Whether to restrict data volume at the WLAN AP.| | macAddress | string | Read only| MAC address of the device.| | ipAddress | number | Read only| IP address of the device that sets up the WLAN connection.| @@ -355,9 +357,9 @@ Checks whether the WLAN is connected. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| ## wifi.isFeatureSupported7+ @@ -372,14 +374,14 @@ Checks whether the device supports the specified WLAN feature. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | featureId | number | Yes| Feature ID.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| featureId | number | Yes| Feature ID.| **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| **Feature IDs** @@ -408,9 +410,9 @@ Obtains IP information. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** - | **Type**| **Description**| - | -------- | -------- | - | [IpInfo](#IpInfo) | IP information obtained.| +| **Type**| **Description**| +| -------- | -------- | +| [IpInfo](#IpInfo) | IP information obtained.| ## IpInfo7+ @@ -439,41 +441,41 @@ Obtains the country code. **System capability**: SystemCapability.Communication.WiFi.Core **Return value** - | **Type**| **Description**| - | -------- | -------- | - | string | Country code obtained.| +| **Type**| **Description**| +| -------- | -------- | +| string | Country code obtained.| ## wifi.getP2pLinkedInfo8+ getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> -Obtains peer-to-peer (P2P) connection information. This method uses a promise to return the result. +Obtains peer-to-peer (P2P) connection information. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Promise used to return the P2P connection information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Promise used to return the P2P connection information obtained.| ## wifi.getP2pLinkedInfo8+ getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void -Obtains P2P connection information. This method uses a callback to return the result. +Obtains P2P connection information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback used to return the P2P connection information obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback used to return the P2P connection information obtained.| ## WifiP2pLinkedInfo8+ @@ -483,8 +485,8 @@ Represents the WLAN connection information. | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | | connectState | [P2pConnectState](#P2pConnectState) | Read only| P2P connection state.| -| isGroupOwner | boolean | Read only| Whether it is a group.| -| groupOwnerAddr | string | Read only| MAC address of the group.| +| isGroupOwner | boolean | Read only| Whether it is a group owner.| +| groupOwnerAddr | string | Read only| MAC address of the group owner.| ## P2pConnectState8+ @@ -501,33 +503,62 @@ Enumerates the P2P connection states. getCurrentGroup(): Promise<WifiP2pGroupInfo> -Obtains the current P2P group information. This method uses a promise to return the result. +Obtains the current P2P group information. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Promise used to return the P2P group information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Promise used to return the P2P group information obtained.| ## wifi.getCurrentGroup8+ getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void -Obtains the P2P group information. This method uses an asynchronous callback to return the result. +Obtains the P2P group information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Yes| Callback used to return the P2P group information obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Yes| Callback used to return the P2P group information obtained.| + +## wifi.getP2pGroups9+ + +getP2pGroups(): Promise<Array<WifiP2pGroupInfo> + +Obtains information about all P2P groups. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise< Array<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> > | Information about all created P2P groups obtained.| + +## wifi.getP2pGroups9+ + +getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>): void + +Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback< Array<[WifiP2pGroupInfo](#WifiP2pGroupInfo)>> | Yes| Callback invoked to return the P2P group information obtained.| ## WifiP2pGroupInfo8+ @@ -574,33 +605,63 @@ Enumerates the device states. getP2pPeerDevices(): Promise<WifiP2pDevice[]> -Obtains the list of peer devices in a P2P connection. This method uses a promise to return the result. +Obtains the list of peer devices in a P2P connection. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice[]](#WifiP2pDevice)> | Promise used to return the peer device list obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pDevice[]](#WifiP2pDevice)> | Promise used to return the peer device list obtained.| ## wifi.getP2pPeerDevices8+ getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void -Obtains the list of peer devices in a P2P connection. This method uses an asynchronous callback to return the result. +Obtains the list of peer devices in a P2P connection. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback used to return the peer device list obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback used to return the peer device list obtained.| + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(): Promise<WifiP2pDevice> + +Obtains local device information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<[WifiP2pDevice](#WifiP2pDevice)> | Promise used to return the local device information obtained.| + + +## wifi.getP2pLocalDevice8+ + +getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void + +Obtains local device information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[WifiP2pDevice](#WifiP2pDevice)> | Yes| Callback invoked to returnthe local device information obtained.| ## wifi.createGroup8+ @@ -614,14 +675,14 @@ Creates a P2P group. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Group configuration.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Group configuration.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## WifiP2PConfig8+ @@ -650,16 +711,16 @@ Enumerates the P2P group bandwidths. removeGroup(): boolean; -Removes a P2P group. +Removes this P2P group. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.p2pConnect8+ @@ -674,14 +735,14 @@ Sets up a P2P connection. **Parameters** - | **Name**| **Type**| Mandatory| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Connection configuration.| +| **Name**| **Type**| Mandatory| **Description**| +| -------- | -------- | -------- | -------- | +| config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Connection configuration.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -762,9 +823,9 @@ Cancels this P2P connection. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.startDiscoverDevices8+ @@ -778,9 +839,9 @@ Starts to discover devices. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.stopDiscoverDevices8+ @@ -794,9 +855,9 @@ Stops discovering devices. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.on('wifiStateChange')7+ @@ -810,10 +871,10 @@ Registers the WLAN state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| **WLAN states** @@ -836,10 +897,10 @@ Unregisters the WLAN state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiStateChange**.| +| callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -850,10 +911,10 @@ Unregisters the WLAN state change events. console.info("Receive power state change event: " + result); } - // Register event + // Register an event. wifi.on(WIFI_POWER_STATE, recvPowerNotifyFunc); - // Unregister event + // Unregister an event. wifi.off(WIFI_POWER_STATE, recvPowerNotifyFunc); ``` @@ -869,10 +930,10 @@ Registers the WLAN connection state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiConnectionChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| **WLAN connection states** @@ -893,10 +954,10 @@ Unregisters the WLAN connection state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiConnectionChange**.| +| callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -910,10 +971,10 @@ Registers the WLAN scan state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiScanStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| **WLAN scan states** @@ -952,10 +1013,10 @@ Registers the RSSI change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiRssiChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| ## wifi.off('wifiRssiChange')7+ @@ -969,10 +1030,10 @@ Unregisters the RSSI change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **wifiRssiChange**.| - | callback | Callback<number> | No| Callback used to return the RSSI, in dBm. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | No| Callback used to return the RSSI, in dBm. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('hotspotStateChange')7+ @@ -986,10 +1047,10 @@ Registers the hotspot state change events. **System capability**: SystemCapability.Communication.WiFi.AP.Core **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **hotspotStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| **Hotspot states** @@ -1012,10 +1073,10 @@ Unregisters the hotspot state change events. **System capability**: SystemCapability.Communication.WiFi.AP.Core **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **hotspotStateChange**.| - | callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pStateChange')8+ @@ -1029,10 +1090,10 @@ Registers the P2P state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pStateChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the P2P state.| **P2P states** @@ -1055,10 +1116,10 @@ Unregisters the P2P state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pStateChange**.| - | callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pConnectionChange')8+ @@ -1072,10 +1133,10 @@ Registers the P2P connection state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pConnectionChange**.| - | callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback invoked to return the P2P connection state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pConnectionChange**.| +| callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback invoked to return the P2P connection state.| ## wifi.off('p2pConnectionChange')8+ @@ -1089,10 +1150,10 @@ Unregisters the P2P connection state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pConnectionChange**.| - | callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pConnectionChange**.| +| callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDeviceChange')8+ @@ -1106,10 +1167,10 @@ Registers the P2P device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDeviceChange**.| - | callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P device state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDeviceChange**.| +| callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P device state.| ## wifi.off('p2pDeviceChange')8+ @@ -1123,10 +1184,10 @@ Unregisters the P2P device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDeviceChange**.| - | callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDeviceChange**.| +| callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPeerDeviceChange')8+ @@ -1140,10 +1201,10 @@ Registers the P2P peer device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| - | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P peer device state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| +| callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P peer device state.| ## wifi.off('p2pPeerDeviceChange')8+ @@ -1157,10 +1218,10 @@ Unregisters the P2P peer device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| - | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | No| Callback used to return the P2P peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| +| callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | No| Callback used to return the P2P peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ @@ -1174,10 +1235,10 @@ Registers the P2P persistent group state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| - | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| +| callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| ## wifi.off('p2pPersistentGroupChange')8+ @@ -1191,27 +1252,27 @@ Unregisters the P2P persistent group state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| - | callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| +| callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDiscoveryChange')8+ on(type: "p2pDiscoveryChange", callback: Callback<number>): void -Registers the P2P discovered device state change events. +Registers the P2P device discovery state change events. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the state of the P2P discovered device.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| +| callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| **P2P discovered device states** @@ -1225,14 +1286,14 @@ Registers the P2P discovered device state change events. off(type: "p2pDiscoveryChange", callback?: Callback<number>): void -Unregisters the P2P discovered device state change events. +Unregisters the P2P device discovery state change events. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | No| Callback used to return the state of the P2P discovered device. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| +| callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index f22c9988cf123f79225babf014b089bb98e6247a..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. @@ -146,7 +147,7 @@ thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.startElement("table"); thatSer.setAttributes("importance", "high"); thatSer.setText("Happy"); -endElement(); // => Happy +thatSer.endElement(); // => Happy ``` 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-js/js-components-basic-input.md b/en/application-dev/reference/arkui-js/js-components-basic-input.md index 283e9aae6e5ad9a4e4cb72abf1e3cc716c1c40d0..1f10982593566d8ad21467a9613d260ab6e6a3ec 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-input.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-input.md @@ -1,610 +1,239 @@ -# input +# input -The **** component provides an interactive interface to receive user input. It can be a radio button, check box, button, single-line text box, and more. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component provides an interactive interface to receive user input. It can be a radio button, check box, button, single-line text box, and more. + +## Required Permissions None -## Child Component + +## Child Components Not supported -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Triggered when

-

type

-

string

-

text

-

No

-

Type of the input component. Available values include text, email, date, time, number, password, button, checkbox, and radio.

-

The text, email, date, time, number, and password types can be dynamically switched and modified.

-

The button, checkbox, and radio types cannot be dynamically modified. Available values include:

-
  • button: a button that can be clicked
  • checkbox: a check box
  • radio: a radio button that allows users to select one from multiple others with the same name
  • text: a single-line text field
  • email: a field used for an email address
  • date: date control, including the year, month, and day, but excluding time
  • time: time control, without the time zone
  • number: field for entering digits
  • password: password field, in which characters will be shielded
    NOTE:

    For wearables, only button, radio, and checkbox types are supported.

    -
    -
-

checked

-

boolean

-

false

-

No

-

Whether the <input> component is selected. This attribute is valid only when type is set to checkbox or radio.

-

name

-

string

-

-

-

No

-

Name of the input component.

-

value

-

string

-

-

-

No

-

Value of the input component. When type is radio, this attribute is mandatory and the value must be unique for radio buttons with the same name.

-

placeholder

-

string

-

-

-

No

-

Content of the hint text. This attribute is available only when the component type is set to text, email, date, time, number, or password.

-

maxlength

-

number

-

-

-

No

-

Maximum number of characters that can be entered in the input box. If no value is specified, the number of characters is not limited.

-

enterkeytype

-

string

-

default

-

No

-

Dynamic modification is not supported.

-

Available values include:

-
  • default
  • next
  • go
  • done
  • send
  • Search
-
NOTE:

The soft keyboard is automatically collapsed after you click the Enter button, except when next is displayed for the button.

-
-

headericon

-

string

-

-

-

No

-

Icon resource path before text input. This icon does not support click events and is unavailable for button, checkbox, and radio types. The supported icon image formats are JPG, PNG, and SVG.

-

showcounter5+

-

boolean

-

false

-

No

-

Whether to display the character counter for an input box. This attribute takes effect only when maxlength is set.

-

menuoptions5+

-

Array<MenuOption>

-

-

-

No

-

Menu options displayed after users touch the More button.

-

autofocus6+

-

boolean

-

false

-

No

-

Whether to automatically obtain the focus.

-
NOTE:

This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the focus method call (for about 100–500 ms) in onActive.

-
-

selectedstart6+

-

number

-

-1

-

No

-

Start position for text selection.

-

selectedend6+

-

number

-

-1

-

No

-

End position for text selection.

-

softkeyboardenabled6+

-

boolean

-

true

-

No

-

Whether to display the soft keyboard during editing.

-

showpasswordicon6+

-

boolean

-

true

-

No

-

Whether to display the icon at the end of the password text box. The setting is valid only when type is set to password.

-
- -**Table 1** MenuOption5+ - - - - - - - - - - - - - - - - -

Name

-

Type

-

Triggered when

-

icon

-

string

-

Path of the icon for a menu option.

-

content

-

string

-

Text content of a menu option.

-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Triggered when

-

color

-

<color>

-

#e6000000

-

No

-

Font color of the single-line text box or button.

-

font-size

-

<length>

-

16px

-

No

-

Font size of the single-line text box or button.

-

allow-scale

-

boolean

-

true

-

No

-

Whether the font size changes with the system's font size settings.

-
NOTE:

If the config-changes tag of fontSize is configured for abilities in the config.json file, the setting takes effect without application restart.

-
-

placeholder-color

-

<color>

-

#99000000

-

No

-

Color of the hint text in the single-line text box. This attribute is available when the component type is set to text, email, date, time, number, or password.

-

font-weight

-

number | string

-

normal

-

No

-

Font weight of the single-line text box or button. For details, see font-weight of the text component.

-

caret-color6+

-

<color>

-

-

-

No

-

Color of the input cursor.

-
- -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - -- When the input component type is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Triggered when

-

change

-

{ value:inputValue }

-

Triggered when the content entered in the text box changes. The most recent text entered by the user is returned.

-
NOTE:

If you change the value attribute directly, this event will not be triggered.

-
-

enterkeyclick

-

{ value:enterKey }

-

Triggered when the Enter key on a soft keyboard is pressed. The type of the Enter key is returned, which is of the number type. Available values are as follows:

-
  • 2: returned if enterkeytype is go.
  • 3: returned if enterkeytype is search.
  • 4: returned if enterkeytype is send.
  • 5: returned if enterkeytype is next.
  • 6: returned if enterkeytype is default, done, or is not set.
-

translate5+

-

{ value: selectedText }

-

Triggered when users click the translate button in the pop menu displayed after they select a text segment. The selected text content is returned.

-

share5+

-

{ value: selectedText }

-

Triggered when users click the share button in the pop menu displayed after they select a text segment. The selected text content is returned.

-

search5+

-

{ value: selectedText }

-

Triggered when users click the search button in the pop menu displayed after they select a text segment. The selected text content is returned.

-

optionselect5+

-

{ index:optionIndex, value: selectedText }

-

Triggered when users click a menu option in the pop menu displayed after they select a text segment. This event is valid only when the menuoptions attribute is set. The option index and selected text content are returned.

-

selectchange6+

-

{ start: number, end: number }

-

Triggered when the text selection changes.

-
- -- When the input component type is set to **checkbox** or **radio**, the following events are supported. - - - - - - - - - - - - -

Name

-

Parameter

-

Triggered when

-

change

-

{ checked:true | false }

-

Triggered when the checked status of the checkbox or radio button changes.

-
- - -## Methods - -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Triggered when

-

focus

-

{focus:true|false}: If focus is not passed, the default value true is used.

-

Obtains or loses the focus of a component. When the component type is set to text, email, date, time, number, or password, the input method can be displayed or collapsed.

-

showError

-

{ error: string }

-

Displays the error message. This attribute is available when the component type is set to text, email, date, time, number, or password.

-

delete6+

-

-

-

Deletes the text content based on the current cursor position when the input component type is set to text, email, date, time, number, or password. If the current input component does not have a cursor, the last character is deleted and the cursor is displayed by default.

-
- -## Example Code - -1. Single-line text box - - ``` - -
- - - -
- ``` - - ``` - /* xxx.css */ - .content { - width: 60%; - flex-direction: column; - align-items: center; - } - .input { - placeholder-color: gray; - } - .button { - background-color: gray; - margin-top: 20px; - } - ``` - - ``` - // xxx.js - import prompt from '@system.prompt' - export default { - change(e){ - prompt.showToast({ - message: "value: " + e.value, - duration: 3000, - }); - }, - enterkeyClick(e){ - prompt.showToast({ - message: "enterkey clicked", - duration: 3000, - }); - }, - buttonClick(e){ - this.$element("input").showError({ - error: 'error text' - }); - }, - } - ``` - - ![](figures/1-2.png) - -2. Common button - - ``` - -
- -
- ``` - - ``` - /* xxx.css */ - .div-button { - flex-direction: column; - align-items: center; - - - } - .button { - margin-top: 30px; - width: 280px; - } - ``` - - ![](figures/en-us_image_0000001198898293.png) - -3. Check box - - ``` - -
- - -
- ``` - - ``` - /* xxx.css */ - .content{ - width: 100%; - height: 200px; - - - align-items: center; - justify-content: center; - } - ``` - - ``` - // xxx.js - import prompt from '@system.prompt' - export default { - checkboxOnChange(e) { - prompt.showToast({ - message:'checked: ' + e.checked, - duration: 3000, - }); - } - } - ``` - - ![](figures/en-us_image_0000001173324749.png) - -4. Radio button - - ``` - -
- - - -
- ``` - - ``` - /* xxx.css */ - .content{ - width: 100%; - height: 200px; - justify-content: center; - align-items: center; - } - ``` - - ``` - // xxx.js - import prompt from '@system.prompt' - export default { - onRadioChange(inputValue, e) { - if (inputValue === e.value) { - prompt.showToast({ - message: 'The chosen radio is ' + e.value, - duration: 3000, - }); - } - } - } - ``` - - ![](figures/1-3.png) +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory| Description | +| -------------------------------- | ----------------------- | --------- | ---- | ------------------------------------------------------------ | +| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded.| +| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | +| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | +| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.| +| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**.| +| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit.| +| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard.| +| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.| +| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | +| menuoptions5+ | Array<MeunOption> | - | No | Menu options displayed after users click the **More** button. | +| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.| +| selectedstart6+ | number | -1 | No | Start position for text selection. | +| selectedend6+ | number | -1 | No | End position for text selection. | +| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | +| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | + +**Table 1** MenuOption5+ + +| Name | Type | Description | +| ------- | ------ | ----------- | +| icon | string | Path of the icon for a menu option.| +| content | string | Text content of a menu option.| + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory| Description | +| ------------------------ | -------------------------- | ---------- | ---- | ------------------------------------------------------------ | +| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | +| font-size | <length> | 16px | No | Font size of the single-line text box or button. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**.| +| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md).| +| caret-color6+ | <color> | - | No | Color of the input cursor. | + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +- When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. + | Name | Parameter | Description | + | ------------------------- | ---------------------------------------- | ---------------------------------------- | + | change | {
 value: inputValue
 } | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered.| + | enterkeyclick | {
 value: enterKey
 } | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.| + | translate5+ | {
 value: selectedText
 } | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.| + | share5+ | {
 value: selectedText
 } | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.| + | search5+ | {
 value: selectedText
 } | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.| + | optionselect5+ | {
 index: optionIndex,
 value: selectedText
 } | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.| + | selectchange6+ | {
start: number,
end: number
 } | Triggered when the text selection changes. | + +- When **type** is set to **checkbox** or **radio**, the following events are supported. + | Name | Parameter | Description | + | ------ | ---------------------------------------- | ---------------------------------------- | + | change | {
 checked:true \| false 
} | Triggered when the checked status of the **checkbox** or **radio** button changes.| + +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| focus | {
 focus: true\|false
 }:
If **focus** is not passed, the default value **true** is used.| Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or password, the input method can be displayed or hidden.| +| showError | {
 error: string 
} | Displays the error message. This attribute is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**.| +| delete6+ | - | Deletes the text content based on the current cursor position when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**; deletes the last character and displays the cursor if the current input component does not have a cursor.| + +## Example + +1. Single-line text box + ```html + +
+ + + +
+ ``` + + ```css + /* xxx.css */ + .content { + width: 60%; + flex-direction: column; + align-items: center; + } + .input { + placeholder-color: gray; + } + .button { + background-color: gray; + margin-top: 20px; + } + ``` + + ```js + // xxx.js + import prompt from '@system.prompt' + export default { + change(e){ + prompt.showToast({ + message: "value: " + e.value, + duration: 3000, + }); + }, + enterkeyClick(e){ + prompt.showToast({ + message: "enterkey clicked", + duration: 3000, + }); + }, + buttonClick(e){ + this.$element("input").showError({ + error: 'error text' + }); + }, + } + ``` + + ![1-2](figures/1-2.png) + +2. Common button + ```html + +
+ +
+ ``` + + ```css + /* xxx.css */ + .div-button { + flex-direction: column; + align-items: center; + } + .button { + margin-top: 30px; + width: 280px; + } + ``` + + ![en-us_image_0000001198898293](figures/en-us_image_0000001198898293.png) + +3. Check box + ```html + +
+ +
+ ``` + + ```css + /* xxx.css */ + .content{ + width: 100%; + height: 200px; + align-items: center; + justify-content: center; + } + ``` + + ```js + // xxx.js + import prompt from '@system.prompt' + export default { + checkboxOnChange(e) { + prompt.showToast({ + message:'checked: ' + e.checked, + duration: 3000, + }); + } + } + ``` + + ![en-us_image_0000001173324749](figures/en-us_image_0000001173324749.png) + +4. Radio button + ```html + +
+ + + +
+ ``` + + ```css + /* xxx.css */ + .content{ + width: 100%; + height: 200px; + justify-content: center; + align-items: center; + } + ``` + + ```js + // xxx.js + import prompt from '@system.prompt' + export default { + onRadioChange(inputValue, e) { + if (inputValue === e.value) { + prompt.showToast({ + message: 'The chosen radio is ' + e.value, + duration: 3000, + }); + } + } + } + ``` + + ![1-3](figures/1-3.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md index 6f8ba597ae293c90835bc5d867ebcb91eaa733ab..9f13895436ce5f1104994f9d6956deba5e04a928 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md @@ -1,215 +1,69 @@ -# marquee +# marquee -The **** component displays single-line scrolling text. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> Since API version 6, the text scrolls only when its width exceeds the width of the **\** component. -## Required Permissions +The **\** component is used to display a scrolling piece of text. + +## Required Permissions None -## Child Component + +## Child Components Not supported -## Attributes -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +## Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

scrollamount

-

number

-

6

-

No

-

Maximum length of each scroll.

-

loop

-

number

-

-1

-

No

-

Number of rolling times. If this parameter is not set, the default value -1 is used. When the value is less than or equal to 0, the marquee scrolls continuously.

-

direction

-

string

-

left

-

No

-

Direction in which the marquee scrolls, which can be left or right.

-
+In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -## Styles +| Name | Type | Default Value | Mandatory | Description | +| ------------ | ------ | ---- | ---- | ---------------------------------------- | +| scrollamount | number | 6 | No | Maximum length of each scroll. | +| loop | number | -1 | No | Number of rolling times. If this parameter is not set, the default value **-1** is used. When the value is less than or equal to **0**, the marquee scrolls continuously.| +| direction | string | left | No | Direction in which the marquee scrolls, which can be **left** or **right**. | -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

color

-

<color>

-

#e5000000

-

No

-

Font color of the scrolling text.

-

font-size

-

<length>

-

37.5

-

No

-

Font size of the scrolling text.

-

allow-scale

-

boolean

-

true

-

No

-

Whether the font size changes with the system's font size settings.

-
NOTE:

If the config-changes tag of fontSize is configured for abilities in the config.json file, the setting takes effect without application restart.

-
-

font-weight

-

number | string

-

normal

-

No

-

Font weight of the scrolling text. For details, see font-weight of the text component.

-

font-family

-

string

-

sans-serif

-

No

-

Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font that exists in the system or the font specified by Custom Font Styles in the family is selected as the font for the text.

-
+## Styles -## Events +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. +| Name | Type | Default Value | Mandatory | Description | +| ----------- | -------------------------- | ---------- | ---- | ---------------------------------------- | +| color | <color> | \#e5000000 | No | Font color of the scrolling text. | +| font-size | <length> | 37.5 | No | Font size of the scrolling text. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\ component](../arkui-js/js-components-basic-text.md#styles)**.| +| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

bounce(Rich)

-

-

-

Triggered when the marquee scrolls to the end.

-

finish(Rich)

-

-

-

Triggered when the marquee finishes the specified number of scrollings (value of the loop attribute). It can be triggered only when the loop attribute is set to a number greater than 0.

-

start(Rich)

-

-

-

Triggered when the marquee starts to scroll.

-
-## Methods +## Events -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

start

-

-

-

Starts scrolling.

-

stop

-

-

-

Stops scrolling.

-
+| Name | Parameter | Description | +| ------------ | ---- | ---------------------------------------- | +| bounce(Rich) | - | Triggered when the marquee scrolls to the end. | +| finish(Rich) | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.| +| start(Rich) | - | Triggered when the marquee starts to scroll. | -## Example Code +## Methods -``` +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ----- | ---- | ----- | +| start | - | Starts scrolling.| +| stop | - | Stops scrolling.| + + +## Example + +```html
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -252,7 +106,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods. } ``` -``` +```js // xxx.js export default { data: { @@ -279,5 +133,4 @@ export default { } ``` -![](figures/lite_bar.gif) - +![lite_bar](figures/lite_bar.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md index 7c925bad746aad5bbade92971de79b1a8063d071..426e227f9009c06b9e6c82f3344719c9d988e948 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md @@ -1,577 +1,128 @@ -# picker-view +# picker-view -The **** component provides the view that shows an embedded scrollable selector on the screen. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Child Components +The **\** component provides the view that shows an embedded scrollable selector on the screen. + + +## Child Components Not supported -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

text

-

No

-

Type of the scrollable selector, which cannot be changed dynamically. Available values are as follows:

-
  • text: text selector
  • time: time selector
  • date: date selector
  • datetime: date and time selector
  • multi-text: multi-column text selector
-
- -Text selector \(**type** is **text**\) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

range

-

Array

-

-

-

No

-

Value range of the text selector.

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: ["15", "20", "25"] in JavaScript.

-
-

selected

-

string

-

0

-

No

-

Default value of the text selector. The value is the index of range.

-

indicatorprefix

-

string

-

-

-

No

-

Prefix field added when a value is specified for the text selector.

-

indicatorsuffix

-

string

-

-

-

No

-

Suffix field added when a value is specified for the text selector.

-
- -Time selector \(**type** is **time**\) - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

containsecond

-

boolean

-

false

-

No

-

Whether seconds are contained.

-

selected

-

string

-

Current time

-

No

-

Default value of the time selector, in the format of HH:mm.

-

If seconds are contained, the format is HH:mm:ss.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-
- -Date selector \(**type** is **date**\) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

start

-

<time>

-

1970-1-1

-

No

-

Start date of the date selector, in the format of YYYY-MM-DD.

-

end

-

<time>

-

2100-12-31

-

No

-

End date of the date selector, in the format of YYYY-MM-DD.

-

selected

-

string

-

Current date

-

No

-

Default value of the date selector, in the format of YYYY-MM-DD.

-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether to display the lunar calendar switch in the date selector. When this switch is displayed, you can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.

-
NOTE:

-
-
- -Date and time selector \(**type** is **datetime**\) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

selected

-

string

-

Current date and time

-

No

-

Default value of the date and time selector. The value can be in the format of MM-DD-HH-mm or YYYY-MM-DD-HH-mm. If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the date and time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether to display the lunar calendar switch in the date and time selector. When this switch is displayed, you can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.

-
NOTE:

-

-
- -Multi-column text selector \(**type** is **multi-text**\) - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

columns

-

number

-

-

-

Yes

-

Number of columns in the multi-column text selector.

-

range

-

Two-dimensional array

-

-

-

No

-

Items of the multi-column text selector. range is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, [["a","b"], ["c","d"]].

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: [["a","b"], ["c","d"]] in the JavaScript.

-
-

selected

-

Array

-

0,0,0,...

-

No

-

Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.

-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

color

-

<color>

-

#ffffff

-

No

-

Font color of a candidate item.

-

font-size

-

<length>

-

16px

-

No

-

Font size of a candidate item. The value is of the length type, in pixels.

-

selected-color

-

<color>

-

#ff0a69f7

-

No

-

Font color of the selected item.

-

selected-font-size

-

<length>

-

20px

-

No

-

Font size of the selected item. The value is of the length type, in pixels.

-

disappear-color5+

-

<color>

-

#ffffff

-

No

-

Font color of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total.

-
NOTE:

-
-

disappear-font-size5+

-

<length>

-

14px

-

No

-

Font size of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total.

-
NOTE:

-
-

font-family

-

string

-

sans-serif

-

No

-

Font type of an item. Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the font specified by Custom Font Styles is used for the text

-
- -## Events + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| type | string | text | No | Type of the scrollable selector, which cannot be changed dynamically. Available values are as follows:
- **text**: text selector.
- **time**: time selector.
- **date**: date selector.
- **datetime**: date and time selector.
- **multi-text**: multi-column text selector.| + +Text selector (**type** is **text**) + +| Name | Type | Default Value | Mandatory | Description | +| --------------- | ------ | ---- | ---- | ---------------------------------------- | +| range | Array | - | No | Value range of the text selector.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | string | 0 | No | Default value of the text selector. The value is the index of **range**. | +| indicatorprefix | string | - | No | Prefix field added when a value is specified for the text selector. | +| indicatorsuffix | string | - | No | Suffix field added when a value is specified for the text selector. | + +Time selector (**type** is **time**) + +| Name | Type | Default Value | Mandatory | Description | +| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| containsecond | boolean | false | No | Whether seconds are contained. | +| selected | string | Current time | No | Default value of the time selector, in the format of HH:mm.
If seconds are contained, the format is HH:mm:ss.| +| hours | number | 241-4 | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| + +Date selector (**type** is **date**) + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------------ | ---------- | ---- | ---------------------------------------- | +| start | <time> | 1970-1-1 | No | Start date of the date selector, in the format of YYYY-MM-DD. | +| end | <time> | 2100-12-31 | No | End date of the date selector, in the format of YYYY-MM-DD. | +| selected | string | Current date | No | Default value of the date selector, in the format of YYYY-MM-DD. | +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.| + +Date and time selector (**type** is **datetime**) + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in the format of MM-DD-HH-mm or YYYY-MM-DD-HH-mm. If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.| +| hours | number | 241-4 | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date and time selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.| + +Multi-column text selector (**type** is **multi-text**) + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------- | --------- | ---- | ---------------------------------------- | +| columns | number | - | Yes | Number of columns in the multi-column text selector. | +| range | Two-dimensional array| - | No | Items of the multi-column text selector. The value is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, **[["a", "b"], ["c", "d"]]**.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | Array | [0,0,0,…]| No | Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.| + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| -------------------------------- | -------------- | ---------- | ---- | ---------------------------------------- | +| color | <color> | \#ffffff | No | Font color of a candidate item. | +| font-size | <length> | 16px | No | Font size of a candidate item. The value is of the length type, in pixels. | +| selected-color | <color> | #ff0a69f7 | No | Font color of the selected item. | +| selected-font-size | <length> | 20px | No | Font size of the selected item. The value is of the length type, in pixels. | +| disappear-color5+ | <color> | \#ffffff | No | Font color of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. | +| disappear-font-size5+ | <length> | 14px | No | Font size of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. | +| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| + + +## Events The following events are supported. -Text selector \(**type** is **text**\) - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ newValue: newValue, newSelected: newSelected }

-

Triggered when a value is specified for the text selector.

-
- -Time selector \(**type** is **time**\) - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ hour: hour, minute: minute, [second:second] }

-

Triggered when a value is specified for the time selector.

-

If seconds are contained, the value contains hour, minute, and second.

-
- -Date selector \(**type** is **date**\) - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year:year, month:month, day:day }

-

Triggered when a value is specified for the date selector.

-
- -Date and time selector \(**type** is **datetime**\) - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year:year, month:month, day:day, hour:hour, minute:minute }

-

Triggered when a value is specified for the date and time selector.

-
- -Multi-text selector \(**type** is **multi-text**\) - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

columnchange

-

{ column:column, newValue:newValue, newSelected:newSelected }

-

Triggered when the value of a column in the multi-column selector changes. column indicates the column whose value has changed, newValue indicates the selected value, and newSelected indicates the index of the selected value.

-
- -## Methods +Text selector (**type** is **text**) + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | --------------- | +| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.| + +Time selector (**type** is **time**) + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ------------------------------- | +| change | { hour: hour, minute: minute, [second:second]} | Triggered when a value is specified for the time selector.
If seconds are contained, the value contains hour, minute, and second.| + +Date selector (**type** is **date**) + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | --------------- | +| change | { year:year, month:month, day:day } | Triggered when a value is specified for the date selector.| + +Date and time selector (**type** is **datetime**) + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ----------------- | +| change | { year:year, month:month, day:day,  hour:hour, minute:minute } | Triggered when a value is specified for the date and time selector.| + +Multi-text selector (**type** is **multi-text**) + +| Name | Parameter | Description | +| ------------ | ---------------------------------------- | ---------------------------------------- | +| columnchange | { column:column, newValue:newValue, newSelected:newSelected } | Triggered when the value of a column in the multi-column selector changes.
**column**: column whose value has changed.
**newValue**: selected value.
**newSelected**: index of the selected value.| + + +## Methods Not supported -## Example Code -``` +## Example + +```html
@@ -581,7 +132,7 @@ Not supported
``` -``` +```css /* xxx.css */ .container { flex-direction: column; @@ -603,7 +154,7 @@ Not supported } ``` -``` +```js /* xxx.js */ export default { data: { @@ -633,5 +184,4 @@ export default { } ``` -![](figures/lite_bar-4.png) - +![lite_bar-4](figures/lite_bar-4.png) diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 6b9270ec688ba6470e5bcde047ea964c15b209bb..a487890669ef23b80304bf82afff664a2008da05 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) + - [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) - 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 **\